diff options
author | Dimitry Andric <dim@FreeBSD.org> | 2018-08-02 17:33:11 +0000 |
---|---|---|
committer | Dimitry Andric <dim@FreeBSD.org> | 2018-08-02 17:33:11 +0000 |
commit | c7e70c433efc6953dc3888b9fbf9f3512d7da2b0 (patch) | |
tree | 27425930fc0c91650a7f3527fcac8e0f92907b90 | |
parent | 486754660bb926339aefcf012a3f848592babb8b (diff) |
Vendor import of clang trunk r338536:vendor/clang/clang-trunk-r338536
Notes
Notes:
svn path=/vendor/clang/dist/; revision=337139
svn path=/vendor/clang/clang-trunk-r338536/; revision=337140; tag=vendor/clang/clang-trunk-r338536
596 files changed, 13281 insertions, 9217 deletions
diff --git a/docs/ClangFormatStyleOptions.rst b/docs/ClangFormatStyleOptions.rst index e4892d79b91f..49f9f68088bc 100644 --- a/docs/ClangFormatStyleOptions.rst +++ b/docs/ClangFormatStyleOptions.rst @@ -1134,17 +1134,21 @@ the configuration (without a prefix: ``Auto``). .. code-block:: c++ true: - SomeClass::Constructor() - : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa) { - return 0; - } + FitsOnOneLine::Constructor() + : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {} + + DoesntFit::Constructor() + : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), + aaaaaaaaaaaaa(aaaaaaaaaaaaaa), + aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {} false: - SomeClass::Constructor() - : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), - aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa) { - return 0; - } + FitsOnOneLine::Constructor() + : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {} + + DoesntFit::Constructor() + : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa), + aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {} **ConstructorInitializerIndentWidth** (``unsigned``) The number of characters to use for indentation of constructor diff --git a/docs/ReleaseNotes.rst b/docs/ReleaseNotes.rst index 342fed3393b1..1e45a13ef916 100644 --- a/docs/ReleaseNotes.rst +++ b/docs/ReleaseNotes.rst @@ -46,7 +46,9 @@ sections with improvements to Clang's support for those languages. Major New Features ------------------ -- ... +- A new Implicit Conversion Sanitizer (``-fsanitize=implicit-conversion``) group + was added. Please refer to the :ref:`release-notes-ubsan` section of the + release notes for the details. Improvements to Clang's diagnostics ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -280,10 +282,36 @@ Static Analyzer ... +.. _release-notes-ubsan: + Undefined Behavior Sanitizer (UBSan) ------------------------------------ -* ... +* A new Implicit Conversion Sanitizer (``-fsanitize=implicit-conversion``) group + was added. + + Currently, only one type of issues is caught - implicit integer truncation + (``-fsanitize=implicit-integer-truncation``), also known as integer demotion. + While there is a ``-Wconversion`` diagnostic group that catches this kind of + issues, it is both noisy, and does not catch **all** the cases. + + .. code-block:: c++ + + unsigned char store = 0; + + bool consume(unsigned int val); + + void test(unsigned long val) { + if (consume(val)) // the value may have been silently truncated. + store = store + 768; // before addition, 'store' was promoted to int. + (void)consume((unsigned int)val); // OK, the truncation is explicit. + } + + Just like other ``-fsanitize=integer`` checks, these issues are **not** + undefined behaviour. But they are not *always* intentional, and are somewhat + hard to track down. This group is **not** enabled by ``-fsanitize=undefined``, + but the ``-fsanitize=implicit-integer-truncation`` check + is enabled by ``-fsanitize=integer``. Core Analysis Improvements ========================== diff --git a/docs/UndefinedBehaviorSanitizer.rst b/docs/UndefinedBehaviorSanitizer.rst index 71a8ebd4bc64..86d0193a23c2 100644 --- a/docs/UndefinedBehaviorSanitizer.rst +++ b/docs/UndefinedBehaviorSanitizer.rst @@ -89,6 +89,12 @@ Available checks are: - ``-fsanitize=function``: Indirect call of a function through a function pointer of the wrong type (Darwin/Linux, C++ and x86/x86_64 only). + - ``-fsanitize=implicit-integer-truncation``: Implicit conversion from + integer of larger bit width to smaller bit width, if that results in data + loss. That is, if the demoted value, after casting back to the original + width, is not equal to the original value before the downcast. + Issues caught by this sanitizer are not undefined behavior, + but are often unintentional. - ``-fsanitize=integer-divide-by-zero``: Integer division by zero. - ``-fsanitize=nonnull-attribute``: Passing null pointer as a function parameter which is declared to never be null. @@ -121,15 +127,21 @@ Available checks are: unsigned overflow in C++. You can use ``-fsanitize=shift-base`` or ``-fsanitize=shift-exponent`` to check only left-hand side or right-hand side of shift operation, respectively. - - ``-fsanitize=signed-integer-overflow``: Signed integer overflow, - including all the checks added by ``-ftrapv``, and checking for - overflow in signed division (``INT_MIN / -1``). + - ``-fsanitize=signed-integer-overflow``: Signed integer overflow, where the + result of a signed integer computation cannot be represented in its type. + This includes all the checks covered by ``-ftrapv``, as well as checks for + signed division overflow (``INT_MIN/-1``), but not checks for + lossy implicit conversions performed before the computation + (see ``-fsanitize=implicit-conversion``). Both of these two issues are + handled by ``-fsanitize=implicit-conversion`` group of checks. - ``-fsanitize=unreachable``: If control flow reaches an unreachable program point. - - ``-fsanitize=unsigned-integer-overflow``: Unsigned integer - overflows. Note that unlike signed integer overflow, unsigned integer - is not undefined behavior. However, while it has well-defined semantics, - it is often unintentional, so UBSan offers to catch it. + - ``-fsanitize=unsigned-integer-overflow``: Unsigned integer overflow, where + the result of an unsigned integer computation cannot be represented in its + type. Unlike signed integer overflow, this is not undefined behavior, but + it is often unintentional. This sanitizer does not check for lossy implicit + conversions performed before such a computation + (see ``-fsanitize=implicit-conversion``). - ``-fsanitize=vla-bound``: A variable-length array whose bound does not evaluate to a positive value. - ``-fsanitize=vptr``: Use of an object whose vptr indicates that it is of @@ -140,11 +152,17 @@ Available checks are: You can also use the following check groups: - ``-fsanitize=undefined``: All of the checks listed above other than - ``unsigned-integer-overflow`` and the ``nullability-*`` checks. + ``unsigned-integer-overflow``, ``implicit-conversion`` and the + ``nullability-*`` group of checks. - ``-fsanitize=undefined-trap``: Deprecated alias of ``-fsanitize=undefined``. - ``-fsanitize=integer``: Checks for undefined or suspicious integer behavior (e.g. unsigned integer overflow). + Enables ``signed-integer-overflow``, ``unsigned-integer-overflow``, + ``shift``, ``integer-divide-by-zero``, and ``implicit-integer-truncation``. + - ``-fsanitize=implicit-conversion``: Checks for suspicious behaviours of + implicit conversions. + Currently, only ``-fsanitize=implicit-integer-truncation`` is implemented. - ``-fsanitize=nullability``: Enables ``nullability-arg``, ``nullability-assign``, and ``nullability-return``. While violating nullability does not have undefined behavior, it is often unintentional, diff --git a/docs/UsersManual.rst b/docs/UsersManual.rst index 418afb2d546c..363bb4e461a6 100644 --- a/docs/UsersManual.rst +++ b/docs/UsersManual.rst @@ -2155,13 +2155,8 @@ Objective-C++ Language Features OpenMP Features =============== -Clang supports all OpenMP 3.1 directives and clauses. In addition, some -features of OpenMP 4.0 are supported. For example, ``#pragma omp simd``, -``#pragma omp for simd``, ``#pragma omp parallel for simd`` directives, extended -set of atomic constructs, ``proc_bind`` clause for all parallel-based -directives, ``depend`` clause for ``#pragma omp task`` directive (except for -array sections), ``#pragma omp cancel`` and ``#pragma omp cancellation point`` -directives, and ``#pragma omp taskgroup`` directive. +Clang supports all OpenMP 4.5 directives and clauses. See :doc:`OpenMPSupport` +for additional details. Use `-fopenmp` to enable OpenMP. Support for OpenMP can be disabled with `-fno-openmp`. @@ -2783,6 +2778,7 @@ Execute ``clang-cl /?`` to see a list of supported options: /Brepro Emit an object file which can be reproduced over time /C Don't discard comments when preprocessing /c Compile only + /d1PP Retain macro definitions in /E mode /d1reportAllClassLayout Dump record layout information /diagnostics:caret Enable caret and column diagnostics (on by default) /diagnostics:classic Disable column and caret diagnostics @@ -2816,6 +2812,7 @@ Execute ``clang-cl /?`` to see a list of supported options: /GS- Disable buffer security check /GS Enable buffer security check /Gs<value> Set stack probe size + /guard:<value> Enable Control Flow Guard with /guard:cf /Gv Set __vectorcall as a default calling convention /Gw- Don't put each data item in its own section /Gw Put each data item in its own section @@ -2871,6 +2868,7 @@ Execute ``clang-cl /?`` to see a list of supported options: /WX- Do not treat warnings as errors /WX Treat warnings as errors /w Disable all warnings + /X Don't add %INCLUDE% to the include search path /Y- Disable precompiled headers, overrides /Yc and /Yu /Yc<filename> Generate a pch file for all code up to and including <filename> /Yu<filename> Load a pch file and use it instead of all code up to and including <filename> @@ -2894,8 +2892,15 @@ Execute ``clang-cl /?`` to see a list of supported options: OPTIONS: -### Print (but do not run) the commands to run for this compilation --analyze Run the static analyzer + -faddrsig Emit an address-significance table -fansi-escape-codes Use ANSI escape codes for diagnostics + -fblocks Enable the 'blocks' language feature + -fcf-protection=<value> Instrument control-flow architecture protection. Options: return, branch, full, none. + -fcf-protection Enable cf-protection in 'full' mode -fcolor-diagnostics Use colors in diagnostics + -fcomplete-member-pointers + Require member pointer base types to be complete if they would be significant under the Microsoft ABI + -fcoverage-mapping Generate coverage mapping to enable code coverage analysis -fdebug-macro Emit macro debug information -fdelayed-template-parsing Parse templated function definitions at the end of the translation unit @@ -2905,6 +2910,7 @@ Execute ``clang-cl /?`` to see a list of supported options: Print fix-its in machine parseable form -flto=<value> Set LTO mode to either 'full' or 'thin' -flto Enable LTO in 'full' mode + -fmerge-all-constants Allow merging of constants -fms-compatibility-version=<value> Dot-separated value representing the Microsoft compiler version number to report in _MSC_VER (0 = don't define it (default)) @@ -2912,9 +2918,17 @@ Execute ``clang-cl /?`` to see a list of supported options: -fms-extensions Accept some non-standard constructs supported by the Microsoft compiler -fmsc-version=<value> Microsoft compiler version number to report in _MSC_VER (0 = don't define it (default)) + -fno-addrsig Don't emit an address-significance table + -fno-builtin-<value> Disable implicit builtin knowledge of a specific function + -fno-builtin Disable implicit builtin knowledge of functions + -fno-complete-member-pointers + Do not require member pointer base types to be complete if they would be significant under the Microsoft ABI + -fno-coverage-mapping Disable code coverage analysis -fno-debug-macro Do not emit macro debug information -fno-delayed-template-parsing Disable delayed template parsing + -fno-sanitize-address-poison-class-member-array-new-cookie + Disable poisoning array cookies when using class member operator new[] in AddressSanitizer -fno-sanitize-address-use-after-scope Disable use-after-scope detection in AddressSanitizer -fno-sanitize-blacklist Don't use blacklist file for sanitizers @@ -2950,6 +2964,8 @@ Execute ``clang-cl /?`` to see a list of supported options: Level of field padding for AddressSanitizer -fsanitize-address-globals-dead-stripping Enable linker dead stripping of globals in AddressSanitizer + -fsanitize-address-poison-class-member-array-new-cookie + Enable poisoning array cookies when using class member operator new[] in AddressSanitizer -fsanitize-address-use-after-scope Enable use-after-scope detection in AddressSanitizer -fsanitize-blacklist=<value> diff --git a/include/clang-c/Index.h b/include/clang-c/Index.h index 0ad90010ccd9..65dada38b050 100644 --- a/include/clang-c/Index.h +++ b/include/clang-c/Index.h @@ -160,7 +160,7 @@ typedef struct CXVersion { int Major; /** * The minor version number, e.g., the '7' in '10.7.3'. This value - * will be negative if no minor version number was provided, e.g., for + * will be negative if no minor version number was provided, e.g., for * version '10'. */ int Minor; @@ -387,7 +387,7 @@ CINDEX_LINKAGE int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID); * multiple inclusions, either with the conventional * \#ifndef/\#define/\#endif macro guards or with \#pragma once. */ -CINDEX_LINKAGE unsigned +CINDEX_LINKAGE unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file); /** @@ -786,7 +786,7 @@ typedef void *CXDiagnostic; * A group of CXDiagnostics. */ typedef void *CXDiagnosticSet; - + /** * Determine the number of diagnostics in a CXDiagnosticSet. */ @@ -802,7 +802,7 @@ CINDEX_LINKAGE unsigned clang_getNumDiagnosticsInSet(CXDiagnosticSet Diags); * via a call to \c clang_disposeDiagnostic(). */ CINDEX_LINKAGE CXDiagnostic clang_getDiagnosticInSet(CXDiagnosticSet Diags, - unsigned Index); + unsigned Index); /** * Describes the kind of error that occurred (if any) in a call to @@ -813,26 +813,26 @@ enum CXLoadDiag_Error { * Indicates that no error occurred. */ CXLoadDiag_None = 0, - + /** * Indicates that an unknown error occurred while attempting to * deserialize diagnostics. */ CXLoadDiag_Unknown = 1, - + /** * Indicates that the file containing the serialized diagnostics * could not be opened. */ CXLoadDiag_CannotLoad = 2, - + /** * Indicates that the serialized diagnostics file is invalid or * corrupt. */ CXLoadDiag_InvalidFile = 3 }; - + /** * Deserialize a set of diagnostics from a Clang diagnostics bitcode * file. @@ -856,7 +856,7 @@ CINDEX_LINKAGE CXDiagnosticSet clang_loadDiagnostics(const char *file, CINDEX_LINKAGE void clang_disposeDiagnosticSet(CXDiagnosticSet Diags); /** - * Retrieve the child diagnostics of a CXDiagnostic. + * Retrieve the child diagnostics of a CXDiagnostic. * * This CXDiagnosticSet does not need to be released by * clang_disposeDiagnosticSet. @@ -888,7 +888,7 @@ CINDEX_LINKAGE CXDiagnostic clang_getDiagnostic(CXTranslationUnit Unit, * \param Unit the translation unit to query. */ CINDEX_LINKAGE CXDiagnosticSet - clang_getDiagnosticSetFromTU(CXTranslationUnit Unit); + clang_getDiagnosticSetFromTU(CXTranslationUnit Unit); /** * Destroy a diagnostic. @@ -934,7 +934,7 @@ enum CXDiagnosticDisplayOptions { * \c -fdiagnostics-print-source-range-info. */ CXDiagnostic_DisplaySourceRanges = 0x04, - + /** * Display the option name associated with this diagnostic, if any. * @@ -943,12 +943,12 @@ enum CXDiagnosticDisplayOptions { * \c -fdiagnostics-show-option. */ CXDiagnostic_DisplayOption = 0x08, - + /** * Display the category number associated with this diagnostic, if any. * * The category number is displayed within brackets after the diagnostic text. - * This option corresponds to the clang flag + * This option corresponds to the clang flag * \c -fdiagnostics-show-category=id. */ CXDiagnostic_DisplayCategoryId = 0x10, @@ -957,7 +957,7 @@ enum CXDiagnosticDisplayOptions { * Display the category name associated with this diagnostic, if any. * * The category name is displayed within brackets after the diagnostic text. - * This option corresponds to the clang flag + * This option corresponds to the clang flag * \c -fdiagnostics-show-category=name. */ CXDiagnostic_DisplayCategoryName = 0x20 @@ -1019,7 +1019,7 @@ CINDEX_LINKAGE CXString clang_getDiagnosticSpelling(CXDiagnostic); * diagnostic (if any). * * \returns A string that contains the command-line option used to enable this - * warning, such as "-Wconversion" or "-pedantic". + * warning, such as "-Wconversion" or "-pedantic". */ CINDEX_LINKAGE CXString clang_getDiagnosticOption(CXDiagnostic Diag, CXString *Disable); @@ -1028,7 +1028,7 @@ CINDEX_LINKAGE CXString clang_getDiagnosticOption(CXDiagnostic Diag, * Retrieve the category number for this diagnostic. * * Diagnostics can be categorized into groups along with other, related - * diagnostics (e.g., diagnostics under the same warning flag). This routine + * diagnostics (e.g., diagnostics under the same warning flag). This routine * retrieves the category number for the given diagnostic. * * \returns The number of the category that contains this diagnostic, or zero @@ -1041,7 +1041,7 @@ CINDEX_LINKAGE unsigned clang_getDiagnosticCategory(CXDiagnostic); * is now deprecated. Use clang_getDiagnosticCategoryText() * instead. * - * \param Category A diagnostic category number, as returned by + * \param Category A diagnostic category number, as returned by * \c clang_getDiagnosticCategory(). * * \returns The name of the given diagnostic category. @@ -1055,7 +1055,7 @@ CXString clang_getDiagnosticCategoryName(unsigned Category); * \returns The text of the given diagnostic category. */ CINDEX_LINKAGE CXString clang_getDiagnosticCategoryText(CXDiagnostic); - + /** * Determine the number of source ranges associated with the given * diagnostic. @@ -1242,9 +1242,9 @@ enum CXTranslationUnit_Flags { * intent of producing a precompiled header. */ CXTranslationUnit_Incomplete = 0x02, - + /** - * Used to indicate that the translation unit should be built with an + * Used to indicate that the translation unit should be built with an * implicit precompiled header for the preamble. * * An implicit precompiled header is used as an optimization when a @@ -1258,7 +1258,7 @@ enum CXTranslationUnit_Flags { * precompiled header to improve parsing performance. */ CXTranslationUnit_PrecompiledPreamble = 0x04, - + /** * Used to indicate that the translation unit should cache some * code-completion results with each reparse of the source file. @@ -1343,7 +1343,7 @@ enum CXTranslationUnit_Flags { * to indicate that the translation unit is likely to be reparsed many times, * either explicitly (via \c clang_reparseTranslationUnit()) or implicitly * (e.g., by code completion (\c clang_codeCompletionAt())). The returned flag - * set contains an unspecified set of optimizations (e.g., the precompiled + * set contains an unspecified set of optimizations (e.g., the precompiled * preamble) geared toward improving the performance of these routines. The * set of optimizations enabled may change from one version to the next. */ @@ -1374,7 +1374,7 @@ clang_parseTranslationUnit(CXIndex CIdx, * command-line arguments so that the compilation can be configured in the same * way that the compiler is configured on the command line. * - * \param CIdx The index object with which the translation unit will be + * \param CIdx The index object with which the translation unit will be * associated. * * \param source_filename The name of the source file to load, or NULL if the @@ -1383,7 +1383,7 @@ clang_parseTranslationUnit(CXIndex CIdx, * \param command_line_args The command-line arguments that would be * passed to the \c clang executable if it were being invoked out-of-process. * These command-line options will be parsed and will affect how the translation - * unit is parsed. Note that the following options are ignored: '-c', + * unit is parsed. Note that the following options are ignored: '-c', * '-emit-ast', '-fsyntax-only' (which is the default), and '-o \<output file>'. * * \param num_command_line_args The number of command-line arguments in @@ -1463,32 +1463,32 @@ enum CXSaveError { * Indicates that no error occurred while saving a translation unit. */ CXSaveError_None = 0, - + /** * Indicates that an unknown error occurred while attempting to save * the file. * - * This error typically indicates that file I/O failed when attempting to + * This error typically indicates that file I/O failed when attempting to * write the file. */ CXSaveError_Unknown = 1, - + /** * Indicates that errors during translation prevented this attempt * to save the translation unit. - * + * * Errors that prevent the translation unit from being saved can be * extracted using \c clang_getNumDiagnostics() and \c clang_getDiagnostic(). */ CXSaveError_TranslationErrors = 2, - + /** * Indicates that the translation unit to be saved was somehow * invalid (e.g., NULL). */ CXSaveError_InvalidTU = 3 }; - + /** * Saves a translation unit into a serialized representation of * that translation unit on disk. @@ -1509,7 +1509,7 @@ enum CXSaveError { * CXSaveTranslationUnit_XXX flags. * * \returns A value that will match one of the enumerators of the CXSaveError - * enumeration. Zero (CXSaveError_None) indicates that the translation unit was + * enumeration. Zero (CXSaveError_None) indicates that the translation unit was * saved successfully, while a non-zero value indicates that a problem occurred. */ CINDEX_LINKAGE int clang_saveTranslationUnit(CXTranslationUnit TU, @@ -1543,7 +1543,7 @@ enum CXReparse_Flags { */ CXReparse_None = 0x0 }; - + /** * Returns the set of flags that is suitable for reparsing a translation * unit. @@ -1551,7 +1551,7 @@ enum CXReparse_Flags { * The set of flags returned provide options for * \c clang_reparseTranslationUnit() by default. The returned flag * set contains an unspecified set of optimizations geared toward common uses - * of reparsing. The set of optimizations enabled may change from one version + * of reparsing. The set of optimizations enabled may change from one version * to the next. */ CINDEX_LINKAGE unsigned clang_defaultReparseOptions(CXTranslationUnit TU); @@ -1563,17 +1563,17 @@ CINDEX_LINKAGE unsigned clang_defaultReparseOptions(CXTranslationUnit TU); * created the given translation unit, for example because those source files * have changed (either on disk or as passed via \p unsaved_files). The * source code will be reparsed with the same command-line options as it - * was originally parsed. + * was originally parsed. * * Reparsing a translation unit invalidates all cursors and source locations * that refer into that translation unit. This makes reparsing a translation * unit semantically equivalent to destroying the translation unit and then * creating a new translation unit with the same command-line arguments. - * However, it may be more efficient to reparse a translation + * However, it may be more efficient to reparse a translation * unit using this routine. * * \param TU The translation unit whose contents will be re-parsed. The - * translation unit must originally have been built with + * translation unit must originally have been built with * \c clang_createTranslationUnitFromSourceFile(). * * \param num_unsaved_files The number of unsaved file entries in \p @@ -1584,7 +1584,7 @@ CINDEX_LINKAGE unsigned clang_defaultReparseOptions(CXTranslationUnit TU); * those files. The contents and name of these files (as specified by * CXUnsavedFile) are copied when necessary, so the client only needs to * guarantee their validity until the call to this function returns. - * + * * \param options A bitset of options composed of the flags in CXReparse_Flags. * The function \c clang_defaultReparseOptions() produces a default set of * options recommended for most uses, based on the translation unit. @@ -1612,8 +1612,8 @@ enum CXTUResourceUsageKind { CXTUResourceUsage_AST_SideTables = 6, CXTUResourceUsage_SourceManager_Membuffer_Malloc = 7, CXTUResourceUsage_SourceManager_Membuffer_MMap = 8, - CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc = 9, - CXTUResourceUsage_ExternalASTSource_Membuffer_MMap = 10, + CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc = 9, + CXTUResourceUsage_ExternalASTSource_Membuffer_MMap = 10, CXTUResourceUsage_Preprocessor = 11, CXTUResourceUsage_PreprocessingRecord = 12, CXTUResourceUsage_SourceManager_DataStructures = 13, @@ -1635,8 +1635,8 @@ const char *clang_getTUResourceUsageName(enum CXTUResourceUsageKind kind); typedef struct CXTUResourceUsageEntry { /* The memory usage category. */ - enum CXTUResourceUsageKind kind; - /* Amount of resources used. + enum CXTUResourceUsageKind kind; + /* Amount of resources used. The units will depend on the resource kind. */ unsigned long amount; } CXTUResourceUsageEntry; @@ -1819,7 +1819,7 @@ enum CXCursorKind { */ CXCursor_TypeRef = 43, CXCursor_CXXBaseSpecifier = 44, - /** + /** * A reference to a class template, function template, template * template parameter, or class template partial specialization. */ @@ -1829,14 +1829,14 @@ enum CXCursorKind { */ CXCursor_NamespaceRef = 46, /** - * A reference to a member of a struct, union, or class that occurs in + * A reference to a member of a struct, union, or class that occurs in * some non-expression context, e.g., a designated initializer. */ CXCursor_MemberRef = 47, /** * A reference to a labeled statement. * - * This cursor kind is used to describe the jump to "start_over" in the + * This cursor kind is used to describe the jump to "start_over" in the * goto statement in the following example: * * \code @@ -1849,7 +1849,7 @@ enum CXCursorKind { * A label reference cursor refers to a label statement. */ CXCursor_LabelRef = 48, - + /** * A reference to a set of overloaded functions or function templates * that has not yet been resolved to a specific function or function template. @@ -1882,18 +1882,18 @@ enum CXCursorKind { * argument-dependent lookup (e.g., the "swap" function at the end of the * example). * - * The functions \c clang_getNumOverloadedDecls() and + * The functions \c clang_getNumOverloadedDecls() and * \c clang_getOverloadedDecl() can be used to retrieve the definitions * referenced by this cursor. */ CXCursor_OverloadedDeclRef = 49, - + /** - * A reference to a variable that occurs in some non-expression + * A reference to a variable that occurs in some non-expression * context, e.g., a C++ lambda capture list. */ CXCursor_VariableRef = 50, - + CXCursor_LastRef = CXCursor_VariableRef, /* Error conditions */ @@ -2153,7 +2153,7 @@ enum CXCursorKind { * \endcode */ CXCursor_LambdaExpr = 144, - + /** Objective-c Boolean Literal. */ CXCursor_ObjCBoolLiteralExpr = 145, @@ -2189,10 +2189,10 @@ enum CXCursorKind { * reported. */ CXCursor_UnexposedStmt = 200, - - /** A labelled statement in a function. + + /** A labelled statement in a function. * - * This cursor kind is used to describe the "start_over:" label statement in + * This cursor kind is used to describe the "start_over:" label statement in * the following example: * * \code @@ -2650,7 +2650,7 @@ CINDEX_LINKAGE int clang_Cursor_isNull(CXCursor cursor); * Compute a hash value for the given cursor. */ CINDEX_LINKAGE unsigned clang_hashCursor(CXCursor); - + /** * Retrieve the kind of the given cursor. */ @@ -2718,7 +2718,7 @@ CINDEX_LINKAGE unsigned clang_isTranslationUnit(enum CXCursorKind); * element, such as a preprocessor directive or macro instantiation. */ CINDEX_LINKAGE unsigned clang_isPreprocessing(enum CXCursorKind); - + /*** * Determine whether the given cursor represents a currently * unexposed piece of the AST (e.g., CXCursor_UnexposedStmt). @@ -2785,7 +2785,7 @@ CINDEX_LINKAGE enum CXVisibilityKind clang_getCursorVisibility(CXCursor cursor); * * \returns The availability of the cursor. */ -CINDEX_LINKAGE enum CXAvailabilityKind +CINDEX_LINKAGE enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor); /** @@ -2831,10 +2831,10 @@ typedef struct CXPlatformAvailability { * * \param cursor The cursor to query. * - * \param always_deprecated If non-NULL, will be set to indicate whether the + * \param always_deprecated If non-NULL, will be set to indicate whether the * entity is deprecated on all platforms. * - * \param deprecated_message If non-NULL, will be set to the message text + * \param deprecated_message If non-NULL, will be set to the message text * provided along with the unconditional deprecation of this entity. The client * is responsible for deallocating this string. * @@ -2842,7 +2842,7 @@ typedef struct CXPlatformAvailability { * entity is unavailable on all platforms. * * \param unavailable_message If non-NULL, will be set to the message text - * provided along with the unconditional unavailability of this entity. The + * provided along with the unconditional unavailability of this entity. The * client is responsible for deallocating this string. * * \param availability If non-NULL, an array of CXPlatformAvailability instances @@ -2850,15 +2850,15 @@ typedef struct CXPlatformAvailability { * the number of platforms for which availability information is available (as * returned by this function) or \c availability_size, whichever is smaller. * - * \param availability_size The number of elements available in the + * \param availability_size The number of elements available in the * \c availability array. * * \returns The number of platforms (N) for which availability information is * available (which is unrelated to \c availability_size). * - * Note that the client is responsible for calling - * \c clang_disposeCXPlatformAvailability to free each of the - * platform-availability structures returned. There are + * Note that the client is responsible for calling + * \c clang_disposeCXPlatformAvailability to free each of the + * platform-availability structures returned. There are * \c min(N, availability_size) such structures. */ CINDEX_LINKAGE int @@ -2875,7 +2875,7 @@ clang_getCursorPlatformAvailability(CXCursor cursor, */ CINDEX_LINKAGE void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability); - + /** * Describe the "language" of the entity referred to by a cursor. */ @@ -2948,7 +2948,7 @@ CINDEX_LINKAGE unsigned clang_CXCursorSet_insert(CXCursorSet cset, * * The semantic parent of a cursor is the cursor that semantically contains * the given \p cursor. For many declarations, the lexical and semantic parents - * are equivalent (the lexical parent is returned by + * are equivalent (the lexical parent is returned by * \c clang_getCursorLexicalParent()). They diverge when declarations or * definitions are provided out-of-line. For example: * @@ -2983,7 +2983,7 @@ CINDEX_LINKAGE CXCursor clang_getCursorSemanticParent(CXCursor cursor); * * The lexical parent of a cursor is the cursor in which the given \p cursor * was actually written. For many declarations, the lexical and semantic parents - * are equivalent (the semantic parent is returned by + * are equivalent (the semantic parent is returned by * \c clang_getCursorSemanticParent()). They diverge when declarations or * definitions are provided out-of-line. For example: * @@ -3046,18 +3046,18 @@ CINDEX_LINKAGE CXCursor clang_getCursorLexicalParent(CXCursor cursor); * \param cursor A cursor representing an Objective-C or C++ * method. This routine will compute the set of methods that this * method overrides. - * + * * \param overridden A pointer whose pointee will be replaced with a * pointer to an array of cursors, representing the set of overridden * methods. If there are no overridden methods, the pointee will be - * set to NULL. The pointee must be freed via a call to + * set to NULL. The pointee must be freed via a call to * \c clang_disposeOverriddenCursors(). * * \param num_overridden A pointer to the number of overridden * functions, will be set to the number of overridden functions in the * array pointed to by \p overridden. */ -CINDEX_LINKAGE void clang_getOverriddenCursors(CXCursor cursor, +CINDEX_LINKAGE void clang_getOverriddenCursors(CXCursor cursor, CXCursor **overridden, unsigned *num_overridden); @@ -3072,7 +3072,7 @@ CINDEX_LINKAGE void clang_disposeOverriddenCursors(CXCursor *overridden); * cursor. */ CINDEX_LINKAGE CXFile clang_getIncludedFile(CXCursor cursor); - + /** * @} */ @@ -3133,7 +3133,7 @@ CINDEX_LINKAGE CXSourceRange clang_getCursorExtent(CXCursor); /** * @} */ - + /** * \defgroup CINDEX_TYPES Type information for CXCursors * @@ -3582,7 +3582,7 @@ CINDEX_LINKAGE CXString clang_getDeclObjCTypeEncoding(CXCursor C); /** * Returns the Objective-C type encoding for the specified CXType. */ -CINDEX_LINKAGE CXString clang_Type_getObjCEncoding(CXType type); +CINDEX_LINKAGE CXString clang_Type_getObjCEncoding(CXType type); /** * Retrieve the spelling of a given CXTypeKind. @@ -3842,7 +3842,7 @@ CINDEX_LINKAGE unsigned clang_Cursor_isBitField(CXCursor C); * CX_CXXBaseSpecifier is virtual. */ CINDEX_LINKAGE unsigned clang_isVirtualBase(CXCursor); - + /** * Represents the C++ access control level to a base class for a * cursor with kind CX_CXXBaseSpecifier. @@ -3887,7 +3887,7 @@ enum CX_StorageClass { CINDEX_LINKAGE enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor); /** - * Determine the number of overloaded declarations referenced by a + * Determine the number of overloaded declarations referenced by a * \c CXCursor_OverloadedDeclRef cursor. * * \param cursor The cursor whose overloaded declarations are being queried. @@ -3906,18 +3906,18 @@ CINDEX_LINKAGE unsigned clang_getNumOverloadedDecls(CXCursor cursor); * \param index The zero-based index into the set of overloaded declarations in * the cursor. * - * \returns A cursor representing the declaration referenced by the given - * \c cursor at the specified \c index. If the cursor does not have an + * \returns A cursor representing the declaration referenced by the given + * \c cursor at the specified \c index. If the cursor does not have an * associated set of overloaded declarations, or if the index is out of bounds, * returns \c clang_getNullCursor(); */ -CINDEX_LINKAGE CXCursor clang_getOverloadedDecl(CXCursor cursor, +CINDEX_LINKAGE CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index); - + /** * @} */ - + /** * \defgroup CINDEX_ATTRIBUTES Information for attributes * @@ -4021,7 +4021,7 @@ CINDEX_LINKAGE unsigned clang_visitChildren(CXCursor parent, * The visitor should return one of the \c CXChildVisitResult values * to direct clang_visitChildrenWithBlock(). */ -typedef enum CXChildVisitResult +typedef enum CXChildVisitResult (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent); /** @@ -4109,10 +4109,10 @@ CINDEX_LINKAGE CXString clang_getCursorSpelling(CXCursor); * Most of the times there is only one range for the complete spelling but for * Objective-C methods and Objective-C message expressions, there are multiple * pieces for each selector identifier. - * + * * \param pieceIndex the index of the spelling name piece. If this is greater * than the actual number of pieces, it will return a NULL (invalid) range. - * + * * \param options Reserved. */ CINDEX_LINKAGE CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor, @@ -4206,11 +4206,11 @@ CINDEX_LINKAGE CXString clang_getCursorPrettyPrinted(CXCursor Cursor, * Retrieve the display name for the entity referenced by this cursor. * * The display name contains extra information that helps identify the cursor, - * such as the parameters of a function or template or the arguments of a + * such as the parameters of a function or template or the arguments of a * class template specialization. */ CINDEX_LINKAGE CXString clang_getCursorDisplayName(CXCursor); - + /** For a cursor that is a reference, retrieve a cursor representing the * entity that it references. * @@ -4274,10 +4274,10 @@ CINDEX_LINKAGE unsigned clang_isCursorDefinition(CXCursor); * }; * \endcode * - * The declarations and the definition of \c X are represented by three - * different cursors, all of which are declarations of the same underlying + * The declarations and the definition of \c X are represented by three + * different cursors, all of which are declarations of the same underlying * entity. One of these cursor is considered the "canonical" cursor, which - * is effectively the representative for the underlying entity. One can + * is effectively the representative for the underlying entity. One can * determine if two cursors are declarations of the same underlying entity by * comparing their canonical cursors. * @@ -4301,11 +4301,11 @@ CINDEX_LINKAGE int clang_Cursor_getObjCSelectorIndex(CXCursor); /** * Given a cursor pointing to a C++ method call or an Objective-C * message, returns non-zero if the method/message is "dynamic", meaning: - * + * * For a C++ method: the call is virtual. * For an Objective-C message: the receiver is an object instance, not 'super' * or a specific class. - * + * * If the method/message is "static" or the cursor does not point to a * method/message, it will return zero. */ @@ -4575,7 +4575,7 @@ CINDEX_LINKAGE unsigned clang_CXXMethod_isDefaulted(CXCursor C); CINDEX_LINKAGE unsigned clang_CXXMethod_isPureVirtual(CXCursor C); /** - * Determine if a C++ member function or member function template is + * Determine if a C++ member function or member function template is * declared 'static'. */ CINDEX_LINKAGE unsigned clang_CXXMethod_isStatic(CXCursor C); @@ -4622,16 +4622,16 @@ CINDEX_LINKAGE unsigned clang_CXXMethod_isConst(CXCursor C); * \c CXCursor_NoDeclFound. */ CINDEX_LINKAGE enum CXCursorKind clang_getTemplateCursorKind(CXCursor C); - + /** * Given a cursor that may represent a specialization or instantiation * of a template, retrieve the cursor that represents the template that it * specializes or from which it was instantiated. * - * This routine determines the template involved both for explicit + * This routine determines the template involved both for explicit * specializations of templates and for implicit instantiations of the template, * both of which are referred to as "specializations". For a class template - * specialization (e.g., \c std::vector<bool>), this routine will return + * specialization (e.g., \c std::vector<bool>), this routine will return * either the primary template (\c std::vector) or, if the specialization was * instantiated from a class template partial specialization, the class template * partial specialization. For a class template partial specialization and a @@ -4639,7 +4639,7 @@ CINDEX_LINKAGE enum CXCursorKind clang_getTemplateCursorKind(CXCursor C); * this routine will return the specialized template. * * For members of a class template (e.g., member functions, member classes, or - * static data members), returns the specialized or instantiated member. + * static data members), returns the specialized or instantiated member. * Although not strictly "templates" in the C++ language, members of class * templates have the same notions of specializations and instantiations that * templates do, so this routine treats them similarly. @@ -4647,7 +4647,7 @@ CINDEX_LINKAGE enum CXCursorKind clang_getTemplateCursorKind(CXCursor C); * \param C A cursor that may be a specialization of a template or a member * of a template. * - * \returns If the given cursor is a specialization or instantiation of a + * \returns If the given cursor is a specialization or instantiation of a * template or a member thereof, the template or member that it specializes or * from which it was instantiated. Otherwise, returns a NULL cursor. */ @@ -4659,11 +4659,11 @@ CINDEX_LINKAGE CXCursor clang_getSpecializedCursorTemplate(CXCursor C); * * \param C A cursor pointing to a member reference, a declaration reference, or * an operator call. - * \param NameFlags A bitset with three independent flags: + * \param NameFlags A bitset with three independent flags: * CXNameRange_WantQualifier, CXNameRange_WantTemplateArgs, and * CXNameRange_WantSinglePiece. - * \param PieceIndex For contiguous names or when passing the flag - * CXNameRange_WantSinglePiece, only one piece with index 0 is + * \param PieceIndex For contiguous names or when passing the flag + * CXNameRange_WantSinglePiece, only one piece with index 0 is * available. When the CXNameRange_WantSinglePiece flag is not passed for a * non-contiguous names, this index can be used to retrieve the individual * pieces of the name. See also CXNameRange_WantSinglePiece. @@ -4672,7 +4672,7 @@ CINDEX_LINKAGE CXCursor clang_getSpecializedCursorTemplate(CXCursor C); * name, or if the PieceIndex is out-of-range, a null-cursor will be returned. */ CINDEX_LINKAGE CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, - unsigned NameFlags, + unsigned NameFlags, unsigned PieceIndex); enum CXNameRefFlags { @@ -4681,7 +4681,7 @@ enum CXNameRefFlags { * range. */ CXNameRange_WantQualifier = 0x1, - + /** * Include the explicit template arguments, e.g. \<int> in x.f<int>, * in the range. @@ -4700,7 +4700,7 @@ enum CXNameRefFlags { */ CXNameRange_WantSinglePiece = 0x4 }; - + /** * @} */ @@ -5153,7 +5153,7 @@ clang_getNumCompletionChunks(CXCompletionString completion_string); /** * Determine the priority of this code completion. * - * The priority of a code completion indicates how likely it is that this + * The priority of a code completion indicates how likely it is that this * particular completion is the completion that the user will select. The * priority is selected by various internal heuristics. * @@ -5164,7 +5164,7 @@ clang_getNumCompletionChunks(CXCompletionString completion_string); */ CINDEX_LINKAGE unsigned clang_getCompletionPriority(CXCompletionString completion_string); - + /** * Determine the availability of the entity that this code-completion * string refers to. @@ -5173,7 +5173,7 @@ clang_getCompletionPriority(CXCompletionString completion_string); * * \returns The availability of the completion string. */ -CINDEX_LINKAGE enum CXAvailabilityKind +CINDEX_LINKAGE enum CXAvailabilityKind clang_getCompletionAvailability(CXCompletionString completion_string); /** @@ -5206,7 +5206,7 @@ clang_getCompletionAnnotation(CXCompletionString completion_string, /** * Retrieve the parent context of the given completion string. * - * The parent context of a completion string is the semantic parent of + * The parent context of a completion string is the semantic parent of * the declaration (if any) that the code completion represents. For example, * a code completion for an Objective-C method would have the method's class * or protocol as its context. @@ -5241,7 +5241,7 @@ clang_getCompletionBriefComment(CXCompletionString completion_string); */ CINDEX_LINKAGE CXCompletionString clang_getCursorCompletionString(CXCursor cursor); - + /** * Contains the results of code-completion. * @@ -5378,12 +5378,12 @@ enum CXCompletionContext { * should be included. (This is equivalent to having no context bits set.) */ CXCompletionContext_Unexposed = 0, - + /** * Completions for any possible type should be included in the results. */ CXCompletionContext_AnyType = 1 << 0, - + /** * Completions for any possible value (variables, function calls, etc.) * should be included in the results. @@ -5404,7 +5404,7 @@ enum CXCompletionContext { * included in the results. */ CXCompletionContext_CXXClassTypeValue = 1 << 4, - + /** * Completions for fields of the member being accessed using the dot * operator should be included in the results. @@ -5420,7 +5420,7 @@ enum CXCompletionContext { * using the dot operator should be included in the results. */ CXCompletionContext_ObjCPropertyAccess = 1 << 7, - + /** * Completions for enum tags should be included in the results. */ @@ -5433,7 +5433,7 @@ enum CXCompletionContext { * Completions for struct tags should be included in the results. */ CXCompletionContext_StructTag = 1 << 10, - + /** * Completions for C++ class names should be included in the results. */ @@ -5448,7 +5448,7 @@ enum CXCompletionContext { * the results. */ CXCompletionContext_NestedNameSpecifier = 1 << 13, - + /** * Completions for Objective-C interfaces (classes) should be included * in the results. @@ -5479,27 +5479,27 @@ enum CXCompletionContext { * the results. */ CXCompletionContext_ObjCSelectorName = 1 << 19, - + /** * Completions for preprocessor macro names should be included in * the results. */ CXCompletionContext_MacroName = 1 << 20, - + /** * Natural language completions should be included in the results. */ CXCompletionContext_NaturalLanguage = 1 << 21, - + /** * The current context is unknown, so set all contexts. */ CXCompletionContext_Unknown = ((1 << 22) - 1) }; - + /** * Returns a default set of code-completion options that can be - * passed to\c clang_codeCompleteAt(). + * passed to\c clang_codeCompleteAt(). */ CINDEX_LINKAGE unsigned clang_defaultCodeCompleteOptions(void); @@ -5562,7 +5562,7 @@ CINDEX_LINKAGE unsigned clang_defaultCodeCompleteOptions(void); * * \param options Extra options that control the behavior of code * completion, expressed as a bitwise OR of the enumerators of the - * CXCodeComplete_Flags enumeration. The + * CXCodeComplete_Flags enumeration. The * \c clang_defaultCodeCompleteOptions() function returns a default set * of code-completion options. * @@ -5581,7 +5581,7 @@ CXCodeCompleteResults *clang_codeCompleteAt(CXTranslationUnit TU, unsigned options); /** - * Sort the code-completion results in case-insensitive alphabetical + * Sort the code-completion results in case-insensitive alphabetical * order. * * \param Results The set of results to sort. @@ -5590,13 +5590,13 @@ CXCodeCompleteResults *clang_codeCompleteAt(CXTranslationUnit TU, CINDEX_LINKAGE void clang_sortCodeCompletionResults(CXCompletionResult *Results, unsigned NumResults); - + /** * Free the given set of code-completion results. */ CINDEX_LINKAGE void clang_disposeCodeCompleteResults(CXCodeCompleteResults *Results); - + /** * Determine the number of diagnostics produced prior to the * location where code completion was performed. @@ -5620,7 +5620,7 @@ CXDiagnostic clang_codeCompleteGetDiagnostic(CXCodeCompleteResults *Results, /** * Determines what completions are appropriate for the context * the given code completion. - * + * * \param Results the code completion results to query * * \returns the kinds of completions that are appropriate for use @@ -5676,7 +5676,7 @@ CXString clang_codeCompleteGetContainerUSR(CXCodeCompleteResults *Results); */ CINDEX_LINKAGE CXString clang_codeCompleteGetObjCSelector(CXCodeCompleteResults *Results); - + /** * @} */ @@ -5700,7 +5700,7 @@ CINDEX_LINKAGE CXString clang_getClangVersion(void); * value enables crash recovery, while 0 disables it. */ CINDEX_LINKAGE void clang_toggleCrashRecovery(unsigned isEnabled); - + /** * Visitor invoked for each file in a translation unit * (used with clang_getInclusions()). @@ -5745,7 +5745,7 @@ typedef enum { typedef void * CXEvalResult; /** - * If cursor is a statement declaration tries to evaluate the + * If cursor is a statement declaration tries to evaluate the * statement and if its variable, tries to evaluate its initializer, * into its corresponding type. */ @@ -5844,7 +5844,7 @@ CINDEX_LINKAGE unsigned clang_remap_getNumFiles(CXRemapping); /** * Get the original and the associated filename from the remapping. - * + * * \param original If non-NULL, will be set to the original filename. * * \param transformed If non-NULL, will be set to the filename that the original @@ -5896,7 +5896,7 @@ typedef enum { /** * Find references of a declaration in a specific file. - * + * * \param cursor pointing to a declaration or a reference of one. * * \param file to search for references. @@ -6255,11 +6255,11 @@ typedef struct { const CXIdxEntityInfo *referencedEntity; /** * Immediate "parent" of the reference. For example: - * + * * \code * Foo *var; * \endcode - * + * * The parent of reference of type 'Foo' is the variable 'var'. * For references inside statement bodies of functions/methods, * the parentEntity will be the function/method. @@ -6294,16 +6294,16 @@ typedef struct { CXIdxClientFile (*enteredMainFile)(CXClientData client_data, CXFile mainFile, void *reserved); - + /** * Called when a file gets \#included/\#imported. */ CXIdxClientFile (*ppIncludedFile)(CXClientData client_data, const CXIdxIncludedFileInfo *); - + /** * Called when a AST file (PCH or module) gets imported. - * + * * AST files will not get indexed (there will not be callbacks to index all * the entities in an AST file). The recommended action is that, if the AST * file is not already indexed, to initiate a new indexing job specific to @@ -6405,7 +6405,7 @@ typedef enum { * Used to indicate that no special indexing options are needed. */ CXIndexOpt_None = 0x0, - + /** * Used to indicate that IndexerCallbacks#indexEntityReference should * be invoked for only one reference of an entity per source file that does @@ -6492,16 +6492,16 @@ CINDEX_LINKAGE int clang_indexSourceFileFullArgv( /** * Index the given translation unit via callbacks implemented through * #IndexerCallbacks. - * + * * The order of callback invocations is not guaranteed to be the same as * when indexing a source file. The high level order will be: - * + * * -Preprocessor callbacks invocations * -Declaration/reference callbacks invocations * -Diagnostic callback invocations * * The parameters are the same as #clang_indexSourceFile. - * + * * \returns If there is a failure from which there is no recovery, returns * non-zero, otherwise returns 0. */ diff --git a/include/clang/ARCMigrate/FileRemapper.h b/include/clang/ARCMigrate/FileRemapper.h index 53b88e9eb5e5..731307f24e22 100644 --- a/include/clang/ARCMigrate/FileRemapper.h +++ b/include/clang/ARCMigrate/FileRemapper.h @@ -41,7 +41,7 @@ class FileRemapper { public: FileRemapper(); ~FileRemapper(); - + bool initFromDisk(StringRef outputDir, DiagnosticsEngine &Diag, bool ignoreIfFilesChanged); bool initFromFile(StringRef filePath, DiagnosticsEngine &Diag, diff --git a/include/clang/AST/ASTContext.h b/include/clang/AST/ASTContext.h index c6f8e2973e8e..a9ab687a8de9 100644 --- a/include/clang/AST/ASTContext.h +++ b/include/clang/AST/ASTContext.h @@ -226,6 +226,12 @@ class ASTContext : public RefCountedBase<ASTContext> { using TypeInfoMap = llvm::DenseMap<const Type *, struct TypeInfo>; mutable TypeInfoMap MemoizedTypeInfo; + /// A cache from types to unadjusted alignment information. Only ARM and + /// AArch64 targets need this information, keeping it separate prevents + /// imposing overhead on TypeInfo size. + using UnadjustedAlignMap = llvm::DenseMap<const Type *, unsigned>; + mutable UnadjustedAlignMap MemoizedUnadjustedAlign; + /// A cache mapping from CXXRecordDecls to key functions. llvm::DenseMap<const CXXRecordDecl*, LazyDeclPtr> KeyFunctions; @@ -1522,7 +1528,7 @@ public: /// The sizeof operator requires this (C99 6.5.3.4p4). CanQualType getSizeType() const; - /// Return the unique signed counterpart of + /// Return the unique signed counterpart of /// the integer type corresponding to size_t. CanQualType getSignedSizeType() const; @@ -2067,6 +2073,16 @@ public: unsigned getTypeAlign(QualType T) const { return getTypeInfo(T).Align; } unsigned getTypeAlign(const Type *T) const { return getTypeInfo(T).Align; } + /// Return the ABI-specified natural alignment of a (complete) type \p T, + /// before alignment adjustments, in bits. + /// + /// This alignment is curently used only by ARM and AArch64 when passing + /// arguments of a composite type. + unsigned getTypeUnadjustedAlign(QualType T) const { + return getTypeUnadjustedAlign(T.getTypePtr()); + } + unsigned getTypeUnadjustedAlign(const Type *T) const; + /// Return the ABI-specified alignment of a type, in bits, or 0 if /// the type is incomplete and we cannot determine the alignment (for /// example, from alignment attributes). @@ -2077,6 +2093,12 @@ public: CharUnits getTypeAlignInChars(QualType T) const; CharUnits getTypeAlignInChars(const Type *T) const; + /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a type, + /// in characters, before alignment adjustments. This method does not work on + /// incomplete types. + CharUnits getTypeUnadjustedAlignInChars(QualType T) const; + CharUnits getTypeUnadjustedAlignInChars(const Type *T) const; + // getTypeInfoDataSizeInChars - Return the size of a type, in chars. If the // type is a record, its data size is returned. std::pair<CharUnits, CharUnits> getTypeInfoDataSizeInChars(QualType T) const; diff --git a/include/clang/AST/ASTDiagnostic.h b/include/clang/AST/ASTDiagnostic.h index b08865dde3c1..2534272da3a3 100644 --- a/include/clang/AST/ASTDiagnostic.h +++ b/include/clang/AST/ASTDiagnostic.h @@ -23,11 +23,11 @@ namespace clang { NUM_BUILTIN_AST_DIAGNOSTICS }; } // end namespace diag - + /// DiagnosticsEngine argument formatting function for diagnostics that /// involve AST nodes. /// - /// This function formats diagnostic arguments for various AST nodes, + /// This function formats diagnostic arguments for various AST nodes, /// including types, declaration names, nested name specifiers, and /// declaration contexts, into strings that can be printed as part of /// diagnostics. It is meant to be used as the argument to diff --git a/include/clang/AST/ASTImporter.h b/include/clang/AST/ASTImporter.h index 6e6a1926254b..2e9a8775a8a2 100644 --- a/include/clang/AST/ASTImporter.h +++ b/include/clang/AST/ASTImporter.h @@ -63,7 +63,7 @@ class Attr; private: /// The contexts we're importing to and from. ASTContext &ToContext, &FromContext; - + /// The file managers we're importing to and from. FileManager &ToFileManager, &FromFileManager; @@ -72,11 +72,11 @@ class Attr; /// Whether the last diagnostic came from the "from" context. bool LastDiagFromFrom = false; - + /// Mapping from the already-imported types in the "from" context /// to the corresponding types in the "to" context. llvm::DenseMap<const Type *, const Type *> ImportedTypes; - + /// Mapping from the already-imported declarations in the "from" /// context to the corresponding declarations in the "to" context. llvm::DenseMap<Decl *, Decl *> ImportedDecls; @@ -93,11 +93,11 @@ class Attr; /// the "from" source manager to the corresponding CXXBasesSpecifier /// in the "to" source manager. ImportedCXXBaseSpecifierMap ImportedCXXBaseSpecifiers; - + /// Declaration (from, to) pairs that are known not to be equivalent /// (which we have already complained about). NonEquivalentDeclSet NonEquivalentDecls; - + public: /// Create a new AST importer. /// @@ -115,13 +115,13 @@ class Attr; ASTImporter(ASTContext &ToContext, FileManager &ToFileManager, ASTContext &FromContext, FileManager &FromFileManager, bool MinimalImport); - + virtual ~ASTImporter(); - + /// Whether the importer will perform a minimal import, creating /// to-be-completed forward declarations when possible. bool isMinimalImport() const { return Minimal; } - + /// Import the given type from the "from" context into the "to" /// context. /// @@ -142,10 +142,10 @@ class Attr; /// \returns the equivalent attribute in the "to" context. Attr *Import(const Attr *FromAttr); - /// Import the given declaration from the "from" context into the + /// Import the given declaration from the "from" context into the /// "to" context. /// - /// \returns the equivalent declaration in the "to" context, or a NULL type + /// \returns the equivalent declaration in the "to" context, or a NULL type /// if an error occurred. Decl *Import(Decl *FromD); Decl *Import(const Decl *FromD) { @@ -163,7 +163,7 @@ class Attr; /// \returns the equivalent declaration context in the "to" /// context, or a NULL type if an error occurred. DeclContext *ImportContext(DeclContext *FromDC); - + /// Import the given expression from the "from" context into the /// "to" context. /// @@ -195,7 +195,7 @@ class Attr; /// Import the goven template name from the "from" context into the /// "to" context. TemplateName Import(TemplateName From); - + /// Import the given source location from the "from" context into /// the "to" context. /// @@ -229,7 +229,7 @@ class Attr; /// \returns the equivalent selector in the "to" context. Selector Import(Selector FromSel); - /// Import the given file ID from the "from" context into the + /// Import the given file ID from the "from" context into the /// "to" context. /// /// \returns the equivalent file ID in the source manager of the "to" @@ -252,13 +252,13 @@ class Attr; /// Import the definition of the given declaration, including all of /// the declarations it contains. /// - /// This routine is intended to be used + /// This routine is intended to be used void ImportDefinition(Decl *From); /// Cope with a name conflict when importing a declaration into the /// given context. /// - /// This routine is invoked whenever there is a name conflict while + /// This routine is invoked whenever there is a name conflict while /// importing a declaration. The returned name will become the name of the /// imported declaration. By default, the returned name is the same as the /// original name, leaving the conflict unresolve such that name lookup @@ -270,7 +270,7 @@ class Attr; /// \param Name the name of the declaration being imported, which conflicts /// with other declarations. /// - /// \param DC the declaration context (in the "to" AST context) in which + /// \param DC the declaration context (in the "to" AST context) in which /// the name is being imported. /// /// \param IDNS the identifier namespace in which the name will be found. @@ -286,25 +286,25 @@ class Attr; unsigned IDNS, NamedDecl **Decls, unsigned NumDecls); - + /// Retrieve the context that AST nodes are being imported into. ASTContext &getToContext() const { return ToContext; } - + /// Retrieve the context that AST nodes are being imported from. ASTContext &getFromContext() const { return FromContext; } - + /// Retrieve the file manager that AST nodes are being imported into. FileManager &getToFileManager() const { return ToFileManager; } /// Retrieve the file manager that AST nodes are being imported from. FileManager &getFromFileManager() const { return FromFileManager; } - + /// Report a diagnostic in the "to" context. DiagnosticBuilder ToDiag(SourceLocation Loc, unsigned DiagID); - + /// Report a diagnostic in the "from" context. DiagnosticBuilder FromDiag(SourceLocation Loc, unsigned DiagID); - + /// Return the set of declarations that we know are not equivalent. NonEquivalentDeclSet &getNonEquivalentDecls() { return NonEquivalentDecls; } @@ -313,7 +313,7 @@ class Attr; /// /// \param D A declaration in the "to" context. virtual void CompleteDecl(Decl* D); - + /// Subclasses can override this function to observe all of the \c From -> /// \c To declaration mappings as they are imported. virtual Decl *Imported(Decl *From, Decl *To) { return To; } @@ -328,7 +328,7 @@ class Attr; /// RecordDecl can be found, we can complete it without the need for /// importation, eliminating this loop. virtual Decl *GetOriginalDecl(Decl *To) { return nullptr; } - + /// Determine whether the given types are structurally /// equivalent. bool IsStructurallyEquivalent(QualType From, QualType To, diff --git a/include/clang/AST/ASTLambda.h b/include/clang/AST/ASTLambda.h index 2fe4e2563b36..6fedcb8d3801 100644 --- a/include/clang/AST/ASTLambda.h +++ b/include/clang/AST/ASTLambda.h @@ -40,7 +40,7 @@ inline bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD) { if (!MD) return false; const CXXRecordDecl *LambdaClass = MD->getParent(); if (LambdaClass && LambdaClass->isGenericLambda()) - return isLambdaCallOperator(MD) && + return isLambdaCallOperator(MD) && MD->isFunctionTemplateSpecialization(); return false; } @@ -51,11 +51,11 @@ inline bool isLambdaConversionOperator(CXXConversionDecl *C) { inline bool isLambdaConversionOperator(Decl *D) { if (!D) return false; - if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) - return isLambdaConversionOperator(Conv); - if (FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(D)) - if (CXXConversionDecl *Conv = - dyn_cast_or_null<CXXConversionDecl>(F->getTemplatedDecl())) + if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) + return isLambdaConversionOperator(Conv); + if (FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(D)) + if (CXXConversionDecl *Conv = + dyn_cast_or_null<CXXConversionDecl>(F->getTemplatedDecl())) return isLambdaConversionOperator(Conv); return false; } @@ -71,7 +71,7 @@ inline bool isGenericLambdaCallOperatorSpecialization(DeclContext *DC) { inline DeclContext *getLambdaAwareParentOfDeclContext(DeclContext *DC) { if (isLambdaCallOperator(DC)) return DC->getParent()->getParent(); - else + else return DC->getParent(); } diff --git a/include/clang/AST/ASTMutationListener.h b/include/clang/AST/ASTMutationListener.h index 31ae2b111e01..80184e1cc740 100644 --- a/include/clang/AST/ASTMutationListener.h +++ b/include/clang/AST/ASTMutationListener.h @@ -134,13 +134,13 @@ public: /// \param M The containing module in which the definition was made visible, /// if any. virtual void RedefinedHiddenDefinition(const NamedDecl *D, Module *M) {} - + /// An attribute was added to a RecordDecl /// /// \param Attr The attribute that was added to the Record /// /// \param Record The RecordDecl that got a new attribute - virtual void AddedAttributeToRecord(const Attr *Attr, + virtual void AddedAttributeToRecord(const Attr *Attr, const RecordDecl *Record) {} // NOTE: If new methods are added they should also be added to diff --git a/include/clang/AST/Attr.h b/include/clang/AST/Attr.h index 32a61c59d236..20922742f687 100644 --- a/include/clang/AST/Attr.h +++ b/include/clang/AST/Attr.h @@ -86,7 +86,7 @@ public: attr::Kind getKind() const { return static_cast<attr::Kind>(AttrKind); } - + unsigned getSpellingListIndex() const { return SpellingListIndex; } const char *getSpelling() const; diff --git a/include/clang/AST/AttrIterator.h b/include/clang/AST/AttrIterator.h index 56807b4590d3..2087ecc0e70c 100644 --- a/include/clang/AST/AttrIterator.h +++ b/include/clang/AST/AttrIterator.h @@ -106,7 +106,7 @@ public: specific_attr_iterator Right) { assert((Left.Current == nullptr) == (Right.Current == nullptr)); if (Left.Current < Right.Current) - Left.AdvanceToNext(Right.Current); + Left.AdvanceToNext(Right.Current); else Right.AdvanceToNext(Left.Current); return Left.Current == Right.Current; diff --git a/include/clang/AST/BaseSubobject.h b/include/clang/AST/BaseSubobject.h index fdb7e718fe9e..2b702c76b2fa 100644 --- a/include/clang/AST/BaseSubobject.h +++ b/include/clang/AST/BaseSubobject.h @@ -24,21 +24,21 @@ namespace clang { class CXXRecordDecl; -// BaseSubobject - Uniquely identifies a direct or indirect base class. +// BaseSubobject - Uniquely identifies a direct or indirect base class. // Stores both the base class decl and the offset from the most derived class to // the base class. Used for vtable and VTT generation. class BaseSubobject { /// Base - The base class declaration. const CXXRecordDecl *Base; - + /// BaseOffset - The offset from the most derived class to the base class. CharUnits BaseOffset; - + public: BaseSubobject() = default; BaseSubobject(const CXXRecordDecl *Base, CharUnits BaseOffset) : Base(Base), BaseOffset(BaseOffset) {} - + /// getBase - Returns the base class declaration. const CXXRecordDecl *getBase() const { return Base; } @@ -74,7 +74,7 @@ template<> struct DenseMapInfo<clang::BaseSubobject> { Base.getBaseOffset())); } - static bool isEqual(const clang::BaseSubobject &LHS, + static bool isEqual(const clang::BaseSubobject &LHS, const clang::BaseSubobject &RHS) { return LHS == RHS; } diff --git a/include/clang/AST/CXXInheritance.h b/include/clang/AST/CXXInheritance.h index 2ae1d8b25823..f5e23f8e8505 100644 --- a/include/clang/AST/CXXInheritance.h +++ b/include/clang/AST/CXXInheritance.h @@ -34,10 +34,10 @@ namespace clang { class ASTContext; class NamedDecl; - + /// Represents an element in a path from a derived class to a -/// base class. -/// +/// base class. +/// /// Each step in the path references the link from a /// derived class to one of its direct base classes, along with a /// base "number" that identifies which base subobject of the @@ -47,12 +47,12 @@ struct CXXBasePathElement { /// class to a base class, which will be followed by this base /// path element. const CXXBaseSpecifier *Base; - + /// The record decl of the class that the base is a base of. const CXXRecordDecl *Class; - + /// Identifies which base class subobject (of type - /// \c Base->getType()) this base path element refers to. + /// \c Base->getType()) this base path element refers to. /// /// This value is only valid if \c !Base->isVirtual(), because there /// is no base numbering for the zero or one virtual bases of a @@ -64,7 +64,7 @@ struct CXXBasePathElement { /// (which is not represented as part of the path) to a particular /// (direct or indirect) base class subobject. /// -/// Individual elements in the path are described by the \c CXXBasePathElement +/// Individual elements in the path are described by the \c CXXBasePathElement /// structure, which captures both the link from a derived class to one of its /// direct bases and identification describing which base class /// subobject is being used. @@ -121,7 +121,7 @@ class CXXBasePaths { /// The type from which this search originated. CXXRecordDecl *Origin = nullptr; - + /// Paths - The actual set of paths that can be taken from the /// derived class to the same base class. std::list<CXXBasePath> Paths; @@ -160,12 +160,12 @@ class CXXBasePaths { /// ambiguous paths while it is looking for a path from a derived /// type to a base type. bool FindAmbiguities; - + /// RecordPaths - Whether Sema::IsDerivedFrom should record paths /// while it is determining whether there are paths from a derived /// type to a base type. bool RecordPaths; - + /// DetectVirtual - Whether Sema::IsDerivedFrom should abort the search /// if it finds a path that goes across a virtual base. The virtual class /// is also recorded. @@ -181,7 +181,7 @@ public: using paths_iterator = std::list<CXXBasePath>::iterator; using const_paths_iterator = std::list<CXXBasePath>::const_iterator; using decl_iterator = NamedDecl **; - + /// BasePaths - Construct a new BasePaths structure to record the /// paths for a derived-to-base search. explicit CXXBasePaths(bool FindAmbiguities = true, bool RecordPaths = true, @@ -193,31 +193,31 @@ public: paths_iterator end() { return Paths.end(); } const_paths_iterator begin() const { return Paths.begin(); } const_paths_iterator end() const { return Paths.end(); } - + CXXBasePath& front() { return Paths.front(); } const CXXBasePath& front() const { return Paths.front(); } - + using decl_range = llvm::iterator_range<decl_iterator>; decl_range found_decls(); - + /// Determine whether the path from the most-derived type to the /// given base type is ambiguous (i.e., it refers to multiple subobjects of /// the same base type). bool isAmbiguous(CanQualType BaseType); - + /// Whether we are finding multiple paths to detect ambiguities. bool isFindingAmbiguities() const { return FindAmbiguities; } - + /// Whether we are recording paths. bool isRecordingPaths() const { return RecordPaths; } - + /// Specify whether we should be recording paths or not. void setRecordingPaths(bool RP) { RecordPaths = RP; } - + /// Whether we are detecting virtual bases. bool isDetectingVirtual() const { return DetectVirtual; } - + /// The virtual base discovered on the path (if we are merely /// detecting virtuals). const RecordType* getDetectedVirtual() const { @@ -228,11 +228,11 @@ public: /// began CXXRecordDecl *getOrigin() const { return Origin; } void setOrigin(CXXRecordDecl *Rec) { Origin = Rec; } - + /// Clear the base-paths results. void clear(); - - /// Swap this data structure's contents with another CXXBasePaths + + /// Swap this data structure's contents with another CXXBasePaths /// object. void swap(CXXBasePaths &Other); }; diff --git a/include/clang/AST/CanonicalType.h b/include/clang/AST/CanonicalType.h index 63a0af66eec3..0e738da43ad4 100644 --- a/include/clang/AST/CanonicalType.h +++ b/include/clang/AST/CanonicalType.h @@ -85,8 +85,8 @@ public: /// Retrieve the underlying type pointer, which refers to a /// canonical type, or nullptr. - const T *getTypePtrOrNull() const { - return cast_or_null<T>(Stored.getTypePtrOrNull()); + const T *getTypePtrOrNull() const { + return cast_or_null<T>(Stored.getTypePtrOrNull()); } /// Implicit conversion to a qualified type. @@ -94,7 +94,7 @@ public: /// Implicit conversion to bool. explicit operator bool() const { return !isNull(); } - + bool isNull() const { return Stored.isNull(); } diff --git a/include/clang/AST/CharUnits.h b/include/clang/AST/CharUnits.h index ddead6046a14..0aadf06fffc9 100644 --- a/include/clang/AST/CharUnits.h +++ b/include/clang/AST/CharUnits.h @@ -61,7 +61,7 @@ namespace clang { /// fromQuantity - Construct a CharUnits quantity from a raw integer type. static CharUnits fromQuantity(QuantityType Quantity) { - return CharUnits(Quantity); + return CharUnits(Quantity); } // Compound assignment. @@ -87,7 +87,7 @@ namespace clang { CharUnits operator-- (int) { return CharUnits(Quantity--); } - + // Comparison operators. bool operator== (const CharUnits &Other) const { return Quantity == Other.Quantity; @@ -97,21 +97,21 @@ namespace clang { } // Relational operators. - bool operator< (const CharUnits &Other) const { - return Quantity < Other.Quantity; + bool operator< (const CharUnits &Other) const { + return Quantity < Other.Quantity; } - bool operator<= (const CharUnits &Other) const { + bool operator<= (const CharUnits &Other) const { return Quantity <= Other.Quantity; } - bool operator> (const CharUnits &Other) const { - return Quantity > Other.Quantity; + bool operator> (const CharUnits &Other) const { + return Quantity > Other.Quantity; } - bool operator>= (const CharUnits &Other) const { - return Quantity >= Other.Quantity; + bool operator>= (const CharUnits &Other) const { + return Quantity >= Other.Quantity; } // Other predicates. - + /// isZero - Test whether the quantity equals zero. bool isZero() const { return Quantity == 0; } @@ -172,7 +172,7 @@ namespace clang { return CharUnits(-Quantity); } - + // Conversions. /// getQuantity - Get the raw integer representation of this quantity. @@ -205,7 +205,7 @@ namespace clang { }; // class CharUnit } // namespace clang -inline clang::CharUnits operator* (clang::CharUnits::QuantityType Scale, +inline clang::CharUnits operator* (clang::CharUnits::QuantityType Scale, const clang::CharUnits &CU) { return CU * Scale; } @@ -223,8 +223,8 @@ template<> struct DenseMapInfo<clang::CharUnits> { static clang::CharUnits getTombstoneKey() { clang::CharUnits::QuantityType Quantity = DenseMapInfo<clang::CharUnits::QuantityType>::getTombstoneKey(); - - return clang::CharUnits::fromQuantity(Quantity); + + return clang::CharUnits::fromQuantity(Quantity); } static unsigned getHashValue(const clang::CharUnits &CU) { @@ -232,7 +232,7 @@ template<> struct DenseMapInfo<clang::CharUnits> { return DenseMapInfo<clang::CharUnits::QuantityType>::getHashValue(Quantity); } - static bool isEqual(const clang::CharUnits &LHS, + static bool isEqual(const clang::CharUnits &LHS, const clang::CharUnits &RHS) { return LHS == RHS; } @@ -241,7 +241,7 @@ template<> struct DenseMapInfo<clang::CharUnits> { template <> struct isPodLike<clang::CharUnits> { static const bool value = true; }; - + } // end namespace llvm #endif // LLVM_CLANG_AST_CHARUNITS_H diff --git a/include/clang/AST/Comment.h b/include/clang/AST/Comment.h index e3a427d8aa0d..f5538dec2a14 100644 --- a/include/clang/AST/Comment.h +++ b/include/clang/AST/Comment.h @@ -98,7 +98,7 @@ protected: unsigned RenderKind : 2; unsigned CommandID : CommandInfo::NumCommandIDBits; }; - enum { NumInlineCommandCommentBits = NumInlineContentCommentBits + 2 + + enum { NumInlineCommandCommentBits = NumInlineContentCommentBits + 2 + CommandInfo::NumCommandIDBits }; class HTMLTagCommentBitfields { @@ -146,7 +146,7 @@ protected: /// Contains values from CommandMarkerKind enum. unsigned CommandMarker : 1; }; - enum { NumBlockCommandCommentBits = NumCommentBits + + enum { NumBlockCommandCommentBits = NumCommentBits + CommandInfo::NumCommandIDBits + 1 }; class ParamCommandCommentBitfields { @@ -987,7 +987,7 @@ struct DeclInfo { /// Declaration the comment is actually attached to (in the source). /// Should not be NULL. const Decl *CommentDecl; - + /// CurrentDecl is the declaration with which the FullComment is associated. /// /// It can be different from \c CommentDecl. It happens when we decide @@ -997,7 +997,7 @@ struct DeclInfo { /// /// The information in the DeclInfo corresponds to CurrentDecl. const Decl *CurrentDecl; - + /// Parameters that can be referenced by \\param if \c CommentDecl is something /// that we consider a "function". ArrayRef<const ParmVarDecl *> ParamVars; @@ -1119,21 +1119,21 @@ public: } child_iterator child_end() const { - return reinterpret_cast<child_iterator>(Blocks.end()); + return reinterpret_cast<child_iterator>(Blocks.end()); } const Decl *getDecl() const LLVM_READONLY { return ThisDeclInfo->CommentDecl; } - + const DeclInfo *getDeclInfo() const LLVM_READONLY { if (!ThisDeclInfo->IsFilled) ThisDeclInfo->fill(); return ThisDeclInfo; } - + ArrayRef<BlockContentComment *> getBlocks() const { return Blocks; } - + }; } // end namespace comments } // end namespace clang diff --git a/include/clang/AST/CommentCommandTraits.h b/include/clang/AST/CommentCommandTraits.h index bac4e99dc7a4..4fd007872c01 100644 --- a/include/clang/AST/CommentCommandTraits.h +++ b/include/clang/AST/CommentCommandTraits.h @@ -107,17 +107,17 @@ struct CommandInfo { /// \fn void f(int a); /// \endcode unsigned IsDeclarationCommand : 1; - + /// True if verbatim-like line command is a function declaration. unsigned IsFunctionDeclarationCommand : 1; /// True if block command is further describing a container API; such /// as \@coclass, \@classdesign, etc. unsigned IsRecordLikeDetailCommand : 1; - + /// True if block command is a container API; such as \@interface. unsigned IsRecordLikeDeclarationCommand : 1; - + /// True if this command is unknown. This \c CommandInfo object was /// created during parsing. unsigned IsUnknownCommand : 1; @@ -150,7 +150,7 @@ public: } const CommandInfo *getTypoCorrectCommandInfo(StringRef Typo) const; - + const CommandInfo *getCommandInfo(unsigned CommandID) const; const CommandInfo *registerUnknownCommand(StringRef CommandName); diff --git a/include/clang/AST/CommentLexer.h b/include/clang/AST/CommentLexer.h index 52c4eb9e309a..3ef5b7c8c998 100644 --- a/include/clang/AST/CommentLexer.h +++ b/include/clang/AST/CommentLexer.h @@ -76,7 +76,7 @@ class Token { /// unused (command spelling can be found with CommandTraits). Otherwise, /// contains the length of the string that starts at TextPtr. unsigned IntVal; - + public: SourceLocation getLocation() const LLVM_READONLY { return Loc; } void setLocation(SourceLocation SL) { Loc = SL; } @@ -228,7 +228,7 @@ private: llvm::BumpPtrAllocator &Allocator; DiagnosticsEngine &Diags; - + const CommandTraits &Traits; const char *const BufferStart; diff --git a/include/clang/AST/CommentSema.h b/include/clang/AST/CommentSema.h index 0e94c33970ca..632eba782b92 100644 --- a/include/clang/AST/CommentSema.h +++ b/include/clang/AST/CommentSema.h @@ -191,11 +191,11 @@ public: void checkBlockCommandDuplicate(const BlockCommandComment *Command); void checkDeprecatedCommand(const BlockCommandComment *Comment); - + void checkFunctionDeclVerbatimLine(const BlockCommandComment *Comment); - + void checkContainerDeclVerbatimLine(const BlockCommandComment *Comment); - + void checkContainerDecl(const BlockCommandComment *Comment); /// Resolve parameter names to parameter indexes in function declaration. diff --git a/include/clang/AST/Decl.h b/include/clang/AST/Decl.h index dde94599636f..ebdb2890daf5 100644 --- a/include/clang/AST/Decl.h +++ b/include/clang/AST/Decl.h @@ -98,7 +98,7 @@ public: /// Return the TypeLoc wrapper for the type source info. TypeLoc getTypeLoc() const; // implemented in TypeLoc.h - + /// Override the type stored in this TypeSourceInfo. Use with caution! void overrideType(QualType T) { Ty = T; } }; @@ -488,7 +488,7 @@ public: SourceLocation IdentL, IdentifierInfo *II, SourceLocation GnuLabelL); static LabelDecl *CreateDeserialized(ASTContext &C, unsigned ID); - + LabelStmt *getStmt() const { return TheStmt; } void setStmt(LabelStmt *T) { TheStmt = T; } @@ -511,8 +511,8 @@ public: }; /// Represent a C++ namespace. -class NamespaceDecl : public NamedDecl, public DeclContext, - public Redeclarable<NamespaceDecl> +class NamespaceDecl : public NamedDecl, public DeclContext, + public Redeclarable<NamespaceDecl> { /// The starting location of the source range, pointing /// to either the namespace or the inline keyword. @@ -523,7 +523,7 @@ class NamespaceDecl : public NamedDecl, public DeclContext, /// A pointer to either the anonymous namespace that lives just inside /// this namespace or to the first namespace in the chain (the latter case - /// only when this is not the first in the chain), along with a + /// only when this is not the first in the chain), along with a /// boolean value indicating whether this is an inline namespace. llvm::PointerIntPair<NamespaceDecl *, 1, bool> AnonOrFirstNamespaceAndInline; @@ -1931,7 +1931,7 @@ public: bool isConstexprSpecified = false); static FunctionDecl *CreateDeserialized(ASTContext &C, unsigned ID); - + DeclarationNameInfo getNameInfo() const { return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc); } @@ -2598,7 +2598,7 @@ public: InClassInitStyle InitStyle); static FieldDecl *CreateDeserialized(ASTContext &C, unsigned ID); - + /// Returns the index of this field within its record, /// as appropriate for passing to ASTRecordLayout::getFieldOffset. unsigned getFieldIndex() const; @@ -2754,7 +2754,7 @@ public: QualType T, Expr *E, const llvm::APSInt &V); static EnumConstantDecl *CreateDeserialized(ASTContext &C, unsigned ID); - + const Expr *getInitExpr() const { return (const Expr*) Init; } Expr *getInitExpr() { return (Expr*) Init; } const llvm::APSInt &getInitVal() const { return Val; } @@ -3812,7 +3812,7 @@ public: /// Finds the first data member which has a name. /// nullptr is returned if no named data member exists. - const FieldDecl *findFirstNamedDataMember() const; + const FieldDecl *findFirstNamedDataMember() const; private: /// Deserialize just the fields. @@ -3835,7 +3835,7 @@ public: SourceLocation RParenLoc); static FileScopeAsmDecl *CreateDeserialized(ASTContext &C, unsigned ID); - + SourceLocation getAsmLoc() const { return getLocation(); } SourceLocation getRParenLoc() const { return RParenLoc; } void setRParenLoc(SourceLocation L) { RParenLoc = L; } @@ -3927,9 +3927,9 @@ protected: IsConversionFromLambda(false), DoesNotEscape(false) {} public: - static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L); + static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L); static BlockDecl *CreateDeserialized(ASTContext &C, unsigned ID); - + SourceLocation getCaretLocation() const { return getLocation(); } bool isVariadic() const { return IsVariadic; } @@ -4009,7 +4009,7 @@ public: } Decl *getBlockManglingContextDecl() const { - return ManglingContextDecl; + return ManglingContextDecl; } void setBlockMangling(unsigned Number, Decl *Ctx) { @@ -4145,16 +4145,16 @@ class ImportDecl final : public Decl, /// The imported module, along with a bit that indicates whether /// we have source-location information for each identifier in the module - /// name. + /// name. /// /// When the bit is false, we only have a single source location for the /// end of the import declaration. llvm::PointerIntPair<Module *, 1, bool> ImportedAndComplete; - + /// The next import in the list of imports local to the translation /// unit being parsed (not loaded from an AST file). ImportDecl *NextLocalImport = nullptr; - + ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported, ArrayRef<SourceLocation> IdentifierLocs); @@ -4162,26 +4162,26 @@ class ImportDecl final : public Decl, SourceLocation EndLoc); ImportDecl(EmptyShell Empty) : Decl(Import, Empty) {} - + public: /// Create a new module import declaration. - static ImportDecl *Create(ASTContext &C, DeclContext *DC, + static ImportDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, Module *Imported, ArrayRef<SourceLocation> IdentifierLocs); - + /// Create a new module import declaration for an implicitly-generated /// import. - static ImportDecl *CreateImplicit(ASTContext &C, DeclContext *DC, - SourceLocation StartLoc, Module *Imported, + static ImportDecl *CreateImplicit(ASTContext &C, DeclContext *DC, + SourceLocation StartLoc, Module *Imported, SourceLocation EndLoc); - + /// Create a new, deserialized module import declaration. - static ImportDecl *CreateDeserialized(ASTContext &C, unsigned ID, + static ImportDecl *CreateDeserialized(ASTContext &C, unsigned ID, unsigned NumLocations); - + /// Retrieve the module that was imported by the import declaration. Module *getImportedModule() const { return ImportedAndComplete.getPointer(); } - + /// Retrieves the locations of each of the identifiers that make up /// the complete module name in the import declaration. /// @@ -4218,7 +4218,7 @@ public: static ExportDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation ExportLoc); static ExportDecl *CreateDeserialized(ASTContext &C, unsigned ID); - + SourceLocation getExportLoc() const { return getLocation(); } SourceLocation getRBraceLoc() const { return RBraceLoc; } void setRBraceLoc(SourceLocation L) { RBraceLoc = L; } diff --git a/include/clang/AST/DeclBase.h b/include/clang/AST/DeclBase.h index f99bd627877c..d6b89d971d94 100644 --- a/include/clang/AST/DeclBase.h +++ b/include/clang/AST/DeclBase.h @@ -302,7 +302,7 @@ private: /// global variable, etc.) that is lexically inside an objc container /// definition. unsigned TopLevelDeclInObjCContainer : 1; - + /// Whether statistic collection is enabled. static bool StatisticsEnabled; @@ -629,7 +629,7 @@ protected: assert(isFromASTFile() && "Only works on a deserialized declaration"); *((unsigned*)this - 2) = ID; } - + public: /// Determine the availability of the given declaration. /// @@ -879,7 +879,7 @@ public: /// Whether this particular Decl is a canonical one. bool isCanonicalDecl() const { return getCanonicalDecl() == this; } - + protected: /// Returns the next redeclaration or itself if this is the only decl. /// @@ -956,10 +956,10 @@ public: /// Retrieve the previous declaration that declares the same entity /// as this declaration, or NULL if there is no previous declaration. Decl *getPreviousDecl() { return getPreviousDeclImpl(); } - + /// Retrieve the most recent declaration that declares the same entity /// as this declaration, or NULL if there is no previous declaration. - const Decl *getPreviousDecl() const { + const Decl *getPreviousDecl() const { return const_cast<Decl *>(this)->getPreviousDeclImpl(); } @@ -974,7 +974,7 @@ public: /// Retrieve the most recent declaration that declares the same entity /// as this declaration (which may be this declaration). - const Decl *getMostRecentDecl() const { + const Decl *getMostRecentDecl() const { return const_cast<Decl *>(this)->getMostRecentDeclImpl(); } @@ -1159,13 +1159,13 @@ protected: inline bool declaresSameEntity(const Decl *D1, const Decl *D2) { if (!D1 || !D2) return false; - + if (D1 == D2) return true; - + return D1->getCanonicalDecl() == D2->getCanonicalDecl(); } - + /// PrettyStackTraceDecl - If a crash occurs, indicate that it happened when /// doing something to a specific decl. class PrettyStackTraceDecl : public llvm::PrettyStackTraceEntry { @@ -1517,7 +1517,7 @@ public: /// connected to this declaration context. /// /// For declaration contexts that have multiple semantically connected but - /// syntactically distinct contexts, such as C++ namespaces, this routine + /// syntactically distinct contexts, such as C++ namespaces, this routine /// retrieves the complete set of such declaration contexts in source order. /// For example, given: /// @@ -1921,7 +1921,7 @@ public: /// Determine whether the given declaration is stored in the list of /// declarations lexically within this context. bool isDeclInLexicalTraversal(const Decl *D) const { - return D && (D->NextInContextAndBits.getPointer() || D == FirstDecl || + return D && (D->NextInContextAndBits.getPointer() || D == FirstDecl || D == LastDecl); } diff --git a/include/clang/AST/DeclCXX.h b/include/clang/AST/DeclCXX.h index 1d0489912c6b..4353f66a34e4 100644 --- a/include/clang/AST/DeclCXX.h +++ b/include/clang/AST/DeclCXX.h @@ -264,7 +264,7 @@ public: return EllipsisLoc; } - /// Returns the access specifier for this base specifier. + /// Returns the access specifier for this base specifier. /// /// This is the actual base specifier as used for semantic analysis, so /// the result can never be AS_none. To retrieve the access specifier as @@ -564,7 +564,7 @@ class CXXRecordDecl : public RecordDecl { CXXRecordDecl *Definition; /// The first friend declaration in this class, or null if there - /// aren't any. + /// aren't any. /// /// This is actually currently stored in reverse order. LazyDeclPtr FirstFriend; @@ -606,14 +606,14 @@ class CXXRecordDecl : public RecordDecl { /// Whether this lambda is known to be dependent, even if its /// context isn't dependent. - /// + /// /// A lambda with a non-dependent context can be dependent if it occurs /// within the default argument of a function template, because the /// lambda will have been created with the enclosing context as its /// declaration context, rather than function. This is an unfortunate - /// artifact of having to parse the default arguments before. + /// artifact of having to parse the default arguments before. unsigned Dependent : 1; - + /// Whether this lambda is a generic lambda. unsigned IsGenericLambda : 1; @@ -626,28 +626,28 @@ class CXXRecordDecl : public RecordDecl { /// The number of explicit captures in this lambda. unsigned NumExplicitCaptures : 13; - /// The number used to indicate this lambda expression for name + /// The number used to indicate this lambda expression for name /// mangling in the Itanium C++ ABI. unsigned ManglingNumber = 0; - + /// The declaration that provides context for this lambda, if the /// actual DeclContext does not suffice. This is used for lambdas that /// occur within default arguments of function parameters within the class /// or within a data member initializer. LazyDeclPtr ContextDecl; - - /// The list of captures, both explicit and implicit, for this + + /// The list of captures, both explicit and implicit, for this /// lambda. Capture *Captures = nullptr; /// The type of the call method. TypeSourceInfo *MethodTyInfo; - LambdaDefinitionData(CXXRecordDecl *D, TypeSourceInfo *Info, - bool Dependent, bool IsGeneric, - LambdaCaptureDefault CaptureDefault) - : DefinitionData(D), Dependent(Dependent), IsGenericLambda(IsGeneric), - CaptureDefault(CaptureDefault), NumCaptures(0), NumExplicitCaptures(0), + LambdaDefinitionData(CXXRecordDecl *D, TypeSourceInfo *Info, + bool Dependent, bool IsGeneric, + LambdaCaptureDefault CaptureDefault) + : DefinitionData(D), Dependent(Dependent), IsGenericLambda(IsGeneric), + CaptureDefault(CaptureDefault), NumCaptures(0), NumExplicitCaptures(0), MethodTyInfo(Info) { IsLambda = true; @@ -1205,22 +1205,22 @@ public: return DD && DD->IsLambda; } - /// Determine whether this class describes a generic + /// Determine whether this class describes a generic /// lambda function object (i.e. function call operator is - /// a template). - bool isGenericLambda() const; + /// a template). + bool isGenericLambda() const; /// Retrieve the lambda call operator of the closure type /// if this is a closure type. - CXXMethodDecl *getLambdaCallOperator() const; + CXXMethodDecl *getLambdaCallOperator() const; /// Retrieve the lambda static invoker, the address of which /// is returned by the conversion operator, and the body of which - /// is forwarded to the lambda call operator. - CXXMethodDecl *getLambdaStaticInvoker() const; + /// is forwarded to the lambda call operator. + CXXMethodDecl *getLambdaStaticInvoker() const; /// Retrieve the generic lambda's template parameter list. - /// Returns null if the class does not represent a lambda or a generic + /// Returns null if the class does not represent a lambda or a generic /// lambda. TemplateParameterList *getGenericLambdaTemplateParameterList() const; @@ -1345,11 +1345,11 @@ public: /// not overridden. bool isAbstract() const { return data().Abstract; } - /// Determine whether this class is standard-layout per + /// Determine whether this class is standard-layout per /// C++ [class]p7. bool isStandardLayout() const { return data().IsStandardLayout; } - /// Determine whether this class was standard-layout per + /// Determine whether this class was standard-layout per /// C++11 [class]p7, specifically using the C++11 rules without any DRs. bool isCXX11StandardLayout() const { return data().IsCXX11StandardLayout; } @@ -1900,25 +1900,25 @@ public: /// If this is the closure type of a lambda expression, retrieve the /// number to be used for name mangling in the Itanium C++ ABI. /// - /// Zero indicates that this closure type has internal linkage, so the + /// Zero indicates that this closure type has internal linkage, so the /// mangling number does not matter, while a non-zero value indicates which /// lambda expression this is in this particular context. unsigned getLambdaManglingNumber() const { assert(isLambda() && "Not a lambda closure type!"); return getLambdaData().ManglingNumber; } - - /// Retrieve the declaration that provides additional context for a + + /// Retrieve the declaration that provides additional context for a /// lambda, when the normal declaration context is not specific enough. /// - /// Certain contexts (default arguments of in-class function parameters and + /// Certain contexts (default arguments of in-class function parameters and /// the initializers of data members) have separate name mangling rules for /// lambdas within the Itanium C++ ABI. For these cases, this routine provides - /// the declaration in which the lambda occurs, e.g., the function parameter + /// the declaration in which the lambda occurs, e.g., the function parameter /// or the non-static data member. Otherwise, it returns NULL to imply that /// the declaration context suffices. Decl *getLambdaContextDecl() const; - + /// Set the mangling number and context declaration for a lambda /// class. void setLambdaMangling(unsigned ManglingNumber, Decl *ContextDecl) { @@ -2799,7 +2799,7 @@ public: /// Determine whether this conversion function is a conversion from /// a lambda closure type to a block pointer. bool isLambdaToBlockPointerConversion() const; - + CXXConversionDecl *getCanonicalDecl() override { return cast<CXXConversionDecl>(FunctionDecl::getCanonicalDecl()); } @@ -2812,7 +2812,7 @@ public: static bool classofKind(Kind K) { return K == CXXConversion; } }; -/// Represents a linkage specification. +/// Represents a linkage specification. /// /// For example: /// \code @@ -2862,7 +2862,7 @@ public: SourceLocation LangLoc, LanguageIDs Lang, bool HasBraces); static LinkageSpecDecl *CreateDeserialized(ASTContext &C, unsigned ID); - + /// Return the language specified by this linkage specification. LanguageIDs getLanguage() const { return LanguageIDs(Language); } @@ -3770,7 +3770,7 @@ public: Expr *AssertExpr, StringLiteral *Message, SourceLocation RParenLoc, bool Failed); static StaticAssertDecl *CreateDeserialized(ASTContext &C, unsigned ID); - + Expr *getAssertExpr() { return AssertExprAndFailed.getPointer(); } const Expr *getAssertExpr() const { return AssertExprAndFailed.getPointer(); } diff --git a/include/clang/AST/DeclFriend.h b/include/clang/AST/DeclFriend.h index 47fb68bf42d3..a8de8ed16840 100644 --- a/include/clang/AST/DeclFriend.h +++ b/include/clang/AST/DeclFriend.h @@ -254,7 +254,7 @@ inline void CXXRecordDecl::pushFriendDecl(FriendDecl *FD) { FD->NextFriend = data().FirstFriend; data().FirstFriend = FD; } - + } // namespace clang #endif // LLVM_CLANG_AST_DECLFRIEND_H diff --git a/include/clang/AST/DeclLookups.h b/include/clang/AST/DeclLookups.h index 64eb3f24b370..9627f440d406 100644 --- a/include/clang/AST/DeclLookups.h +++ b/include/clang/AST/DeclLookups.h @@ -54,7 +54,7 @@ public: ++It; } while (It != End && It->first == DeclarationName::getUsingDirectiveName()); - + return *this; } diff --git a/include/clang/AST/DeclObjC.h b/include/clang/AST/DeclObjC.h index c81a5f805fc0..c1cc726e3152 100644 --- a/include/clang/AST/DeclObjC.h +++ b/include/clang/AST/DeclObjC.h @@ -587,7 +587,7 @@ class ObjCTypeParamDecl : public TypedefNameDecl { /// explicitly specified. SourceLocation ColonLoc; - ObjCTypeParamDecl(ASTContext &ctx, DeclContext *dc, + ObjCTypeParamDecl(ASTContext &ctx, DeclContext *dc, ObjCTypeParamVariance variance, SourceLocation varianceLoc, unsigned index, SourceLocation nameLoc, IdentifierInfo *name, @@ -659,7 +659,7 @@ class ObjCTypeParamList final unsigned End; }; - union { + union { /// Location of the left and right angle brackets. PODSourceRange Brackets; @@ -1123,7 +1123,7 @@ public: ObjCPropertyDecl *>; using ProtocolPropertySet = llvm::SmallDenseSet<const ObjCProtocolDecl *, 8>; using PropertyDeclOrder = llvm::SmallVector<ObjCPropertyDecl *, 8>; - + /// This routine collects list of properties to be implemented in the class. /// This includes, class's and its conforming protocols' properties. /// Note, the superclass's properties are not included in the list. @@ -1195,15 +1195,15 @@ class ObjCInterfaceDecl : public ObjCContainerDecl /// TypeForDecl - This indicates the Type object that represents this /// TypeDecl. It is a cache maintained by ASTContext::getObjCInterfaceType mutable const Type *TypeForDecl = nullptr; - + struct DefinitionData { - /// The definition of this class, for quick access from any + /// The definition of this class, for quick access from any /// declaration. ObjCInterfaceDecl *Definition = nullptr; - + /// When non-null, this is always an ObjCObjectType. TypeSourceInfo *SuperClassTInfo = nullptr; - + /// Protocols referenced in the \@interface declaration ObjCProtocolList ReferencedProtocols; @@ -1247,11 +1247,11 @@ class ObjCInterfaceDecl : public ObjCContainerDecl /// One of the \c InheritedDesignatedInitializersState enumeratos. mutable unsigned InheritedDesignatedInitializers : 2; - + /// The location of the last location in this declaration, before - /// the properties/methods. For example, this will be the '>', '}', or - /// identifier, - SourceLocation EndLoc; + /// the properties/methods. For example, this will be the '>', '}', or + /// identifier, + SourceLocation EndLoc; DefinitionData() : ExternallyCompleted(false), IvarListMissingImplementation(true), @@ -1285,7 +1285,7 @@ class ObjCInterfaceDecl : public ObjCContainerDecl /// Allocate the definition data for this class. void allocateDefinitionData(); - + using redeclarable_base = Redeclarable<ObjCInterfaceDecl>; ObjCInterfaceDecl *getNextRedeclarationImpl() override { @@ -1334,7 +1334,7 @@ public: SourceRange getSourceRange() const override LLVM_READONLY { if (isThisDeclarationADefinition()) return ObjCContainerDecl::getSourceRange(); - + return SourceRange(getAtStartLoc(), getLocation()); } @@ -1390,7 +1390,7 @@ public: // FIXME: Should make sure no callers ever do this. if (!hasDefinition()) return protocol_iterator(); - + if (data().ExternallyCompleted) LoadExternalDefinition(); @@ -1453,7 +1453,7 @@ public: if (data().ExternallyCompleted) LoadExternalDefinition(); - return data().AllReferencedProtocols.empty() + return data().AllReferencedProtocols.empty() ? protocol_begin() : data().AllReferencedProtocols.begin(); } @@ -1462,11 +1462,11 @@ public: // FIXME: Should make sure no callers ever do this. if (!hasDefinition()) return all_protocol_iterator(); - + if (data().ExternallyCompleted) LoadExternalDefinition(); - return data().AllReferencedProtocols.empty() + return data().AllReferencedProtocols.empty() ? protocol_end() : data().AllReferencedProtocols.end(); } @@ -1476,17 +1476,17 @@ public: ivar_range ivars() const { return ivar_range(ivar_begin(), ivar_end()); } - ivar_iterator ivar_begin() const { + ivar_iterator ivar_begin() const { if (const ObjCInterfaceDecl *Def = getDefinition()) - return ivar_iterator(Def->decls_begin()); - + return ivar_iterator(Def->decls_begin()); + // FIXME: Should make sure no callers ever do this. return ivar_iterator(); } - ivar_iterator ivar_end() const { + ivar_iterator ivar_end() const { if (const ObjCInterfaceDecl *Def = getDefinition()) - return ivar_iterator(Def->decls_end()); + return ivar_iterator(Def->decls_end()); // FIXME: Should make sure no callers ever do this. return ivar_iterator(); @@ -1546,10 +1546,10 @@ public: /// Determine whether this particular declaration of this class is /// actually also a definition. - bool isThisDeclarationADefinition() const { + bool isThisDeclarationADefinition() const { return getDefinition() == this; } - + /// Determine whether this class has been defined. bool hasDefinition() const { // If the name of this class is out-of-date, bring it up-to-date, which @@ -1561,16 +1561,16 @@ public: return Data.getPointer(); } - - /// Retrieve the definition of this class, or NULL if this class - /// has been forward-declared (with \@class) but not yet defined (with + + /// Retrieve the definition of this class, or NULL if this class + /// has been forward-declared (with \@class) but not yet defined (with /// \@interface). ObjCInterfaceDecl *getDefinition() { return hasDefinition()? Data.getPointer()->Definition : nullptr; } - /// Retrieve the definition of this class, or NULL if this class - /// has been forward-declared (with \@class) but not yet defined (with + /// Retrieve the definition of this class, or NULL if this class + /// has been forward-declared (with \@class) but not yet defined (with /// \@interface). const ObjCInterfaceDecl *getDefinition() const { return hasDefinition()? Data.getPointer()->Definition : nullptr; @@ -1579,7 +1579,7 @@ public: /// Starts the definition of this Objective-C class, taking it from /// a forward declaration (\@class) to a definition (\@interface). void startDefinition(); - + /// Retrieve the superclass type. const ObjCObjectType *getSuperClassType() const { if (TypeSourceInfo *TInfo = getSuperClassTInfo()) @@ -1593,7 +1593,7 @@ public: // FIXME: Should make sure no callers ever do this. if (!hasDefinition()) return nullptr; - + if (data().ExternallyCompleted) LoadExternalDefinition(); @@ -1604,7 +1604,7 @@ public: // does not include any type arguments that apply to the superclass. ObjCInterfaceDecl *getSuperClass() const; - void setSuperClass(TypeSourceInfo *superClass) { + void setSuperClass(TypeSourceInfo *superClass) { data().SuperClassTInfo = superClass; } @@ -1618,7 +1618,7 @@ public: ObjCCategoryDecl *Current = nullptr; void findAcceptableCategory(); - + public: using value_type = ObjCCategoryDecl *; using reference = value_type; @@ -1659,7 +1659,7 @@ private: /// /// Used in the \c visible_categories_iterator. static bool isVisibleCategory(ObjCCategoryDecl *Cat); - + public: /// Iterator that walks over the list of categories and extensions /// that are visible, i.e., not hidden in a non-imported submodule. @@ -1765,7 +1765,7 @@ private: /// /// Used in the \c known_extensions_iterator. static bool isKnownExtension(ObjCCategoryDecl *Cat); - + public: friend class ASTDeclReader; friend class ASTDeclWriter; @@ -1787,7 +1787,7 @@ public: known_extensions_iterator known_extensions_begin() const { return known_extensions_iterator(getCategoryListRaw()); } - + /// Retrieve an iterator to the end of the known-extensions list. known_extensions_iterator known_extensions_end() const { return known_extensions_iterator(); @@ -1804,7 +1804,7 @@ public: // FIXME: Should make sure no callers ever do this. if (!hasDefinition()) return nullptr; - + if (data().ExternallyCompleted) LoadExternalDefinition(); @@ -1831,7 +1831,7 @@ public: while (I != nullptr) { if (declaresSameEntity(this, I)) return true; - + I = I->getSuperClass(); } return false; @@ -1841,7 +1841,7 @@ public: /// to be incompatible with __weak references. Returns true if it is. bool isArcWeakrefUnavailable() const; - /// isObjCRequiresPropertyDefs - Checks that a class or one of its super + /// isObjCRequiresPropertyDefs - Checks that a class or one of its super /// classes must not be auto-synthesized. Returns class decl. if it must not /// be; 0, otherwise. const ObjCInterfaceDecl *isObjCRequiresPropertyDefs() const; @@ -1854,7 +1854,7 @@ public: } ObjCProtocolDecl *lookupNestedProtocol(IdentifierInfo *Name); - + // Lookup a method. First, we search locally. If a method isn't // found, we search referenced protocols and class categories. ObjCMethodDecl *lookupMethod(Selector Sel, bool isInstance, @@ -1893,14 +1893,14 @@ public: true /* followsSuper */, Cat); } - - SourceLocation getEndOfDefinitionLoc() const { + + SourceLocation getEndOfDefinitionLoc() const { if (!hasDefinition()) return getLocation(); - - return data().EndLoc; + + return data().EndLoc; } - + void setEndOfDefinitionLoc(SourceLocation LE) { data().EndLoc = LE; } /// Retrieve the starting location of the superclass. @@ -1909,7 +1909,7 @@ public: /// isImplicitInterfaceDecl - check that this is an implicitly declared /// ObjCInterfaceDecl node. This is for legacy objective-c \@implementation /// declaration without an \@interface declaration. - bool isImplicitInterfaceDecl() const { + bool isImplicitInterfaceDecl() const { return hasDefinition() ? data().Definition->isImplicit() : isImplicit(); } @@ -1987,7 +1987,7 @@ public: bool synthesized=false); static ObjCIvarDecl *CreateDeserialized(ASTContext &C, unsigned ID); - + /// Return the class interface that this ivar is logically contained /// in; this is either the interface where the ivar was declared, or the /// interface the ivar is conceptually a part of in the case of synthesized @@ -2045,7 +2045,7 @@ public: QualType T, Expr *BW); static ObjCAtDefsFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID); - + // Implement isa/cast/dyncast/etc. static bool classof(const Decl *D) { return classofKind(D->getKind()); } static bool classofKind(Kind K) { return K == ObjCAtDefsField; } @@ -2087,7 +2087,7 @@ class ObjCProtocolDecl : public ObjCContainerDecl, ObjCProtocolDecl *Definition; /// Referenced protocols - ObjCProtocolList ReferencedProtocols; + ObjCProtocolList ReferencedProtocols; }; /// Contains a pointer to the data associated with this class, @@ -2107,7 +2107,7 @@ class ObjCProtocolDecl : public ObjCContainerDecl, assert(Data.getPointer() && "Objective-C protocol has no definition!"); return *Data.getPointer(); } - + void allocateDefinitionData(); using redeclarable_base = Redeclarable<ObjCProtocolDecl>; @@ -2152,15 +2152,15 @@ public: protocol_iterator protocol_begin() const { if (!hasDefinition()) return protocol_iterator(); - + return data().ReferencedProtocols.begin(); } - protocol_iterator protocol_end() const { + protocol_iterator protocol_end() const { if (!hasDefinition()) return protocol_iterator(); - - return data().ReferencedProtocols.end(); + + return data().ReferencedProtocols.end(); } using protocol_loc_iterator = ObjCProtocolList::loc_iterator; @@ -2173,22 +2173,22 @@ public: protocol_loc_iterator protocol_loc_begin() const { if (!hasDefinition()) return protocol_loc_iterator(); - + return data().ReferencedProtocols.loc_begin(); } protocol_loc_iterator protocol_loc_end() const { if (!hasDefinition()) return protocol_loc_iterator(); - + return data().ReferencedProtocols.loc_end(); } - unsigned protocol_size() const { + unsigned protocol_size() const { if (!hasDefinition()) return 0; - - return data().ReferencedProtocols.size(); + + return data().ReferencedProtocols.size(); } /// setProtocolList - Set the list of protocols that this interface @@ -2235,12 +2235,12 @@ public: return hasDefinition()? Data.getPointer()->Definition : nullptr; } - /// Determine whether this particular declaration is also the + /// Determine whether this particular declaration is also the /// definition. bool isThisDeclarationADefinition() const { return getDefinition() == this; } - + /// Starts the definition of this Objective-C protocol. void startDefinition(); @@ -2251,10 +2251,10 @@ public: SourceRange getSourceRange() const override LLVM_READONLY { if (isThisDeclarationADefinition()) return ObjCContainerDecl::getSourceRange(); - + return SourceRange(getAtStartLoc(), getLocation()); } - + using redecl_range = redeclarable_base::redecl_range; using redecl_iterator = redeclarable_base::redecl_iterator; @@ -2316,7 +2316,7 @@ class ObjCCategoryDecl : public ObjCContainerDecl { /// class extension may have private ivars. SourceLocation IvarLBraceLoc; SourceLocation IvarRBraceLoc; - + ObjCCategoryDecl(DeclContext *DC, SourceLocation AtLoc, SourceLocation ClassNameLoc, SourceLocation CategoryNameLoc, IdentifierInfo *Id, ObjCInterfaceDecl *IDecl, @@ -2431,7 +2431,7 @@ public: SourceLocation getCategoryNameLoc() const { return CategoryNameLoc; } void setCategoryNameLoc(SourceLocation Loc) { CategoryNameLoc = Loc; } - + void setIvarLBraceLoc(SourceLocation Loc) { IvarLBraceLoc = Loc; } SourceLocation getIvarLBraceLoc() const { return IvarLBraceLoc; } void setIvarRBraceLoc(SourceLocation Loc) { IvarRBraceLoc = Loc; } @@ -2576,7 +2576,7 @@ class ObjCImplementationDecl : public ObjCImplDecl { /// \@implementation may have private ivars. SourceLocation IvarLBraceLoc; SourceLocation IvarRBraceLoc; - + /// Support for ivar initialization. /// The arguments used to initialize the ivars LazyCXXCtorInitializersPtr IvarInitializers; @@ -2594,7 +2594,7 @@ class ObjCImplementationDecl : public ObjCImplDecl { ObjCInterfaceDecl *superDecl, SourceLocation nameLoc, SourceLocation atStartLoc, SourceLocation superLoc = SourceLocation(), - SourceLocation IvarLBraceLoc=SourceLocation(), + SourceLocation IvarLBraceLoc=SourceLocation(), SourceLocation IvarRBraceLoc=SourceLocation()) : ObjCImplDecl(ObjCImplementation, DC, classInterface, classInterface ? classInterface->getIdentifier() @@ -2616,7 +2616,7 @@ public: SourceLocation nameLoc, SourceLocation atStartLoc, SourceLocation superLoc = SourceLocation(), - SourceLocation IvarLBraceLoc=SourceLocation(), + SourceLocation IvarLBraceLoc=SourceLocation(), SourceLocation IvarRBraceLoc=SourceLocation()); static ObjCImplementationDecl *CreateDeserialized(ASTContext &C, unsigned ID); @@ -2700,7 +2700,7 @@ public: std::string getNameAsString() const { return getName(); } - + /// Produce a name to be used for class's metadata. It comes either via /// class's objc_runtime_name attribute or class name. StringRef getObjCRuntimeNameAsString() const; @@ -2715,7 +2715,7 @@ public: SourceLocation getIvarLBraceLoc() const { return IvarLBraceLoc; } void setIvarRBraceLoc(SourceLocation Loc) { IvarRBraceLoc = Loc; } SourceLocation getIvarRBraceLoc() const { return IvarRBraceLoc; } - + using ivar_iterator = specific_decl_iterator<ObjCIvarDecl>; using ivar_range = llvm::iterator_range<specific_decl_iterator<ObjCIvarDecl>>; @@ -2760,9 +2760,9 @@ public: SourceLocation L, IdentifierInfo *Id, ObjCInterfaceDecl* aliasedClass); - static ObjCCompatibleAliasDecl *CreateDeserialized(ASTContext &C, + static ObjCCompatibleAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID); - + const ObjCInterfaceDecl *getClassInterface() const { return AliasedClass; } ObjCInterfaceDecl *getClassInterface() { return AliasedClass; } void setClassInterface(ObjCInterfaceDecl *D) { AliasedClass = D; } diff --git a/include/clang/AST/DeclTemplate.h b/include/clang/AST/DeclTemplate.h index a2f00ec9ffa2..e0ea7cb8b1b8 100644 --- a/include/clang/AST/DeclTemplate.h +++ b/include/clang/AST/DeclTemplate.h @@ -734,8 +734,8 @@ public: }; /// Declaration of a redeclarable template. -class RedeclarableTemplateDecl : public TemplateDecl, - public Redeclarable<RedeclarableTemplateDecl> +class RedeclarableTemplateDecl : public TemplateDecl, + public Redeclarable<RedeclarableTemplateDecl> { using redeclarable_base = Redeclarable<RedeclarableTemplateDecl>; @@ -823,7 +823,7 @@ protected: /// Pointer to the common data shared by all declarations of this /// template. mutable CommonBase *Common = nullptr; - + /// Retrieves the "common" pointer shared by all (re-)declarations of /// the same template. Calling this routine may implicitly allocate memory /// for the common pointer. @@ -888,10 +888,10 @@ public: } /// Retrieve the member template from which this template was - /// instantiated, or nullptr if this template was not instantiated from a + /// instantiated, or nullptr if this template was not instantiated from a /// member template. /// - /// A template is instantiated from a member template when the member + /// A template is instantiated from a member template when the member /// template itself is part of a class template (or member thereof). For /// example, given /// @@ -1178,7 +1178,7 @@ public: unsigned D, unsigned P, IdentifierInfo *Id, bool Typename, bool ParameterPack); - static TemplateTypeParmDecl *CreateDeserialized(const ASTContext &C, + static TemplateTypeParmDecl *CreateDeserialized(const ASTContext &C, unsigned ID); /// Whether this template type parameter was declared with @@ -1312,12 +1312,12 @@ public: QualType T, TypeSourceInfo *TInfo, ArrayRef<QualType> ExpandedTypes, ArrayRef<TypeSourceInfo *> ExpandedTInfos); - static NonTypeTemplateParmDecl *CreateDeserialized(ASTContext &C, + static NonTypeTemplateParmDecl *CreateDeserialized(ASTContext &C, unsigned ID); - static NonTypeTemplateParmDecl *CreateDeserialized(ASTContext &C, + static NonTypeTemplateParmDecl *CreateDeserialized(ASTContext &C, unsigned ID, unsigned NumExpandedTypes); - + using TemplateParmPosition::getDepth; using TemplateParmPosition::setDepth; using TemplateParmPosition::getPosition; @@ -1495,7 +1495,7 @@ public: static TemplateTemplateParmDecl *CreateDeserialized(ASTContext &C, unsigned ID, unsigned NumExpansions); - + using TemplateParmPosition::getDepth; using TemplateParmPosition::setDepth; using TemplateParmPosition::getPosition; @@ -2442,7 +2442,7 @@ public: static ClassScopeFunctionSpecializationDecl * CreateDeserialized(ASTContext &Context, unsigned ID); - + // Implement isa/cast/dyncast/etc. static bool classof(const Decl *D) { return classofKind(D->getKind()); } diff --git a/include/clang/AST/DeclarationName.h b/include/clang/AST/DeclarationName.h index 9d3dad6bbd9d..856f3ab5720e 100644 --- a/include/clang/AST/DeclarationName.h +++ b/include/clang/AST/DeclarationName.h @@ -211,14 +211,14 @@ public: /// getNameKind - Determine what kind of name this is. NameKind getNameKind() const; - /// Determines whether the name itself is dependent, e.g., because it + /// Determines whether the name itself is dependent, e.g., because it /// involves a C++ type that is itself dependent. /// /// Note that this does not capture all of the notions of "dependent name", - /// because an identifier can be a dependent name if it is used as the + /// because an identifier can be a dependent name if it is used as the /// callee in a call expression with dependent arguments. bool isDependentName() const; - + /// getNameAsString - Retrieve the human-readable string for this name. std::string getAsString() const; @@ -543,7 +543,7 @@ public: /// Determine whether this name involves a template parameter. bool isInstantiationDependent() const; - + /// Determine whether this name contains an unexpanded /// parameter pack. bool containsUnexpandedParameterPack() const; @@ -558,7 +558,7 @@ public: SourceLocation getBeginLoc() const { return NameLoc; } /// getEndLoc - Retrieve the location of the last token. - SourceLocation getEndLoc() const; + SourceLocation getEndLoc() const { return getLocEnd(); } /// getSourceRange - The range of the declaration name. SourceRange getSourceRange() const LLVM_READONLY { @@ -570,9 +570,11 @@ public: } SourceLocation getLocEnd() const LLVM_READONLY { - SourceLocation EndLoc = getEndLoc(); + SourceLocation EndLoc = getEndLocPrivate(); return EndLoc.isValid() ? EndLoc : getLocStart(); } +private: + SourceLocation getEndLocPrivate() const; }; /// Insertion operator for diagnostics. This allows sending DeclarationName's diff --git a/include/clang/AST/DependentDiagnostic.h b/include/clang/AST/DependentDiagnostic.h index a514326c6cb1..c21ef7907b8a 100644 --- a/include/clang/AST/DependentDiagnostic.h +++ b/include/clang/AST/DependentDiagnostic.h @@ -101,9 +101,9 @@ private: friend class DependentStoredDeclsMap; DependentDiagnostic(const PartialDiagnostic &PDiag, - PartialDiagnostic::Storage *Storage) + PartialDiagnostic::Storage *Storage) : Diag(PDiag, Storage) {} - + static DependentDiagnostic *Create(ASTContext &Context, DeclContext *Parent, const PartialDiagnostic &PDiag); diff --git a/include/clang/AST/EvaluatedExprVisitor.h b/include/clang/AST/EvaluatedExprVisitor.h index e00986dbe9c8..1aec5ae842d4 100644 --- a/include/clang/AST/EvaluatedExprVisitor.h +++ b/include/clang/AST/EvaluatedExprVisitor.h @@ -21,9 +21,9 @@ #include "clang/AST/StmtVisitor.h" namespace clang { - + class ASTContext; - + /// Given a potentially-evaluated expression, this visitor visits all /// of its potentially-evaluated subexpressions, recursively. template<template <typename> class Ptr, typename ImplClass> diff --git a/include/clang/AST/Expr.h b/include/clang/AST/Expr.h index 7585231e62e5..c18fbf05df68 100644 --- a/include/clang/AST/Expr.h +++ b/include/clang/AST/Expr.h @@ -884,7 +884,7 @@ public: : Expr(OpaqueValueExprClass, T, VK, OK, T->isDependentType() || (SourceExpr && SourceExpr->isTypeDependent()), - T->isDependentType() || + T->isDependentType() || (SourceExpr && SourceExpr->isValueDependent()), T->isInstantiationDependentType() || (SourceExpr && SourceExpr->isInstantiationDependent()), @@ -2787,20 +2787,26 @@ public: /// representation in the source code (ExplicitCastExpr's derived /// classes). class CastExpr : public Expr { +public: + using BasePathSizeTy = unsigned int; + static_assert(std::numeric_limits<BasePathSizeTy>::max() >= 16384, + "[implimits] Direct and indirect base classes [16384]."); + private: Stmt *Op; bool CastConsistency() const; + BasePathSizeTy *BasePathSize(); + const CXXBaseSpecifier * const *path_buffer() const { return const_cast<CastExpr*>(this)->path_buffer(); } CXXBaseSpecifier **path_buffer(); - void setBasePathSize(unsigned basePathSize) { - CastExprBits.BasePathSize = basePathSize; - assert(CastExprBits.BasePathSize == basePathSize && - "basePathSize doesn't fit in bits of CastExprBits.BasePathSize!"); + void setBasePathSize(BasePathSizeTy basePathSize) { + assert(!path_empty() && basePathSize != 0); + *(BasePathSize()) = basePathSize; } protected: @@ -2823,7 +2829,9 @@ protected: Op(op) { CastExprBits.Kind = kind; CastExprBits.PartOfExplicitCast = false; - setBasePathSize(BasePathSize); + CastExprBits.BasePathIsEmpty = BasePathSize == 0; + if (!path_empty()) + setBasePathSize(BasePathSize); assert(CastConsistency()); } @@ -2831,7 +2839,9 @@ protected: CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize) : Expr(SC, Empty) { CastExprBits.PartOfExplicitCast = false; - setBasePathSize(BasePathSize); + CastExprBits.BasePathIsEmpty = BasePathSize == 0; + if (!path_empty()) + setBasePathSize(BasePathSize); } public: @@ -2859,8 +2869,12 @@ public: typedef CXXBaseSpecifier **path_iterator; typedef const CXXBaseSpecifier * const *path_const_iterator; - bool path_empty() const { return CastExprBits.BasePathSize == 0; } - unsigned path_size() const { return CastExprBits.BasePathSize; } + bool path_empty() const { return CastExprBits.BasePathIsEmpty; } + unsigned path_size() const { + if (path_empty()) + return 0U; + return *(const_cast<CastExpr *>(this)->BasePathSize()); + } path_iterator path_begin() { return path_buffer(); } path_iterator path_end() { return path_buffer() + path_size(); } path_const_iterator path_begin() const { return path_buffer(); } @@ -2908,7 +2922,12 @@ public: /// @endcode class ImplicitCastExpr final : public CastExpr, - private llvm::TrailingObjects<ImplicitCastExpr, CXXBaseSpecifier *> { + private llvm::TrailingObjects<ImplicitCastExpr, CastExpr::BasePathSizeTy, + CXXBaseSpecifier *> { + size_t numTrailingObjects(OverloadToken<CastExpr::BasePathSizeTy>) const { + return path_empty() ? 0 : 1; + } + private: ImplicitCastExpr(QualType ty, CastKind kind, Expr *op, unsigned BasePathLength, ExprValueKind VK) @@ -3013,7 +3032,8 @@ public: /// (Type)expr. For example: @c (int)f. class CStyleCastExpr final : public ExplicitCastExpr, - private llvm::TrailingObjects<CStyleCastExpr, CXXBaseSpecifier *> { + private llvm::TrailingObjects<CStyleCastExpr, CastExpr::BasePathSizeTy, + CXXBaseSpecifier *> { SourceLocation LPLoc; // the location of the left paren SourceLocation RPLoc; // the location of the right paren @@ -3027,6 +3047,10 @@ class CStyleCastExpr final explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize) : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize) { } + size_t numTrailingObjects(OverloadToken<CastExpr::BasePathSizeTy>) const { + return path_empty() ? 0 : 1; + } + public: static CStyleCastExpr *Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind K, @@ -5341,7 +5365,7 @@ public: SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); } SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); } - + static bool classof(const Stmt *T) { return T->getStmtClass() == TypoExprClass; } diff --git a/include/clang/AST/ExprCXX.h b/include/clang/AST/ExprCXX.h index 8206a26b2c4b..7ab8020dec64 100644 --- a/include/clang/AST/ExprCXX.h +++ b/include/clang/AST/ExprCXX.h @@ -301,7 +301,8 @@ public: /// \c static_cast<int>(1.0). class CXXStaticCastExpr final : public CXXNamedCastExpr, - private llvm::TrailingObjects<CXXStaticCastExpr, CXXBaseSpecifier *> { + private llvm::TrailingObjects<CXXStaticCastExpr, CastExpr::BasePathSizeTy, + CXXBaseSpecifier *> { CXXStaticCastExpr(QualType ty, ExprValueKind vk, CastKind kind, Expr *op, unsigned pathSize, TypeSourceInfo *writtenTy, SourceLocation l, SourceLocation RParenLoc, @@ -312,6 +313,10 @@ class CXXStaticCastExpr final explicit CXXStaticCastExpr(EmptyShell Empty, unsigned PathSize) : CXXNamedCastExpr(CXXStaticCastExprClass, Empty, PathSize) {} + size_t numTrailingObjects(OverloadToken<CastExpr::BasePathSizeTy>) const { + return path_empty() ? 0 : 1; + } + public: friend class CastExpr; friend TrailingObjects; @@ -337,7 +342,8 @@ public: /// check to determine how to perform the type conversion. class CXXDynamicCastExpr final : public CXXNamedCastExpr, - private llvm::TrailingObjects<CXXDynamicCastExpr, CXXBaseSpecifier *> { + private llvm::TrailingObjects< + CXXDynamicCastExpr, CastExpr::BasePathSizeTy, CXXBaseSpecifier *> { CXXDynamicCastExpr(QualType ty, ExprValueKind VK, CastKind kind, Expr *op, unsigned pathSize, TypeSourceInfo *writtenTy, SourceLocation l, SourceLocation RParenLoc, @@ -348,6 +354,10 @@ class CXXDynamicCastExpr final explicit CXXDynamicCastExpr(EmptyShell Empty, unsigned pathSize) : CXXNamedCastExpr(CXXDynamicCastExprClass, Empty, pathSize) {} + size_t numTrailingObjects(OverloadToken<CastExpr::BasePathSizeTy>) const { + return path_empty() ? 0 : 1; + } + public: friend class CastExpr; friend TrailingObjects; @@ -380,6 +390,7 @@ public: class CXXReinterpretCastExpr final : public CXXNamedCastExpr, private llvm::TrailingObjects<CXXReinterpretCastExpr, + CastExpr::BasePathSizeTy, CXXBaseSpecifier *> { CXXReinterpretCastExpr(QualType ty, ExprValueKind vk, CastKind kind, Expr *op, unsigned pathSize, @@ -392,6 +403,10 @@ class CXXReinterpretCastExpr final CXXReinterpretCastExpr(EmptyShell Empty, unsigned pathSize) : CXXNamedCastExpr(CXXReinterpretCastExprClass, Empty, pathSize) {} + size_t numTrailingObjects(OverloadToken<CastExpr::BasePathSizeTy>) const { + return path_empty() ? 0 : 1; + } + public: friend class CastExpr; friend TrailingObjects; @@ -419,7 +434,8 @@ public: /// value. class CXXConstCastExpr final : public CXXNamedCastExpr, - private llvm::TrailingObjects<CXXConstCastExpr, CXXBaseSpecifier *> { + private llvm::TrailingObjects<CXXConstCastExpr, CastExpr::BasePathSizeTy, + CXXBaseSpecifier *> { CXXConstCastExpr(QualType ty, ExprValueKind VK, Expr *op, TypeSourceInfo *writtenTy, SourceLocation l, SourceLocation RParenLoc, SourceRange AngleBrackets) @@ -429,6 +445,10 @@ class CXXConstCastExpr final explicit CXXConstCastExpr(EmptyShell Empty) : CXXNamedCastExpr(CXXConstCastExprClass, Empty, 0) {} + size_t numTrailingObjects(OverloadToken<CastExpr::BasePathSizeTy>) const { + return path_empty() ? 0 : 1; + } + public: friend class CastExpr; friend TrailingObjects; @@ -721,7 +741,7 @@ public: } }; -/// A member reference to an MSPropertyDecl. +/// A member reference to an MSPropertyDecl. /// /// This expression always has pseudo-object type, and therefore it is /// typically not encountered in a fully-typechecked expression except @@ -1471,7 +1491,8 @@ public: /// \endcode class CXXFunctionalCastExpr final : public ExplicitCastExpr, - private llvm::TrailingObjects<CXXFunctionalCastExpr, CXXBaseSpecifier *> { + private llvm::TrailingObjects< + CXXFunctionalCastExpr, CastExpr::BasePathSizeTy, CXXBaseSpecifier *> { SourceLocation LParenLoc; SourceLocation RParenLoc; @@ -1486,6 +1507,10 @@ class CXXFunctionalCastExpr final explicit CXXFunctionalCastExpr(EmptyShell Shell, unsigned PathSize) : ExplicitCastExpr(CXXFunctionalCastExprClass, Shell, PathSize) {} + size_t numTrailingObjects(OverloadToken<CastExpr::BasePathSizeTy>) const { + return path_empty() ? 0 : 1; + } + public: friend class CastExpr; friend TrailingObjects; @@ -1591,7 +1616,7 @@ class LambdaExpr final : public Expr, /// The number of captures. unsigned NumCaptures : 16; - + /// The default capture kind, which is a value of type /// LambdaCaptureDefault. unsigned CaptureDefault : 2; @@ -1602,10 +1627,10 @@ class LambdaExpr final : public Expr, /// Whether this lambda had the result type explicitly specified. unsigned ExplicitResultType : 1; - + /// The location of the closing brace ('}') that completes /// the lambda. - /// + /// /// The location of the brace is also available by looking up the /// function call operator in the lambda class. However, it is /// stored here to improve the performance of getSourceRange(), and @@ -1673,7 +1698,7 @@ public: /// Retrieve this lambda's captures. capture_range captures() const; - + /// Retrieve an iterator pointing to the first lambda capture. capture_iterator capture_begin() const; @@ -1686,7 +1711,7 @@ public: /// Retrieve this lambda's explicit captures. capture_range explicit_captures() const; - + /// Retrieve an iterator pointing to the first explicit /// lambda capture. capture_iterator explicit_capture_begin() const; @@ -1754,18 +1779,18 @@ public: SourceRange getIntroducerRange() const { return IntroducerRange; } /// Retrieve the class that corresponds to the lambda. - /// + /// /// This is the "closure type" (C++1y [expr.prim.lambda]), and stores the /// captures in its fields and provides the various operations permitted /// on a lambda (copying, calling). CXXRecordDecl *getLambdaClass() const; /// Retrieve the function call operator associated with this - /// lambda expression. + /// lambda expression. CXXMethodDecl *getCallOperator() const; - /// If this is a generic lambda expression, retrieve the template - /// parameter list associated with it, or else return null. + /// If this is a generic lambda expression, retrieve the template + /// parameter list associated with it, or else return null. TemplateParameterList *getTemplateParameterList() const; /// Whether this is a generic lambda. @@ -1784,7 +1809,7 @@ public: /// Whether this lambda had its result type explicitly specified. bool hasExplicitResultType() const { return ExplicitResultType; } - + static bool classof(const Stmt *T) { return T->getStmtClass() == LambdaExprClass; } @@ -2129,7 +2154,7 @@ public: Expr *getArgument() { return cast<Expr>(Argument); } const Expr *getArgument() const { return cast<Expr>(Argument); } - /// Retrieve the type being destroyed. + /// Retrieve the type being destroyed. /// /// If the type being destroyed is a dependent type which may or may not /// be a pointer, return an invalid type. @@ -2345,13 +2370,13 @@ class TypeTraitExpr final private llvm::TrailingObjects<TypeTraitExpr, TypeSourceInfo *> { /// The location of the type trait keyword. SourceLocation Loc; - + /// The location of the closing parenthesis. SourceLocation RParenLoc; - + // Note: The TypeSourceInfos for the arguments are allocated after the // TypeTraitExpr. - + TypeTraitExpr(QualType T, SourceLocation Loc, TypeTrait Kind, ArrayRef<TypeSourceInfo *> Args, SourceLocation RParenLoc, @@ -2377,26 +2402,26 @@ public: static TypeTraitExpr *CreateDeserialized(const ASTContext &C, unsigned NumArgs); - + /// Determine which type trait this expression uses. TypeTrait getTrait() const { return static_cast<TypeTrait>(TypeTraitExprBits.Kind); } - bool getValue() const { - assert(!isValueDependent()); - return TypeTraitExprBits.Value; + bool getValue() const { + assert(!isValueDependent()); + return TypeTraitExprBits.Value; } - + /// Determine the number of arguments to this type trait. unsigned getNumArgs() const { return TypeTraitExprBits.NumArgs; } - + /// Retrieve the Ith argument. TypeSourceInfo *getArg(unsigned I) const { assert(I < getNumArgs() && "Argument out-of-range"); return getArgs()[I]; } - + /// Retrieve the argument types. ArrayRef<TypeSourceInfo *> getArgs() const { return llvm::makeArrayRef(getTrailingObjects<TypeSourceInfo *>(), @@ -2409,7 +2434,7 @@ public: static bool classof(const Stmt *T) { return T->getStmtClass() == TypeTraitExprClass; } - + // Iterators child_range children() { return child_range(child_iterator(), child_iterator()); diff --git a/include/clang/AST/ExprObjC.h b/include/clang/AST/ExprObjC.h index 5dac0e037da1..bb0402c27080 100644 --- a/include/clang/AST/ExprObjC.h +++ b/include/clang/AST/ExprObjC.h @@ -90,16 +90,16 @@ public: Value(val), Loc(l) {} explicit ObjCBoolLiteralExpr(EmptyShell Empty) : Expr(ObjCBoolLiteralExprClass, Empty) {} - + bool getValue() const { return Value; } void setValue(bool V) { Value = V; } - + SourceLocation getLocStart() const LLVM_READONLY { return Loc; } SourceLocation getLocEnd() const LLVM_READONLY { return Loc; } SourceLocation getLocation() const { return Loc; } void setLocation(SourceLocation L) { Loc = L; } - + // Iterators child_range children() { return child_range(child_iterator(), child_iterator()); @@ -124,30 +124,30 @@ public: ObjCBoxedExpr(Expr *E, QualType T, ObjCMethodDecl *method, SourceRange R) - : Expr(ObjCBoxedExprClass, T, VK_RValue, OK_Ordinary, - E->isTypeDependent(), E->isValueDependent(), + : Expr(ObjCBoxedExprClass, T, VK_RValue, OK_Ordinary, + E->isTypeDependent(), E->isValueDependent(), E->isInstantiationDependent(), - E->containsUnexpandedParameterPack()), + E->containsUnexpandedParameterPack()), SubExpr(E), BoxingMethod(method), Range(R) {} explicit ObjCBoxedExpr(EmptyShell Empty) : Expr(ObjCBoxedExprClass, Empty) {} - + Expr *getSubExpr() { return cast<Expr>(SubExpr); } const Expr *getSubExpr() const { return cast<Expr>(SubExpr); } - + ObjCMethodDecl *getBoxingMethod() const { - return BoxingMethod; + return BoxingMethod; } - + SourceLocation getAtLoc() const { return Range.getBegin(); } - + SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); } SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); } SourceRange getSourceRange() const LLVM_READONLY { return Range; } - + // Iterators child_range children() { return child_range(&SubExpr, &SubExpr+1); } @@ -208,7 +208,7 @@ public: /// getNumElements - Return number of elements of objective-c array literal. unsigned getNumElements() const { return NumElements; } - + /// getElement - Return the Element at the specified index. Expr *getElement(unsigned Index) { assert((Index < NumElements) && "Arg access out of range!"); @@ -218,11 +218,11 @@ public: assert((Index < NumElements) && "Arg access out of range!"); return getElements()[Index]; } - + ObjCMethodDecl *getArrayWithObjectsMethod() const { - return ArrayWithObjectsMethod; + return ArrayWithObjectsMethod; } - + // Iterators child_range children() { return child_range(reinterpret_cast<Stmt **>(getElements()), @@ -239,13 +239,13 @@ public: struct ObjCDictionaryElement { /// The key for the dictionary element. Expr *Key; - + /// The value of the dictionary element. Expr *Value; - + /// The location of the ellipsis, if this is a pack expansion. SourceLocation EllipsisLoc; - + /// The number of elements this pack expansion will expand to, if /// this is a pack expansion and is known. Optional<unsigned> NumExpansions; @@ -308,7 +308,7 @@ class ObjCDictionaryLiteral final using KeyValuePair = ObjCDictionaryLiteral_KeyValuePair; using ExpansionData = ObjCDictionaryLiteral_ExpansionData; - ObjCDictionaryLiteral(ArrayRef<ObjCDictionaryElement> VK, + ObjCDictionaryLiteral(ArrayRef<ObjCDictionaryElement> VK, bool HasPackExpansions, QualType T, ObjCMethodDecl *method, SourceRange SR); @@ -328,16 +328,16 @@ public: friend TrailingObjects; static ObjCDictionaryLiteral *Create(const ASTContext &C, - ArrayRef<ObjCDictionaryElement> VK, + ArrayRef<ObjCDictionaryElement> VK, bool HasPackExpansions, QualType T, ObjCMethodDecl *method, SourceRange SR); - + static ObjCDictionaryLiteral *CreateEmpty(const ASTContext &C, unsigned NumElements, bool HasPackExpansions); - - /// getNumElements - Return number of elements of objective-c dictionary + + /// getNumElements - Return number of elements of objective-c dictionary /// literal. unsigned getNumElements() const { return NumElements; } @@ -354,7 +354,7 @@ public: } return Result; } - + ObjCMethodDecl *getDictWithObjectsMethod() const { return DictWithObjectsMethod; } @@ -394,7 +394,7 @@ public: EncodedType->getType()->isDependentType(), EncodedType->getType()->isDependentType(), EncodedType->getType()->isInstantiationDependentType(), - EncodedType->getType()->containsUnexpandedParameterPack()), + EncodedType->getType()->containsUnexpandedParameterPack()), EncodedType(EncodedType), AtLoc(at), RParenLoc(rp) {} explicit ObjCEncodeExpr(EmptyShell Empty) : Expr(ObjCEncodeExprClass, Empty){} @@ -408,8 +408,8 @@ public: TypeSourceInfo *getEncodedTypeSourceInfo() const { return EncodedType; } - void setEncodedTypeSourceInfo(TypeSourceInfo *EncType) { - EncodedType = EncType; + void setEncodedTypeSourceInfo(TypeSourceInfo *EncType) { + EncodedType = EncType; } SourceLocation getLocStart() const LLVM_READONLY { return AtLoc; } @@ -531,9 +531,9 @@ public: bool arrow = false, bool freeIvar = false) : Expr(ObjCIvarRefExprClass, t, VK_LValue, d->isBitField() ? OK_BitField : OK_Ordinary, - /*TypeDependent=*/false, base->isValueDependent(), + /*TypeDependent=*/false, base->isValueDependent(), base->isInstantiationDependent(), - base->containsUnexpandedParameterPack()), + base->containsUnexpandedParameterPack()), D(d), Base(base), Loc(l), OpLoc(oploc), IsArrow(arrow), IsFreeIvar(freeIvar) {} @@ -560,7 +560,7 @@ public: return isFreeIvar() ? Loc : getBase()->getLocStart(); } SourceLocation getLocEnd() const LLVM_READONLY { return Loc; } - + SourceLocation getOpLoc() const { return OpLoc; } void setOpLoc(SourceLocation L) { OpLoc = L; } @@ -600,13 +600,13 @@ private: // transformation is lossy on the first character). SourceLocation IdLoc; - + /// When the receiver in property access is 'super', this is /// the location of the 'super' keyword. When it's an interface, /// this is that interface. SourceLocation ReceiverLoc; llvm::PointerUnion3<Stmt *, const Type *, ObjCInterfaceDecl *> Receiver; - + public: ObjCPropertyRefExpr(ObjCPropertyDecl *PD, QualType t, ExprValueKind VK, ExprObjectKind OK, @@ -618,7 +618,7 @@ public: PropertyOrGetter(PD, false), IdLoc(l), Receiver(base) { assert(t->isSpecificPlaceholderType(BuiltinType::PseudoObject)); } - + ObjCPropertyRefExpr(ObjCPropertyDecl *PD, QualType t, ExprValueKind VK, ExprObjectKind OK, SourceLocation l, SourceLocation sl, QualType st) @@ -716,19 +716,19 @@ public: setMethodRefFlag(MethodRef_Setter, val); } - const Expr *getBase() const { - return cast<Expr>(Receiver.get<Stmt*>()); + const Expr *getBase() const { + return cast<Expr>(Receiver.get<Stmt*>()); } - Expr *getBase() { - return cast<Expr>(Receiver.get<Stmt*>()); + Expr *getBase() { + return cast<Expr>(Receiver.get<Stmt*>()); } SourceLocation getLocation() const { return IdLoc; } - + SourceLocation getReceiverLocation() const { return ReceiverLoc; } - QualType getSuperReceiverType() const { - return QualType(Receiver.get<const Type*>(), 0); + QualType getSuperReceiverType() const { + return QualType(Receiver.get<const Type*>(), 0); } ObjCInterfaceDecl *getClassReceiver() const { @@ -796,7 +796,7 @@ private: SetterAndMethodRefFlags.setInt(f); } }; - + /// ObjCSubscriptRefExpr - used for array and dictionary subscripting. /// array[4] = array[3]; dictionary[key] = dictionary[alt_key]; class ObjCSubscriptRefExpr : public Expr { @@ -808,20 +808,20 @@ class ObjCSubscriptRefExpr : public Expr { // an objective-c object pointer expression. enum { BASE, KEY, END_EXPR }; Stmt* SubExprs[END_EXPR]; - + ObjCMethodDecl *GetAtIndexMethodDecl; - + // For immutable objects this is null. When ObjCSubscriptRefExpr is to read // an indexed object this is null too. ObjCMethodDecl *SetAtIndexMethodDecl; - + public: ObjCSubscriptRefExpr(Expr *base, Expr *key, QualType T, ExprValueKind VK, ExprObjectKind OK, ObjCMethodDecl *getMethod, ObjCMethodDecl *setMethod, SourceLocation RB) - : Expr(ObjCSubscriptRefExprClass, T, VK, OK, - base->isTypeDependent() || key->isTypeDependent(), + : Expr(ObjCSubscriptRefExprClass, T, VK, OK, + base->isTypeDependent() || key->isTypeDependent(), base->isValueDependent() || key->isValueDependent(), (base->isInstantiationDependent() || key->isInstantiationDependent()), @@ -834,7 +834,7 @@ public: explicit ObjCSubscriptRefExpr(EmptyShell Empty) : Expr(ObjCSubscriptRefExprClass, Empty) {} - + SourceLocation getRBracket() const { return RBracket; } void setRBracket(SourceLocation RB) { RBracket = RB; } @@ -843,25 +843,25 @@ public: } SourceLocation getLocEnd() const LLVM_READONLY { return RBracket; } - + Expr *getBaseExpr() const { return cast<Expr>(SubExprs[BASE]); } void setBaseExpr(Stmt *S) { SubExprs[BASE] = S; } - + Expr *getKeyExpr() const { return cast<Expr>(SubExprs[KEY]); } void setKeyExpr(Stmt *S) { SubExprs[KEY] = S; } - + ObjCMethodDecl *getAtIndexMethodDecl() const { return GetAtIndexMethodDecl; } - + ObjCMethodDecl *setAtIndexMethodDecl() const { return SetAtIndexMethodDecl; } - + bool isArraySubscriptRefExpr() const { return getKeyExpr()->getType()->isIntegralOrEnumerationType(); } - + child_range children() { return child_range(SubExprs, SubExprs+END_EXPR); } @@ -913,7 +913,7 @@ class ObjCMessageExpr final /// The number of arguments in the message send, not /// including the receiver. unsigned NumArgs : NumArgsBitWidth; - + /// The kind of message send this is, which is one of the /// ReceiverKind values. /// @@ -958,7 +958,7 @@ class ObjCMessageExpr final SourceLocation SuperLoc, bool IsInstanceSuper, QualType SuperType, - Selector Sel, + Selector Sel, ArrayRef<SourceLocation> SelLocs, SelectorLocationsKind SelLocsK, ObjCMethodDecl *Method, @@ -968,7 +968,7 @@ class ObjCMessageExpr final ObjCMessageExpr(QualType T, ExprValueKind VK, SourceLocation LBracLoc, TypeSourceInfo *Receiver, - Selector Sel, + Selector Sel, ArrayRef<SourceLocation> SelLocs, SelectorLocationsKind SelLocsK, ObjCMethodDecl *Method, @@ -978,7 +978,7 @@ class ObjCMessageExpr final ObjCMessageExpr(QualType T, ExprValueKind VK, SourceLocation LBracLoc, Expr *Receiver, - Selector Sel, + Selector Sel, ArrayRef<SourceLocation> SelLocs, SelectorLocationsKind SelLocsK, ObjCMethodDecl *Method, @@ -1091,7 +1091,7 @@ public: SourceLocation SuperLoc, bool IsInstanceSuper, QualType SuperType, - Selector Sel, + Selector Sel, ArrayRef<SourceLocation> SelLocs, ObjCMethodDecl *Method, ArrayRef<Expr *> Args, @@ -1125,7 +1125,7 @@ public: ExprValueKind VK, SourceLocation LBracLoc, TypeSourceInfo *Receiver, - Selector Sel, + Selector Sel, ArrayRef<SourceLocation> SelLocs, ObjCMethodDecl *Method, ArrayRef<Expr *> Args, @@ -1159,7 +1159,7 @@ public: ExprValueKind VK, SourceLocation LBracLoc, Expr *Receiver, - Selector Sel, + Selector Sel, ArrayRef<SourceLocation> SeLocs, ObjCMethodDecl *Method, ArrayRef<Expr *> Args, @@ -1215,14 +1215,14 @@ public: /// Turn this message send into an instance message that /// computes the receiver object with the given expression. - void setInstanceReceiver(Expr *rec) { + void setInstanceReceiver(Expr *rec) { Kind = Instance; setReceiverPointer(rec); } - + /// Returns the type of a class message send, or NULL if the /// message is not a class message. - QualType getClassReceiver() const { + QualType getClassReceiver() const { if (TypeSourceInfo *TSInfo = getClassReceiverTypeInfo()) return TSInfo->getType(); @@ -1244,7 +1244,7 @@ public: /// Retrieve the location of the 'super' keyword for a class /// or instance message to 'super', otherwise an invalid source location. - SourceLocation getSuperLoc() const { + SourceLocation getSuperLoc() const { if (getReceiverKind() == SuperInstance || getReceiverKind() == SuperClass) return SuperLoc; @@ -1274,7 +1274,7 @@ public: /// \returns The Objective-C interface if known, otherwise nullptr. ObjCInterfaceDecl *getReceiverInterface() const; - /// Retrieve the type referred to by 'super'. + /// Retrieve the type referred to by 'super'. /// /// The returned type will either be an ObjCInterfaceType (for an /// class message to super) or an ObjCObjectPointerType that refers @@ -1294,26 +1294,26 @@ public: Selector getSelector() const; - void setSelector(Selector S) { + void setSelector(Selector S) { HasMethod = false; SelectorOrMethod = reinterpret_cast<uintptr_t>(S.getAsOpaquePtr()); } - const ObjCMethodDecl *getMethodDecl() const { + const ObjCMethodDecl *getMethodDecl() const { if (HasMethod) return reinterpret_cast<const ObjCMethodDecl *>(SelectorOrMethod); return nullptr; } - ObjCMethodDecl *getMethodDecl() { + ObjCMethodDecl *getMethodDecl() { if (HasMethod) return reinterpret_cast<ObjCMethodDecl *>(SelectorOrMethod); return nullptr; } - void setMethodDecl(ObjCMethodDecl *MD) { + void setMethodDecl(ObjCMethodDecl *MD) { HasMethod = true; SelectorOrMethod = reinterpret_cast<uintptr_t>(MD); } @@ -1414,16 +1414,16 @@ public: arg_iterator arg_begin() { return reinterpret_cast<Stmt **>(getArgs()); } - arg_iterator arg_end() { - return reinterpret_cast<Stmt **>(getArgs() + NumArgs); + arg_iterator arg_end() { + return reinterpret_cast<Stmt **>(getArgs() + NumArgs); } - const_arg_iterator arg_begin() const { - return reinterpret_cast<Stmt const * const*>(getArgs()); + const_arg_iterator arg_begin() const { + return reinterpret_cast<Stmt const * const*>(getArgs()); } - const_arg_iterator arg_end() const { - return reinterpret_cast<Stmt const * const*>(getArgs() + NumArgs); + const_arg_iterator arg_end() const { + return reinterpret_cast<Stmt const * const*>(getArgs() + NumArgs); } static bool classof(const Stmt *T) { @@ -1439,7 +1439,7 @@ class ObjCIsaExpr : public Expr { /// IsaMemberLoc - This is the location of the 'isa'. SourceLocation IsaMemberLoc; - + /// OpLoc - This is the location of '.' or '->' SourceLocation OpLoc; @@ -1468,18 +1468,18 @@ public: /// location of 'F'. SourceLocation getIsaMemberLoc() const { return IsaMemberLoc; } void setIsaMemberLoc(SourceLocation L) { IsaMemberLoc = L; } - + SourceLocation getOpLoc() const { return OpLoc; } void setOpLoc(SourceLocation L) { OpLoc = L; } SourceLocation getLocStart() const LLVM_READONLY { return getBase()->getLocStart(); } - + SourceLocation getBaseLocEnd() const LLVM_READONLY { return getBase()->getLocEnd(); } - + SourceLocation getLocEnd() const LLVM_READONLY { return IsaMemberLoc; } SourceLocation getExprLoc() const LLVM_READONLY { return IsaMemberLoc; } @@ -1546,7 +1546,7 @@ public: /// copy-restore. If false, the temporary will be zero-initialized. bool shouldCopy() const { return ObjCIndirectCopyRestoreExprBits.ShouldCopy; } - child_range children() { return child_range(&Operand, &Operand+1); } + child_range children() { return child_range(&Operand, &Operand+1); } // Source locations are determined by the subexpression. SourceLocation getLocStart() const LLVM_READONLY { @@ -1571,7 +1571,8 @@ public: /// \endcode class ObjCBridgedCastExpr final : public ExplicitCastExpr, - private llvm::TrailingObjects<ObjCBridgedCastExpr, CXXBaseSpecifier *> { + private llvm::TrailingObjects< + ObjCBridgedCastExpr, CastExpr::BasePathSizeTy, CXXBaseSpecifier *> { friend class ASTStmtReader; friend class ASTStmtWriter; friend class CastExpr; @@ -1581,6 +1582,10 @@ class ObjCBridgedCastExpr final SourceLocation BridgeKeywordLoc; unsigned Kind : 2; + size_t numTrailingObjects(OverloadToken<CastExpr::BasePathSizeTy>) const { + return path_empty() ? 0 : 1; + } + public: ObjCBridgedCastExpr(SourceLocation LParenLoc, ObjCBridgeCastKind Kind, CastKind CK, SourceLocation BridgeKeywordLoc, @@ -1588,7 +1593,7 @@ public: : ExplicitCastExpr(ObjCBridgedCastExprClass, TSInfo->getType(), VK_RValue, CK, Operand, 0, TSInfo), LParenLoc(LParenLoc), BridgeKeywordLoc(BridgeKeywordLoc), Kind(Kind) {} - + /// Construct an empty Objective-C bridged cast. explicit ObjCBridgedCastExpr(EmptyShell Shell) : ExplicitCastExpr(ObjCBridgedCastExprClass, Shell, 0) {} @@ -1596,22 +1601,22 @@ public: SourceLocation getLParenLoc() const { return LParenLoc; } /// Determine which kind of bridge is being performed via this cast. - ObjCBridgeCastKind getBridgeKind() const { - return static_cast<ObjCBridgeCastKind>(Kind); + ObjCBridgeCastKind getBridgeKind() const { + return static_cast<ObjCBridgeCastKind>(Kind); } - + /// Retrieve the kind of bridge being performed as a string. StringRef getBridgeKindName() const; - + /// The location of the bridge keyword. SourceLocation getBridgeKeywordLoc() const { return BridgeKeywordLoc; } - + SourceLocation getLocStart() const LLVM_READONLY { return LParenLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return getSubExpr()->getLocEnd(); } - + static bool classof(const Stmt *T) { return T->getStmtClass() == ObjCBridgedCastExprClass; } diff --git a/include/clang/AST/ExternalASTMerger.h b/include/clang/AST/ExternalASTMerger.h index ae8a761e127e..7b01fa8cbced 100644 --- a/include/clang/AST/ExternalASTMerger.h +++ b/include/clang/AST/ExternalASTMerger.h @@ -37,7 +37,7 @@ namespace clang { /// lookup. In this case, Origins contains an entry overriding lookup and /// specifying the correct pair of DeclContext/ASTContext. /// -/// - The DeclContext of origin was determined by another ExterenalASTMerger. +/// - The DeclContext of origin was determined by another ExterenalASTMerger. /// (This is possible when the source ASTContext for one of the Importers has /// its own ExternalASTMerger). The origin must be properly forwarded in this /// case. @@ -57,7 +57,7 @@ public: typedef std::map<const DeclContext *, DCOrigin> OriginMap; typedef std::vector<std::unique_ptr<ASTImporter>> ImporterVector; private: - /// One importer exists for each source. + /// One importer exists for each source. ImporterVector Importers; /// Overrides in case name lookup would return nothing or would return /// the wrong thing. @@ -106,7 +106,7 @@ public: /// Remove a set of ASTContexts as possible origins. /// /// Sometimes an origin goes away (for example, if a source file gets - /// superseded by a newer version). + /// superseded by a newer version). /// /// The caller is responsible for ensuring that this doesn't leave /// DeclContexts that can't be completed. @@ -163,7 +163,7 @@ private: template <typename CallbackType> void ForEachMatchingDC(const DeclContext *DC, CallbackType Callback); -public: +public: /// Log something if there is a logging callback installed. llvm::raw_ostream &logs() { return *LogStream; } diff --git a/include/clang/AST/ExternalASTSource.h b/include/clang/AST/ExternalASTSource.h index 82255bb1c44c..525d4c78b362 100644 --- a/include/clang/AST/ExternalASTSource.h +++ b/include/clang/AST/ExternalASTSource.h @@ -270,10 +270,10 @@ public: /// /// The default implementation of this method is a no-op. virtual void PrintStats(); - + /// Perform layout on the given record. /// - /// This routine allows the external AST source to provide an specific + /// This routine allows the external AST source to provide an specific /// layout for a record, overriding the layout that would normally be /// constructed. It is intended for clients who receive specific layout /// details rather than source code (such as LLDB). The client is expected @@ -290,13 +290,13 @@ public: /// expressed in bits. All of the fields must be provided with offsets. /// /// \param BaseOffsets The offset of each of the direct, non-virtual base - /// classes. If any bases are not given offsets, the bases will be laid + /// classes. If any bases are not given offsets, the bases will be laid /// out according to the ABI. /// /// \param VirtualBaseOffsets The offset of each of the virtual base classes - /// (either direct or not). If any bases are not given offsets, the bases will be laid + /// (either direct or not). If any bases are not given offsets, the bases will be laid /// out according to the ABI. - /// + /// /// \returns true if the record layout was provided, false otherwise. virtual bool layoutRecordType( const RecordDecl *Record, uint64_t &Size, uint64_t &Alignment, @@ -307,15 +307,15 @@ public: //===--------------------------------------------------------------------===// // Queries for performance analysis. //===--------------------------------------------------------------------===// - + struct MemoryBufferSizes { size_t malloc_bytes; size_t mmap_bytes; - + MemoryBufferSizes(size_t malloc_bytes, size_t mmap_bytes) : malloc_bytes(malloc_bytes), mmap_bytes(mmap_bytes) {} }; - + /// Return the amount of memory used by memory buffers, breaking down /// by heap-backed versus mmap'ed memory. MemoryBufferSizes getMemoryBufferSizes() const { @@ -512,10 +512,10 @@ namespace clang { /// Represents a lazily-loaded vector of data. /// /// The lazily-loaded vector of data contains data that is partially loaded -/// from an external source and partially added by local translation. The +/// from an external source and partially added by local translation. The /// items loaded from the external source are loaded lazily, when needed for /// iteration over the complete vector. -template<typename T, typename Source, +template<typename T, typename Source, void (Source::*Loader)(SmallVectorImpl<T>&), unsigned LoadedStorage = 2, unsigned LocalStorage = 4> class LazyVector { @@ -564,20 +564,20 @@ public: iterator begin(Source *source, bool LocalOnly = false) { if (LocalOnly) return iterator(this, 0); - + if (source) (source->*Loader)(Loaded); return iterator(this, -(int)Loaded.size()); } - + iterator end() { return iterator(this, Local.size()); } - + void push_back(const T& LocalValue) { Local.push_back(LocalValue); } - + void erase(iterator From, iterator To) { if (From.isLoaded() && To.isLoaded()) { Loaded.erase(&*From, &*To); diff --git a/include/clang/AST/GlobalDecl.h b/include/clang/AST/GlobalDecl.h index 3b3e4367d56c..7f017994216f 100644 --- a/include/clang/AST/GlobalDecl.h +++ b/include/clang/AST/GlobalDecl.h @@ -57,7 +57,7 @@ public: GlobalDecl CanonGD; CanonGD.Value.setPointer(Value.getPointer()->getCanonicalDecl()); CanonGD.Value.setInt(Value.getInt()); - + return CanonGD; } @@ -72,11 +72,11 @@ public: assert(isa<CXXDestructorDecl>(getDecl()) && "Decl is not a dtor!"); return static_cast<CXXDtorType>(Value.getInt()); } - + friend bool operator==(const GlobalDecl &LHS, const GlobalDecl &RHS) { return LHS.Value == RHS.Value; } - + void *getAsOpaquePtr() const { return Value.getOpaqueValue(); } static GlobalDecl getFromOpaquePtr(void *P) { @@ -84,7 +84,7 @@ public: GD.Value.setFromOpaqueValue(P); return GD; } - + GlobalDecl getWithDecl(const Decl *D) { GlobalDecl Result(*this); Result.Value.setPointer(D); @@ -100,7 +100,7 @@ namespace llvm { static inline clang::GlobalDecl getEmptyKey() { return clang::GlobalDecl(); } - + static inline clang::GlobalDecl getTombstoneKey() { return clang::GlobalDecl:: getFromOpaquePtr(reinterpret_cast<void*>(-1)); @@ -109,13 +109,13 @@ namespace llvm { static unsigned getHashValue(clang::GlobalDecl GD) { return DenseMapInfo<void*>::getHashValue(GD.getAsOpaquePtr()); } - - static bool isEqual(clang::GlobalDecl LHS, + + static bool isEqual(clang::GlobalDecl LHS, clang::GlobalDecl RHS) { return LHS == RHS; } }; - + // GlobalDecl isn't *technically* a POD type. However, its copy constructor, // copy assignment operator, and destructor are all trivial. template <> diff --git a/include/clang/AST/LambdaCapture.h b/include/clang/AST/LambdaCapture.h index bcc5352c1c9d..f246bc423bfb 100644 --- a/include/clang/AST/LambdaCapture.h +++ b/include/clang/AST/LambdaCapture.h @@ -41,7 +41,7 @@ class LambdaCapture { }; // Decl could represent: - // - a VarDecl* that represents the variable that was captured or the + // - a VarDecl* that represents the variable that was captured or the // init-capture. // - or, is a nullptr and Capture_This is set in Bits if this represents a // capture of '*this' by value or reference. diff --git a/include/clang/AST/Mangle.h b/include/clang/AST/Mangle.h index 401574b265b0..c42fe91b3246 100644 --- a/include/clang/AST/Mangle.h +++ b/include/clang/AST/Mangle.h @@ -73,7 +73,7 @@ public: DiagnosticsEngine &getDiags() const { return Diags; } virtual void startNewFunction() { LocalBlockIds.clear(); } - + unsigned getBlockId(const BlockDecl *BD, bool Local) { llvm::DenseMap<const BlockDecl *, unsigned> &BlockIds = Local? LocalBlockIds : GlobalBlockIds; diff --git a/include/clang/AST/NSAPI.h b/include/clang/AST/NSAPI.h index ee07745b1242..bf2afe38cbca 100644 --- a/include/clang/AST/NSAPI.h +++ b/include/clang/AST/NSAPI.h @@ -113,7 +113,7 @@ public: NSMutableDict_setValueForKey }; static const unsigned NumNSDictionaryMethods = 13; - + /// The Objective-C NSDictionary selectors. Selector getNSDictionarySelector(NSDictionaryMethodKind MK) const; diff --git a/include/clang/AST/NestedNameSpecifier.h b/include/clang/AST/NestedNameSpecifier.h index 2255d5114350..3a7b45767dac 100644 --- a/include/clang/AST/NestedNameSpecifier.h +++ b/include/clang/AST/NestedNameSpecifier.h @@ -44,7 +44,7 @@ class TypeLoc; /// specifier. Nested name specifiers are made up of a sequence of /// specifiers, each of which can be a namespace, type, identifier /// (for dependent names), decltype specifier, or the global specifier ('::'). -/// The last two specifiers can only appear at the start of a +/// The last two specifiers can only appear at the start of a /// nested-namespace-specifier. class NestedNameSpecifier : public llvm::FoldingSetNode { /// Enumeration describing @@ -438,7 +438,7 @@ public: /// Turn this (empty) nested-name-specifier into the global /// nested-name-specifier '::'. void MakeGlobal(ASTContext &Context, SourceLocation ColonColonLoc); - + /// Turns this (empty) nested-name-specifier into '__super' /// nested-name-specifier. /// @@ -452,7 +452,7 @@ public: /// name. /// /// \param ColonColonLoc The location of the trailing '::'. - void MakeSuper(ASTContext &Context, CXXRecordDecl *RD, + void MakeSuper(ASTContext &Context, CXXRecordDecl *RD, SourceLocation SuperLoc, SourceLocation ColonColonLoc); /// Make a new nested-name-specifier from incomplete source-location diff --git a/include/clang/AST/OperationKinds.def b/include/clang/AST/OperationKinds.def index 823e32424f1e..e2d65d84880c 100644 --- a/include/clang/AST/OperationKinds.def +++ b/include/clang/AST/OperationKinds.def @@ -307,7 +307,7 @@ CAST_OPERATION(AtomicToNonAtomic) /// Converts from T to _Atomic(T). CAST_OPERATION(NonAtomicToAtomic) -/// Causes a block literal to by copied to the heap and then +/// Causes a block literal to by copied to the heap and then /// autoreleased. /// /// This particular cast kind is used for the conversion from a C++11 @@ -391,13 +391,13 @@ BINARY_OPERATION(Comma, ",") // [C99 6.5.2.4] Postfix increment and decrement UNARY_OPERATION(PostInc, "++") UNARY_OPERATION(PostDec, "--") -// [C99 6.5.3.1] Prefix increment and decrement +// [C99 6.5.3.1] Prefix increment and decrement UNARY_OPERATION(PreInc, "++") UNARY_OPERATION(PreDec, "--") // [C99 6.5.3.2] Address and indirection UNARY_OPERATION(AddrOf, "&") UNARY_OPERATION(Deref, "*") -// [C99 6.5.3.3] Unary arithmetic +// [C99 6.5.3.3] Unary arithmetic UNARY_OPERATION(Plus, "+") UNARY_OPERATION(Minus, "-") UNARY_OPERATION(Not, "~") diff --git a/include/clang/AST/OperationKinds.h b/include/clang/AST/OperationKinds.h index c7e01fa1834e..ac512d721e34 100644 --- a/include/clang/AST/OperationKinds.h +++ b/include/clang/AST/OperationKinds.h @@ -16,7 +16,7 @@ #define LLVM_CLANG_AST_OPERATIONKINDS_H namespace clang { - + /// CastKind - The kind of operation required for a conversion. enum CastKind { #define CAST_OPERATION(Name) CK_##Name, diff --git a/include/clang/AST/PrettyPrinter.h b/include/clang/AST/PrettyPrinter.h index 41c804486c35..b49f5be1b1e6 100644 --- a/include/clang/AST/PrettyPrinter.h +++ b/include/clang/AST/PrettyPrinter.h @@ -109,7 +109,7 @@ struct PrintingPolicy { /// Suppress printing parts of scope specifiers that don't need /// to be written, e.g., for inline or anonymous namespaces. bool SuppressUnwrittenScope : 1; - + /// Suppress printing of variable initializers. /// /// This flag is used when printing the loop variable in a for-range @@ -140,15 +140,15 @@ struct PrintingPolicy { /// char a[9] = "A string"; /// \endcode bool ConstantArraySizeAsWritten : 1; - + /// When printing an anonymous tag name, also print the location of that /// entity (e.g., "enum <anonymous at t.h:10:5>"). Otherwise, just prints /// "(anonymous)" for the name. bool AnonymousTagLocations : 1; - + /// When true, suppress printing of the __strong lifetime qualifier in ARC. unsigned SuppressStrongLifetime : 1; - + /// When true, suppress printing of lifetime qualifier in ARC. unsigned SuppressLifetimeQualifiers : 1; @@ -179,7 +179,7 @@ struct PrintingPolicy { /// declarations inside namespaces etc. Effectively, this should print /// only the requested declaration. unsigned TerseOutput : 1; - + /// When true, do certain refinement needed for producing proper declaration /// tag; such as, do not print attributes attached to the declaration. /// diff --git a/include/clang/AST/RecordLayout.h b/include/clang/AST/RecordLayout.h index dc60ef892b07..a546c200ffe0 100644 --- a/include/clang/AST/RecordLayout.h +++ b/include/clang/AST/RecordLayout.h @@ -71,6 +71,10 @@ private: // Alignment - Alignment of record in characters. CharUnits Alignment; + // UnadjustedAlignment - Maximum of the alignments of the record members in + // characters. + CharUnits UnadjustedAlignment; + /// RequiredAlignment - The required alignment of the object. In the MS-ABI /// the __declspec(align()) trumps #pramga pack and must always be obeyed. CharUnits RequiredAlignment; @@ -120,10 +124,10 @@ private: /// BaseSharingVBPtr - The base we share vbptr with. const CXXRecordDecl *BaseSharingVBPtr; - + /// FIXME: This should really use a SmallPtrMap, once we have one in LLVM :) using BaseOffsetsMapTy = llvm::DenseMap<const CXXRecordDecl *, CharUnits>; - + /// BaseOffsets - Contains a map from base classes to their offset. BaseOffsetsMapTy BaseOffsets; @@ -136,6 +140,7 @@ private: CXXRecordLayoutInfo *CXXInfo = nullptr; ASTRecordLayout(const ASTContext &Ctx, CharUnits size, CharUnits alignment, + CharUnits unadjustedAlignment, CharUnits requiredAlignment, CharUnits datasize, ArrayRef<uint64_t> fieldoffsets); @@ -144,6 +149,7 @@ private: // Constructor for C++ records. ASTRecordLayout(const ASTContext &Ctx, CharUnits size, CharUnits alignment, + CharUnits unadjustedAlignment, CharUnits requiredAlignment, bool hasOwnVFPtr, bool hasExtendableVFPtr, CharUnits vbptroffset, @@ -162,7 +168,7 @@ private: ~ASTRecordLayout() = default; void Destroy(ASTContext &Ctx); - + public: ASTRecordLayout(const ASTRecordLayout &) = delete; ASTRecordLayout &operator=(const ASTRecordLayout &) = delete; @@ -170,6 +176,10 @@ public: /// getAlignment - Get the record alignment in characters. CharUnits getAlignment() const { return Alignment; } + /// getUnadjustedAlignment - Get the record alignment in characters, before + /// alignment adjustement. + CharUnits getUnadjustedAlignment() const { return UnadjustedAlignment; } + /// getSize - Get the record size in characters. CharUnits getSize() const { return Size; } @@ -259,7 +269,7 @@ public: assert(CXXInfo && "Record layout does not have C++ specific info!"); return CXXInfo->HasExtendableVFPtr; } - + /// hasOwnVBPtr - Does this class provide its own virtual-base /// table pointer, rather than inheriting one from a primary base /// class? diff --git a/include/clang/AST/Stmt.h b/include/clang/AST/Stmt.h index 91dbcb71a600..aa0f88b71023 100644 --- a/include/clang/AST/Stmt.h +++ b/include/clang/AST/Stmt.h @@ -204,7 +204,7 @@ protected: unsigned Kind : 6; unsigned PartOfExplicitCast : 1; // Only set for ImplicitCastExpr. - unsigned BasePathSize : 32 - 6 - 1 - NumExprBits; + unsigned BasePathIsEmpty : 1; }; class CallExprBitfields { @@ -271,12 +271,12 @@ protected: friend class ASTStmtReader; friend class ASTStmtWriter; friend class TypeTraitExpr; - + unsigned : NumExprBits; - + /// The kind of type trait, which is a value of a TypeTrait enumerator. unsigned Kind : 8; - + /// If this expression is not value-dependent, this indicates whether /// the trait evaluated true or false. unsigned Value : 1; @@ -1556,7 +1556,7 @@ public: /// getInputConstraint - Return the specified input constraint. Unlike output /// constraints, these can be empty. StringRef getInputConstraint(unsigned i) const; - + const Expr *getInputExpr(unsigned i) const; //===--- Other ---===// @@ -2133,7 +2133,7 @@ private: /// The number of variable captured, including 'this'. unsigned NumCaptures; - /// The pointer part is the implicit the outlined function and the + /// The pointer part is the implicit the outlined function and the /// int part is the captured region kind, 'CR_Default' etc. llvm::PointerIntPair<CapturedDecl *, 2, CapturedRegionKind> CapDeclAndKind; diff --git a/include/clang/AST/StmtIterator.h b/include/clang/AST/StmtIterator.h index 33aab08bbb71..806edaa38821 100644 --- a/include/clang/AST/StmtIterator.h +++ b/include/clang/AST/StmtIterator.h @@ -33,14 +33,14 @@ protected: DeclGroupMode = 0x2, Flags = 0x3 }; - + union { Stmt **stmt; Decl **DGI; }; uintptr_t RawVAPtr = 0; Decl **DGE; - + StmtIteratorBase(Stmt **s) : stmt(s) {} StmtIteratorBase(const VariableArrayType *t); StmtIteratorBase(Decl **dgi, Decl **dge); diff --git a/include/clang/AST/StmtObjC.h b/include/clang/AST/StmtObjC.h index 571ad76be8a9..0b2cc78b65be 100644 --- a/include/clang/AST/StmtObjC.h +++ b/include/clang/AST/StmtObjC.h @@ -81,7 +81,7 @@ public: ObjCAtCatchStmt(SourceLocation atCatchLoc, SourceLocation rparenloc, VarDecl *catchVarDecl, Stmt *atCatchStmt) - : Stmt(ObjCAtCatchStmtClass), ExceptionDecl(catchVarDecl), + : Stmt(ObjCAtCatchStmtClass), ExceptionDecl(catchVarDecl), Body(atCatchStmt), AtCatchLoc(atCatchLoc), RParenLoc(rparenloc) { } explicit ObjCAtCatchStmt(EmptyShell Empty) : @@ -155,27 +155,27 @@ class ObjCAtTryStmt : public Stmt { private: // The location of the @ in the \@try. SourceLocation AtTryLoc; - + // The number of catch blocks in this statement. unsigned NumCatchStmts : 16; - + // Whether this statement has a \@finally statement. bool HasFinally : 1; - + /// Retrieve the statements that are stored after this \@try statement. /// /// The order of the statements in memory follows the order in the source, /// with the \@try body first, followed by the \@catch statements (if any) /// and, finally, the \@finally (if it exists). Stmt **getStmts() { return reinterpret_cast<Stmt **> (this + 1); } - const Stmt* const *getStmts() const { - return reinterpret_cast<const Stmt * const*> (this + 1); + const Stmt* const *getStmts() const { + return reinterpret_cast<const Stmt * const*> (this + 1); } - + ObjCAtTryStmt(SourceLocation atTryLoc, Stmt *atTryStmt, Stmt **CatchStmts, unsigned NumCatchStmts, Stmt *atFinallyStmt); - + explicit ObjCAtTryStmt(EmptyShell Empty, unsigned NumCatchStmts, bool HasFinally) : Stmt(ObjCAtTryStmtClass, Empty), NumCatchStmts(NumCatchStmts), @@ -188,7 +188,7 @@ public: Stmt *atFinallyStmt); static ObjCAtTryStmt *CreateEmpty(const ASTContext &Context, unsigned NumCatchStmts, bool HasFinally); - + /// Retrieve the location of the @ in the \@try. SourceLocation getAtTryLoc() const { return AtTryLoc; } void setAtTryLoc(SourceLocation Loc) { AtTryLoc = Loc; } @@ -201,41 +201,41 @@ public: /// Retrieve the number of \@catch statements in this try-catch-finally /// block. unsigned getNumCatchStmts() const { return NumCatchStmts; } - + /// Retrieve a \@catch statement. const ObjCAtCatchStmt *getCatchStmt(unsigned I) const { assert(I < NumCatchStmts && "Out-of-bounds @catch index"); return cast_or_null<ObjCAtCatchStmt>(getStmts()[I + 1]); } - + /// Retrieve a \@catch statement. ObjCAtCatchStmt *getCatchStmt(unsigned I) { assert(I < NumCatchStmts && "Out-of-bounds @catch index"); return cast_or_null<ObjCAtCatchStmt>(getStmts()[I + 1]); } - + /// Set a particular catch statement. void setCatchStmt(unsigned I, ObjCAtCatchStmt *S) { assert(I < NumCatchStmts && "Out-of-bounds @catch index"); getStmts()[I + 1] = S; } - + /// Retrieve the \@finally statement, if any. const ObjCAtFinallyStmt *getFinallyStmt() const { if (!HasFinally) return nullptr; - + return cast_or_null<ObjCAtFinallyStmt>(getStmts()[1 + NumCatchStmts]); } ObjCAtFinallyStmt *getFinallyStmt() { if (!HasFinally) return nullptr; - + return cast_or_null<ObjCAtFinallyStmt>(getStmts()[1 + NumCatchStmts]); } - void setFinallyStmt(Stmt *S) { + void setFinallyStmt(Stmt *S) { assert(HasFinally && "@try does not have a @finally slot!"); - getStmts()[1 + NumCatchStmts] = S; + getStmts()[1 + NumCatchStmts] = S; } SourceLocation getLocStart() const LLVM_READONLY { return AtTryLoc; } diff --git a/include/clang/AST/StmtOpenMP.h b/include/clang/AST/StmtOpenMP.h index 84a35db938b0..d23375e7606b 100644 --- a/include/clang/AST/StmtOpenMP.h +++ b/include/clang/AST/StmtOpenMP.h @@ -2319,7 +2319,7 @@ class OMPTargetDataDirective : public OMPExecutableDirective { /// OMPTargetDataDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) - : OMPExecutableDirective(this, OMPTargetDataDirectiveClass, + : OMPExecutableDirective(this, OMPTargetDataDirectiveClass, OMPD_target_data, StartLoc, EndLoc, NumClauses, 1) {} @@ -2328,7 +2328,7 @@ class OMPTargetDataDirective : public OMPExecutableDirective { /// \param NumClauses Number of clauses. /// explicit OMPTargetDataDirective(unsigned NumClauses) - : OMPExecutableDirective(this, OMPTargetDataDirectiveClass, + : OMPExecutableDirective(this, OMPTargetDataDirectiveClass, OMPD_target_data, SourceLocation(), SourceLocation(), NumClauses, 1) {} @@ -3157,7 +3157,7 @@ class OMPDistributeParallelForSimdDirective final : public OMPLoopDirective { unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPDistributeParallelForSimdDirectiveClass, - OMPD_distribute_parallel_for_simd, StartLoc, + OMPD_distribute_parallel_for_simd, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// Build an empty directive. @@ -3168,7 +3168,7 @@ class OMPDistributeParallelForSimdDirective final : public OMPLoopDirective { explicit OMPDistributeParallelForSimdDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPDistributeParallelForSimdDirectiveClass, - OMPD_distribute_parallel_for_simd, + OMPD_distribute_parallel_for_simd, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} @@ -3232,7 +3232,7 @@ class OMPDistributeSimdDirective final : public OMPLoopDirective { /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// - explicit OMPDistributeSimdDirective(unsigned CollapsedNum, + explicit OMPDistributeSimdDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPDistributeSimdDirectiveClass, OMPD_distribute_simd, SourceLocation(), @@ -3369,7 +3369,7 @@ class OMPTargetSimdDirective final : public OMPLoopDirective { /// \param NumClauses Number of clauses. /// explicit OMPTargetSimdDirective(unsigned CollapsedNum, unsigned NumClauses) - : OMPLoopDirective(this, OMPTargetSimdDirectiveClass, OMPD_target_simd, + : OMPLoopDirective(this, OMPTargetSimdDirectiveClass, OMPD_target_simd, SourceLocation(),SourceLocation(), CollapsedNum, NumClauses) {} @@ -3425,8 +3425,8 @@ class OMPTeamsDistributeDirective final : public OMPLoopDirective { /// OMPTeamsDistributeDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) - : OMPLoopDirective(this, OMPTeamsDistributeDirectiveClass, - OMPD_teams_distribute, StartLoc, EndLoc, + : OMPLoopDirective(this, OMPTeamsDistributeDirectiveClass, + OMPD_teams_distribute, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// Build an empty directive. @@ -3567,7 +3567,7 @@ class OMPTeamsDistributeParallelForSimdDirective final unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTeamsDistributeParallelForSimdDirectiveClass, - OMPD_teams_distribute_parallel_for_simd, StartLoc, + OMPD_teams_distribute_parallel_for_simd, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// Build an empty directive. @@ -3578,7 +3578,7 @@ class OMPTeamsDistributeParallelForSimdDirective final explicit OMPTeamsDistributeParallelForSimdDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTeamsDistributeParallelForSimdDirectiveClass, - OMPD_teams_distribute_parallel_for_simd, + OMPD_teams_distribute_parallel_for_simd, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} diff --git a/include/clang/AST/TemplateBase.h b/include/clang/AST/TemplateBase.h index a1920253de78..6898ef4e1b8a 100644 --- a/include/clang/AST/TemplateBase.h +++ b/include/clang/AST/TemplateBase.h @@ -252,7 +252,7 @@ public: /// Determine whether this template argument is a pack expansion. bool isPackExpansion() const; - + /// Retrieve the type for a type template argument. QualType getAsType() const { assert(getKind() == Type && "Unexpected kind"); @@ -288,14 +288,14 @@ public: TemplateName getAsTemplateOrTemplatePattern() const { assert((getKind() == Template || getKind() == TemplateExpansion) && "Unexpected kind"); - + return TemplateName::getFromVoidPointer(TemplateArg.Name); } /// Retrieve the number of expansions that a template template argument /// expansion will produce, if known. Optional<unsigned> getNumTemplateExpansions() const; - + /// Retrieve the template argument as an integral value. // FIXME: Provide a way to read the integral data without copying the value. llvm::APSInt getAsIntegral() const { @@ -378,13 +378,13 @@ public: /// Print this template argument to the given output stream. void print(const PrintingPolicy &Policy, raw_ostream &Out) const; - + /// Debugging aid that dumps the template argument. void dump(raw_ostream &Out) const; /// Debugging aid that dumps the template argument to standard error. void dump() const; - + /// Used to insert TemplateArguments into FoldingSets. void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) const; }; @@ -411,9 +411,9 @@ public: constexpr TemplateArgumentLocInfo() : Template({nullptr, nullptr, 0, 0}) {} TemplateArgumentLocInfo(TypeSourceInfo *TInfo) : Declarator(TInfo) {} - + TemplateArgumentLocInfo(Expr *E) : Expression(E) {} - + TemplateArgumentLocInfo(NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateNameLoc, SourceLocation EllipsisLoc) { @@ -432,14 +432,14 @@ public: } NestedNameSpecifierLoc getTemplateQualifierLoc() const { - return NestedNameSpecifierLoc(Template.Qualifier, + return NestedNameSpecifierLoc(Template.Qualifier, Template.QualifierLocData); } - + SourceLocation getTemplateNameLoc() const { return SourceLocation::getFromRawEncoding(Template.TemplateNameLoc); } - + SourceLocation getTemplateEllipsisLoc() const { return SourceLocation::getFromRawEncoding(Template.EllipsisLoc); } @@ -465,10 +465,16 @@ public: TemplateArgumentLoc(const TemplateArgument &Argument, Expr *E) : Argument(Argument), LocInfo(E) { - assert(Argument.getKind() == TemplateArgument::Expression); + + // Permit any kind of template argument that can be represented with an + // expression + assert(Argument.getKind() == TemplateArgument::NullPtr || + Argument.getKind() == TemplateArgument::Integral || + Argument.getKind() == TemplateArgument::Declaration || + Argument.getKind() == TemplateArgument::Expression); } - TemplateArgumentLoc(const TemplateArgument &Argument, + TemplateArgumentLoc(const TemplateArgument &Argument, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateNameLoc, SourceLocation EllipsisLoc = SourceLocation()) @@ -477,13 +483,13 @@ public: assert(Argument.getKind() == TemplateArgument::Template || Argument.getKind() == TemplateArgument::TemplateExpansion); } - + /// - Fetches the primary location of the argument. SourceLocation getLocation() const { if (Argument.getKind() == TemplateArgument::Template || Argument.getKind() == TemplateArgument::TemplateExpansion) return getTemplateNameLoc(); - + return getSourceRange().getBegin(); } @@ -528,13 +534,13 @@ public: Argument.getKind() == TemplateArgument::TemplateExpansion); return LocInfo.getTemplateQualifierLoc(); } - + SourceLocation getTemplateNameLoc() const { assert(Argument.getKind() == TemplateArgument::Template || Argument.getKind() == TemplateArgument::TemplateExpansion); return LocInfo.getTemplateNameLoc(); - } - + } + SourceLocation getTemplateEllipsisLoc() const { assert(Argument.getKind() == TemplateArgument::TemplateExpansion); return LocInfo.getTemplateEllipsisLoc(); @@ -689,7 +695,7 @@ inline const TemplateArgument & assert(Idx < getNumArgs() && "Template argument out of range"); return getArgs()[Idx]; } - + } // namespace clang #endif // LLVM_CLANG_AST_TEMPLATEBASE_H diff --git a/include/clang/AST/TemplateName.h b/include/clang/AST/TemplateName.h index 50549e1a0a6a..d88d58d0a2aa 100644 --- a/include/clang/AST/TemplateName.h +++ b/include/clang/AST/TemplateName.h @@ -22,7 +22,7 @@ #include <cassert> namespace clang { - + class ASTContext; class DependentTemplateName; class DiagnosticBuilder; @@ -38,7 +38,7 @@ class SubstTemplateTemplateParmStorage; class TemplateArgument; class TemplateDecl; class TemplateTemplateParmDecl; - + /// Implementation class used to describe either a set of overloaded /// template names or an already-substituted template template parameter pack. class UncommonTemplateNameStorage { @@ -52,7 +52,7 @@ protected: struct BitsTag { /// A Kind. unsigned Kind : 2; - + /// The number of stored templates or template arguments, /// depending on which subclass we have. unsigned Size : 30; @@ -62,21 +62,21 @@ protected: struct BitsTag Bits; void *PointerAlignment; }; - + UncommonTemplateNameStorage(Kind kind, unsigned size) { Bits.Kind = kind; Bits.Size = size; } - + public: unsigned size() const { return Bits.Size; } - + OverloadedTemplateStorage *getAsOverloadedStorage() { return Bits.Kind == Overloaded - ? reinterpret_cast<OverloadedTemplateStorage *>(this) + ? reinterpret_cast<OverloadedTemplateStorage *>(this) : nullptr; } - + SubstTemplateTemplateParmStorage *getAsSubstTemplateTemplateParm() { return Bits.Kind == SubstTemplateTemplateParm ? reinterpret_cast<SubstTemplateTemplateParmStorage *>(this) @@ -89,13 +89,13 @@ public: : nullptr; } }; - + /// A structure for storing the information associated with an /// overloaded template name. class OverloadedTemplateStorage : public UncommonTemplateNameStorage { friend class ASTContext; - OverloadedTemplateStorage(unsigned size) + OverloadedTemplateStorage(unsigned size) : UncommonTemplateNameStorage(Overloaded, size) {} NamedDecl **getStorage() { @@ -115,7 +115,7 @@ public: /// A structure for storing an already-substituted template template /// parameter pack. /// -/// This kind of template names occurs when the parameter pack has been +/// This kind of template names occurs when the parameter pack has been /// provided with a template template argument pack in a context where its /// enclosing pack expansion could not be fully expanded. class SubstTemplateTemplateParmPackStorage @@ -123,25 +123,25 @@ class SubstTemplateTemplateParmPackStorage { TemplateTemplateParmDecl *Parameter; const TemplateArgument *Arguments; - + public: SubstTemplateTemplateParmPackStorage(TemplateTemplateParmDecl *Parameter, - unsigned Size, + unsigned Size, const TemplateArgument *Arguments) : UncommonTemplateNameStorage(SubstTemplateTemplateParmPack, Size), Parameter(Parameter), Arguments(Arguments) {} - + /// Retrieve the template template parameter pack being substituted. TemplateTemplateParmDecl *getParameterPack() const { return Parameter; } - + /// Retrieve the template template argument pack with which this /// parameter was substituted. TemplateArgument getArgumentPack() const; - + void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context); - + static void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context, TemplateTemplateParmDecl *Parameter, @@ -193,11 +193,11 @@ public: /// A set of overloaded template declarations. OverloadedTemplate, - /// A qualified template name, where the qualification is kept + /// A qualified template name, where the qualification is kept /// to describe the source code as written. QualifiedTemplate, - /// A dependent template name that has not been resolved to a + /// A dependent template name that has not been resolved to a /// template (or set of templates). DependentTemplate, @@ -205,7 +205,7 @@ public: /// for some other template name. SubstTemplateTemplateParm, - /// A template template parameter pack that has been substituted for + /// A template template parameter pack that has been substituted for /// a template template argument pack, but has not yet been expanded into /// individual arguments. SubstTemplateTemplateParmPack @@ -221,7 +221,7 @@ public: /// Determine whether this template name is NULL. bool isNull() const; - + // Get the kind of name that is actually stored. NameKind getKind() const; @@ -243,14 +243,14 @@ public: /// refers to a single template, returns NULL. OverloadedTemplateStorage *getAsOverloadedTemplate() const; - /// Retrieve the substituted template template parameter, if + /// Retrieve the substituted template template parameter, if /// known. /// /// \returns The storage for the substituted template template parameter, /// if known. Otherwise, returns NULL. SubstTemplateTemplateParmStorage *getAsSubstTemplateTemplateParm() const; - /// Retrieve the substituted template template parameter pack, if + /// Retrieve the substituted template template parameter pack, if /// known. /// /// \returns The storage for the substituted template template parameter pack, @@ -339,7 +339,7 @@ public: TemplateName getReplacement() const { return Replacement; } void Profile(llvm::FoldingSetNodeID &ID); - + static void Profile(llvm::FoldingSetNodeID &ID, TemplateTemplateParmDecl *parameter, TemplateName replacement); @@ -436,7 +436,7 @@ class DependentTemplateName : public llvm::FoldingSetNode { /// /// Only valid when the bit on \c Qualifier is clear. const IdentifierInfo *Identifier; - + /// The overloaded operator name. /// /// Only valid when the bit on \c Qualifier is set. @@ -453,26 +453,26 @@ class DependentTemplateName : public llvm::FoldingSetNode { DependentTemplateName(NestedNameSpecifier *Qualifier, const IdentifierInfo *Identifier) - : Qualifier(Qualifier, false), Identifier(Identifier), + : Qualifier(Qualifier, false), Identifier(Identifier), CanonicalTemplateName(this) {} DependentTemplateName(NestedNameSpecifier *Qualifier, const IdentifierInfo *Identifier, TemplateName Canon) - : Qualifier(Qualifier, false), Identifier(Identifier), + : Qualifier(Qualifier, false), Identifier(Identifier), CanonicalTemplateName(Canon) {} DependentTemplateName(NestedNameSpecifier *Qualifier, OverloadedOperatorKind Operator) - : Qualifier(Qualifier, true), Operator(Operator), + : Qualifier(Qualifier, true), Operator(Operator), CanonicalTemplateName(this) {} - + DependentTemplateName(NestedNameSpecifier *Qualifier, OverloadedOperatorKind Operator, TemplateName Canon) - : Qualifier(Qualifier, true), Operator(Operator), + : Qualifier(Qualifier, true), Operator(Operator), CanonicalTemplateName(Canon) {} - + public: /// Return the nested name specifier that qualifies this name. NestedNameSpecifier *getQualifier() const { return Qualifier.getPointer(); } @@ -481,22 +481,22 @@ public: bool isIdentifier() const { return !Qualifier.getInt(); } /// Returns the identifier to which this template name refers. - const IdentifierInfo *getIdentifier() const { + const IdentifierInfo *getIdentifier() const { assert(isIdentifier() && "Template name isn't an identifier?"); return Identifier; } - + /// Determine whether this template name refers to an overloaded /// operator. bool isOverloadedOperator() const { return Qualifier.getInt(); } - + /// Return the overloaded operator to which this template name refers. - OverloadedOperatorKind getOperator() const { + OverloadedOperatorKind getOperator() const { assert(isOverloadedOperator() && "Template name isn't an overloaded operator?"); - return Operator; + return Operator; } - + void Profile(llvm::FoldingSetNodeID &ID) { if (isIdentifier()) Profile(ID, getQualifier(), getIdentifier()); diff --git a/include/clang/AST/Type.h b/include/clang/AST/Type.h index c692707847a6..9a8dd6faff31 100644 --- a/include/clang/AST/Type.h +++ b/include/clang/AST/Type.h @@ -992,7 +992,7 @@ public: static std::string getAsString(const Type *ty, Qualifiers qs, const PrintingPolicy &Policy); - std::string getAsString() const; + std::string getAsString() const; std::string getAsString(const PrintingPolicy &Policy) const; void print(raw_ostream &OS, const PrintingPolicy &Policy, @@ -2017,6 +2017,9 @@ public: /// type of a class template or class template partial specialization. CXXRecordDecl *getAsCXXRecordDecl() const; + /// Retrieves the RecordDecl this type refers to. + RecordDecl *getAsRecordDecl() const; + /// Retrieves the TagDecl that this type refers to, either /// because the type is a TagType or because it is the injected-class-name /// type of a class template or class template partial specialization. @@ -2926,7 +2929,7 @@ public: }; /// Represents an extended address space qualifier where the input address space -/// value is dependent. Non-dependent address spaces are not represented with a +/// value is dependent. Non-dependent address spaces are not represented with a /// special Type subclass; they are stored on an ExtQuals node as part of a QualType. /// /// For example: @@ -2945,7 +2948,7 @@ class DependentAddressSpaceType : public Type, public llvm::FoldingSetNode { SourceLocation loc; DependentAddressSpaceType(const ASTContext &Context, QualType PointeeType, - QualType can, Expr *AddrSpaceExpr, + QualType can, Expr *AddrSpaceExpr, SourceLocation loc); public: @@ -3264,7 +3267,7 @@ public: Bits = ((unsigned)cc) | (noReturn ? NoReturnMask : 0) | (producesResult ? ProducesResultMask : 0) | (noCallerSavedRegs ? NoCallerSavedRegsMask : 0) | - (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0) | + (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0) | (NoCfCheck ? NoCfCheckMask : 0); } @@ -4234,6 +4237,7 @@ public: attr_null_unspecified, attr_objc_kindof, attr_objc_inert_unsafe_unretained, + attr_lifetimebound, }; private: @@ -5336,7 +5340,7 @@ public: /// with base C and no protocols. /// /// 'C<P>' is an unspecialized ObjCObjectType with base C and protocol list [P]. -/// 'C<C*>' is a specialized ObjCObjectType with type arguments 'C*' and no +/// 'C<C*>' is a specialized ObjCObjectType with type arguments 'C*' and no /// protocol list. /// 'C<C*><P>' is a specialized ObjCObjectType with base C, type arguments 'C*', /// and protocol list [P]. @@ -5968,7 +5972,7 @@ inline QualType QualType::getUnqualifiedType() const { return QualType(getSplitUnqualifiedTypeImpl(*this).Ty, 0); } - + inline SplitQualType QualType::getSplitUnqualifiedType() const { if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers()) return split(); @@ -6443,7 +6447,7 @@ inline bool Type::isIntegralOrEnumerationType() const { if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) return IsEnumDeclComplete(ET->getDecl()); - return false; + return false; } inline bool Type::isBooleanType() const { diff --git a/include/clang/AST/TypeLoc.h b/include/clang/AST/TypeLoc.h index 25cd014efe5f..c69f4aa4abcf 100644 --- a/include/clang/AST/TypeLoc.h +++ b/include/clang/AST/TypeLoc.h @@ -992,7 +992,7 @@ class ObjCObjectTypeLoc : public ConcreteTypeLoc<UnqualTypeLoc, return (TypeSourceInfo**)this->getExtraLocalData(); } - // SourceLocations are stored after the type argument information, one for + // SourceLocations are stored after the type argument information, one for // each Protocol. SourceLocation *getProtocolLocArray() const { return (SourceLocation*)(getTypeArgLocArray() + getNumTypeArgs()); @@ -1131,11 +1131,11 @@ public: void setNameLoc(SourceLocation Loc) { getLocalData()->NameLoc = Loc; } - + SourceRange getLocalSourceRange() const { return SourceRange(getNameLoc(), getNameEndLoc()); } - + SourceLocation getNameEndLoc() const { return getLocalData()->NameEndLoc; } @@ -1766,10 +1766,10 @@ public: return range; } - /// Returns the type before the address space attribute application - /// area. + /// Returns the type before the address space attribute application + /// area. /// int * __attribute__((address_space(11))) * - /// ^ ^ + /// ^ ^ QualType getInnerType() const { return this->getTypePtr()->getPointeeType(); } diff --git a/include/clang/AST/TypeOrdering.h b/include/clang/AST/TypeOrdering.h index d29dd6d60124..7ea78071f5cf 100644 --- a/include/clang/AST/TypeOrdering.h +++ b/include/clang/AST/TypeOrdering.h @@ -56,20 +56,20 @@ namespace llvm { }; template<> struct DenseMapInfo<clang::CanQualType> { - static inline clang::CanQualType getEmptyKey() { - return clang::CanQualType(); + static inline clang::CanQualType getEmptyKey() { + return clang::CanQualType(); } - + static inline clang::CanQualType getTombstoneKey() { using clang::CanQualType; return CanQualType::getFromOpaquePtr(reinterpret_cast<clang::Type *>(-1)); } - + static unsigned getHashValue(clang::CanQualType Val) { return (unsigned)((uintptr_t)Val.getAsOpaquePtr()) ^ ((unsigned)((uintptr_t)Val.getAsOpaquePtr() >> 9)); } - + static bool isEqual(clang::CanQualType LHS, clang::CanQualType RHS) { return LHS == RHS; } diff --git a/include/clang/AST/UnresolvedSet.h b/include/clang/AST/UnresolvedSet.h index d6b01cb57334..b62e9f138bb6 100644 --- a/include/clang/AST/UnresolvedSet.h +++ b/include/clang/AST/UnresolvedSet.h @@ -146,7 +146,7 @@ template <unsigned InlineCapacity> class UnresolvedSet : SmallVector<DeclAccessPair, InlineCapacity> Decls; }; - + } // namespace clang #endif // LLVM_CLANG_AST_UNRESOLVEDSET_H diff --git a/include/clang/AST/VTTBuilder.h b/include/clang/AST/VTTBuilder.h index 84661c8cc7f2..3a8a6a9c15f0 100644 --- a/include/clang/AST/VTTBuilder.h +++ b/include/clang/AST/VTTBuilder.h @@ -76,15 +76,15 @@ class VTTBuilder { const CXXRecordDecl *MostDerivedClass; using VTTVTablesVectorTy = SmallVector<VTTVTable, 64>; - + /// The VTT vtables. VTTVTablesVectorTy VTTVTables; - + using VTTComponentsVectorTy = SmallVector<VTTComponent, 64>; - + /// The VTT components. VTTComponentsVectorTy VTTComponents; - + /// The AST record layout of the most derived class. const ASTRecordLayout &MostDerivedClassLayout; @@ -105,35 +105,35 @@ class VTTBuilder { /// Add a vtable pointer to the VTT currently being built. void AddVTablePointer(BaseSubobject Base, uint64_t VTableIndex, const CXXRecordDecl *VTableClass); - + /// Lay out the secondary VTTs of the given base subobject. void LayoutSecondaryVTTs(BaseSubobject Base); - + /// Lay out the secondary virtual pointers for the given base /// subobject. /// /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base /// or a direct or indirect base of a virtual base. - void LayoutSecondaryVirtualPointers(BaseSubobject Base, + void LayoutSecondaryVirtualPointers(BaseSubobject Base, bool BaseIsMorallyVirtual, uint64_t VTableIndex, const CXXRecordDecl *VTableClass, VisitedVirtualBasesSetTy &VBases); - + /// Lay out the secondary virtual pointers for the given base /// subobject. - void LayoutSecondaryVirtualPointers(BaseSubobject Base, + void LayoutSecondaryVirtualPointers(BaseSubobject Base, uint64_t VTableIndex); /// Lay out the VTTs for the virtual base classes of the given /// record declaration. void LayoutVirtualVTTs(const CXXRecordDecl *RD, VisitedVirtualBasesSetTy &VBases); - + /// Lay out the VTT for the given subobject, including any /// secondary VTTs, secondary virtual pointers and virtual VTTs. void LayoutVTT(BaseSubobject Base, bool BaseIsVirtual); - + public: VTTBuilder(ASTContext &Ctx, const CXXRecordDecl *MostDerivedClass, bool GenerateDefinition); @@ -142,17 +142,17 @@ public: const VTTComponentsVectorTy &getVTTComponents() const { return VTTComponents; } - + // Returns a reference to the VTT vtables. const VTTVTablesVectorTy &getVTTVTables() const { return VTTVTables; } - + /// Returns a reference to the sub-VTT indices. const llvm::DenseMap<BaseSubobject, uint64_t> &getSubVTTIndicies() const { return SubVTTIndicies; } - + /// Returns a reference to the secondary virtual pointer indices. const llvm::DenseMap<BaseSubobject, uint64_t> & getSecondaryVirtualPointerIndices() const { diff --git a/include/clang/AST/VTableBuilder.h b/include/clang/AST/VTableBuilder.h index 643103916149..4a779db01ff8 100644 --- a/include/clang/AST/VTableBuilder.h +++ b/include/clang/AST/VTableBuilder.h @@ -394,7 +394,7 @@ public: /// Return the offset in chars (relative to the vtable address point) where /// the offset of the virtual base that contains the given base is stored, - /// otherwise, if no virtual base contains the given class, return 0. + /// otherwise, if no virtual base contains the given class, return 0. /// /// Base must be a virtual base class or an unambiguous base. CharUnits getVirtualBaseOffsetOffset(const CXXRecordDecl *RD, diff --git a/include/clang/ASTMatchers/ASTMatchers.h b/include/clang/ASTMatchers/ASTMatchers.h index 58f65a39fb48..51f2ce2af75c 100644 --- a/include/clang/ASTMatchers/ASTMatchers.h +++ b/include/clang/ASTMatchers/ASTMatchers.h @@ -1247,7 +1247,7 @@ extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCMethodDecl> objcMethodDecl; /// Matches block declarations. -/// +/// /// Example matches the declaration of the nameless block printing an input /// integer. /// @@ -1654,7 +1654,6 @@ extern const internal::VariadicDynCastAllOfMatcher<Stmt, DeclRefExpr> /// - (void) init { /// a = @"hello"; /// } -//} /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCIvarRefExpr> objcIvarRefExpr; @@ -2886,7 +2885,7 @@ AST_MATCHER(ObjCMessageExpr, hasKeywordSelector) { AST_MATCHER_P(ObjCMessageExpr, numSelectorArgs, unsigned, N) { return Node.getSelector().getNumArgs() == N; } - + /// Matches if the call expression's callee expression matches. /// /// Given @@ -3679,7 +3678,7 @@ AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParam, /// \code /// b = ^(int y) { printf("%d", y) }; /// \endcode -/// +/// /// the matcher blockDecl(hasAnyParameter(hasName("y"))) /// matches the declaration of the block b with hasParameter /// matching y. @@ -5141,7 +5140,7 @@ extern const AstTypeMatcher<AutoType> autoType; /// int j = 42; /// decltype(i + j) result = i + j; /// \endcode -/// decltypeType() +/// decltypeType() /// matches "decltype(i + j)" extern const AstTypeMatcher<DecltypeType> decltypeType; @@ -6048,8 +6047,8 @@ AST_MATCHER(NamedDecl, hasExternalFormalLinkage) { /// void x(int val) {} /// void y(int val = 0) {} /// \endcode -AST_MATCHER(ParmVarDecl, hasDefaultArgument) { - return Node.hasDefaultArg(); +AST_MATCHER(ParmVarDecl, hasDefaultArgument) { + return Node.hasDefaultArg(); } /// Matches array new expressions. diff --git a/include/clang/Analysis/Analyses/CFGReachabilityAnalysis.h b/include/clang/Analysis/Analyses/CFGReachabilityAnalysis.h index da59514c4fa6..49da6815ace9 100644 --- a/include/clang/Analysis/Analyses/CFGReachabilityAnalysis.h +++ b/include/clang/Analysis/Analyses/CFGReachabilityAnalysis.h @@ -23,7 +23,7 @@ namespace clang { class CFG; class CFGBlock; - + // A class that performs reachability queries for CFGBlocks. Several internal // checks in this checker require reachability information. The requests all // tend to have a common destination, so we lazily do a predecessor search @@ -45,7 +45,7 @@ public: private: void mapReachability(const CFGBlock *Dst); }; - + } // namespace clang #endif // LLVM_CLANG_ANALYSIS_ANALYSES_CFGREACHABILITYANALYSIS_H diff --git a/include/clang/Analysis/Analyses/Consumed.h b/include/clang/Analysis/Analyses/Consumed.h index 6003d665fd88..5a70989e5087 100644 --- a/include/clang/Analysis/Analyses/Consumed.h +++ b/include/clang/Analysis/Analyses/Consumed.h @@ -38,18 +38,18 @@ class Stmt; class VarDecl; namespace consumed { - + class ConsumedStmtVisitor; enum ConsumedState { // No state information for the given variable. CS_None, - + CS_Unknown, CS_Unconsumed, CS_Consumed }; - + using OptionalNotes = SmallVector<PartialDiagnosticAt, 1>; using DelayedDiag = std::pair<PartialDiagnosticAt, OptionalNotes>; using DiagList = std::list<DelayedDiag>; @@ -60,7 +60,7 @@ namespace consumed { /// Emit the warnings and notes left by the analysis. virtual void emitDiagnostics() {} - + /// Warn that a variable's state doesn't match at the entry and exit /// of a loop. /// @@ -70,7 +70,7 @@ namespace consumed { /// state. virtual void warnLoopStateMismatch(SourceLocation Loc, StringRef VariableName) {} - + /// Warn about parameter typestate mismatches upon return. /// /// \param Loc -- The SourceLocation of the return statement. @@ -84,22 +84,22 @@ namespace consumed { StringRef VariableName, StringRef ExpectedState, StringRef ObservedState) {} - + // FIXME: Add documentation. virtual void warnParamTypestateMismatch(SourceLocation LOC, StringRef ExpectedState, StringRef ObservedState) {} - + // FIXME: This can be removed when the attr propagation fix for templated // classes lands. /// Warn about return typestates set for unconsumable types. - /// + /// /// \param Loc -- The location of the attributes. /// /// \param TypeName -- The name of the unconsumable type. virtual void warnReturnTypestateForUnconsumableType(SourceLocation Loc, StringRef TypeName) {} - + /// Warn about return typestate mismatches. /// /// \param Loc -- The SourceLocation of the return statement. @@ -144,71 +144,71 @@ namespace consumed { using VarMapType = llvm::DenseMap<const VarDecl *, ConsumedState>; using TmpMapType = llvm::DenseMap<const CXXBindTemporaryExpr *, ConsumedState>; - + protected: bool Reachable = true; const Stmt *From = nullptr; VarMapType VarMap; TmpMapType TmpMap; - + public: ConsumedStateMap() = default; ConsumedStateMap(const ConsumedStateMap &Other) : Reachable(Other.Reachable), From(Other.From), VarMap(Other.VarMap), TmpMap() {} - + /// Warn if any of the parameters being tracked are not in the state /// they were declared to be in upon return from a function. void checkParamsForReturnTypestate(SourceLocation BlameLoc, ConsumedWarningsHandlerBase &WarningsHandler) const; - + /// Clear the TmpMap. void clearTemporaries(); - + /// Get the consumed state of a given variable. ConsumedState getState(const VarDecl *Var) const; - + /// Get the consumed state of a given temporary value. ConsumedState getState(const CXXBindTemporaryExpr *Tmp) const; - + /// Merge this state map with another map. void intersect(const ConsumedStateMap &Other); void intersectAtLoopHead(const CFGBlock *LoopHead, const CFGBlock *LoopBack, const ConsumedStateMap *LoopBackStates, ConsumedWarningsHandlerBase &WarningsHandler); - + /// Return true if this block is reachable. bool isReachable() const { return Reachable; } - + /// Mark the block as unreachable. void markUnreachable(); - + /// Set the source for a decision about the branching of states. /// \param Source -- The statement that was the origin of a branching /// decision. void setSource(const Stmt *Source) { this->From = Source; } - + /// Set the consumed state of a given variable. void setState(const VarDecl *Var, ConsumedState State); - + /// Set the consumed state of a given temporary value. void setState(const CXXBindTemporaryExpr *Tmp, ConsumedState State); - + /// Remove the temporary value from our state map. void remove(const CXXBindTemporaryExpr *Tmp); - + /// Tests to see if there is a mismatch in the states stored in two /// maps. /// /// \param Other -- The second map to compare against. bool operator!=(const ConsumedStateMap *Other) const; }; - + class ConsumedBlockInfo { std::vector<std::unique_ptr<ConsumedStateMap>> StateMapsArray; std::vector<unsigned int> VisitOrder; - + public: ConsumedBlockInfo() = default; @@ -218,7 +218,7 @@ namespace consumed { for (const auto BI : *SortedGraph) VisitOrder[BI->getBlockID()] = VisitOrderCounter++; } - + bool allBackEdgesVisited(const CFGBlock *CurrBlock, const CFGBlock *TargetBlock); @@ -228,7 +228,7 @@ namespace consumed { std::unique_ptr<ConsumedStateMap> StateMap); ConsumedStateMap* borrowInfo(const CFGBlock *Block); - + void discardInfo(const CFGBlock *Block); std::unique_ptr<ConsumedStateMap> getInfo(const CFGBlock *Block); @@ -243,12 +243,12 @@ namespace consumed { std::unique_ptr<ConsumedStateMap> CurrStates; ConsumedState ExpectedReturnState; - + void determineExpectedReturnState(AnalysisDeclContext &AC, const FunctionDecl *D); bool splitState(const CFGBlock *CurrBlock, const ConsumedStmtVisitor &Visitor); - + public: ConsumedWarningsHandlerBase &WarningsHandler; @@ -256,7 +256,7 @@ namespace consumed { : WarningsHandler(WarningsHandler) {} ConsumedState getExpectedReturnState() const { return ExpectedReturnState; } - + /// Check a function's CFG for consumed violations. /// /// We traverse the blocks in the CFG, keeping track of the state of each diff --git a/include/clang/Analysis/Analyses/Dominators.h b/include/clang/Analysis/Analyses/Dominators.h index a9cdc5560bc0..021e98dcd885 100644 --- a/include/clang/Analysis/Analyses/Dominators.h +++ b/include/clang/Analysis/Analyses/Dominators.h @@ -20,7 +20,7 @@ #include "llvm/ADT/GraphTraits.h" #include "llvm/ADT/iterator.h" #include "llvm/Support/GenericDomTree.h" -#include "llvm/Support/GenericDomTreeConstruction.h" +#include "llvm/Support/GenericDomTreeConstruction.h" #include "llvm/Support/raw_ostream.h" // FIXME: There is no good reason for the domtree to require a print method diff --git a/include/clang/Analysis/Analyses/FormatString.h b/include/clang/Analysis/Analyses/FormatString.h index 6f8bb9b4095f..598d341ac829 100644 --- a/include/clang/Analysis/Analyses/FormatString.h +++ b/include/clang/Analysis/Analyses/FormatString.h @@ -236,7 +236,7 @@ public: const char *toString() const; bool isPrintfKind() const { return IsPrintf; } - + Optional<ConversionSpecifier> getStandardSpecifier() const; protected: diff --git a/include/clang/Analysis/Analyses/LiveVariables.h b/include/clang/Analysis/Analyses/LiveVariables.h index 21c3ba255c36..0cb500fffb95 100644 --- a/include/clang/Analysis/Analyses/LiveVariables.h +++ b/include/clang/Analysis/Analyses/LiveVariables.h @@ -25,7 +25,7 @@ class CFGBlock; class Stmt; class DeclRefExpr; class SourceManager; - + class LiveVariables : public ManagedAnalysis { public: class LivenessValues { @@ -34,7 +34,7 @@ public: llvm::ImmutableSet<const Stmt *> liveStmts; llvm::ImmutableSet<const VarDecl *> liveDecls; llvm::ImmutableSet<const BindingDecl *> liveBindings; - + bool equals(const LivenessValues &V) const; LivenessValues() @@ -48,21 +48,21 @@ public: bool isLive(const Stmt *S) const; bool isLive(const VarDecl *D) const; - - friend class LiveVariables; + + friend class LiveVariables; }; - + class Observer { virtual void anchor(); public: virtual ~Observer() {} - + /// A callback invoked right before invoking the /// liveness transfer function on the given statement. virtual void observeStmt(const Stmt *S, const CFGBlock *currentBlock, const LivenessValues& V) {} - + /// Called when the live variables analysis registers /// that a variable is killed. virtual void observerKill(const DeclRefExpr *DR) {} @@ -73,47 +73,47 @@ public: /// Compute the liveness information for a given CFG. static LiveVariables *computeLiveness(AnalysisDeclContext &analysisContext, bool killAtAssign); - + /// Return true if a variable is live at the end of a /// specified block. bool isLive(const CFGBlock *B, const VarDecl *D); - + /// Returns true if a variable is live at the beginning of the /// the statement. This query only works if liveness information /// has been recorded at the statement level (see runOnAllBlocks), and /// only returns liveness information for block-level expressions. bool isLive(const Stmt *S, const VarDecl *D); - + /// Returns true the block-level expression "value" is live /// before the given block-level expression (see runOnAllBlocks). bool isLive(const Stmt *Loc, const Stmt *StmtVal); - + /// Print to stderr the liveness information associated with /// each basic block. void dumpBlockLiveness(const SourceManager& M); void runOnAllBlocks(Observer &obs); - + static LiveVariables *create(AnalysisDeclContext &analysisContext) { return computeLiveness(analysisContext, true); } - + static const void *getTag(); - + private: LiveVariables(void *impl); void *impl; }; - + class RelaxedLiveVariables : public LiveVariables { public: static LiveVariables *create(AnalysisDeclContext &analysisContext) { return computeLiveness(analysisContext, false); } - + static const void *getTag(); }; - + } // end namespace clang #endif diff --git a/include/clang/Analysis/Analyses/ReachableCode.h b/include/clang/Analysis/Analyses/ReachableCode.h index 4c523bfc8b56..d79f1b03df7b 100644 --- a/include/clang/Analysis/Analyses/ReachableCode.h +++ b/include/clang/Analysis/Analyses/ReachableCode.h @@ -57,7 +57,7 @@ public: }; /// ScanReachableFromBlock - Mark all blocks reachable from Start. -/// Returns the total number of blocks that were marked reachable. +/// Returns the total number of blocks that were marked reachable. unsigned ScanReachableFromBlock(const CFGBlock *Start, llvm::BitVector &Reachable); diff --git a/include/clang/Analysis/Analyses/ThreadSafetyCommon.h b/include/clang/Analysis/Analyses/ThreadSafetyCommon.h index 580872e17ef4..599c164923cb 100644 --- a/include/clang/Analysis/Analyses/ThreadSafetyCommon.h +++ b/include/clang/Analysis/Analyses/ThreadSafetyCommon.h @@ -500,7 +500,7 @@ private: std::vector<til::BasicBlock *> BlockMap; // Extra information per BB. Indexed by clang BlockID. - std::vector<BlockInfo> BBInfo; + std::vector<BlockInfo> BBInfo; LVarDefinitionMap CurrentLVarMap; std::vector<til::Phi *> CurrentArguments; diff --git a/include/clang/Analysis/AnalysisDeclContext.h b/include/clang/Analysis/AnalysisDeclContext.h index 8c391b5ee1e5..19531d92e645 100644 --- a/include/clang/Analysis/AnalysisDeclContext.h +++ b/include/clang/Analysis/AnalysisDeclContext.h @@ -111,7 +111,7 @@ public: AnalysisDeclContextManager *getManager() const { return Manager; } - + /// Return the build options used to construct the CFG. CFG::BuildOptions &getCFGBuildOptions() { return cfgBuildOptions; @@ -190,7 +190,7 @@ public: const Stmt *S, const CFGBlock *Blk, unsigned Idx); - + const BlockInvocationContext * getBlockInvocationContext(const LocationContext *parent, const BlockDecl *BD, @@ -359,7 +359,7 @@ class BlockInvocationContext : public LocationContext { friend class LocationContextManager; const BlockDecl *BD; - + // FIXME: Come up with a more type-safe way to model context-sensitivity. const void *ContextData; @@ -372,7 +372,7 @@ public: ~BlockInvocationContext() override = default; const BlockDecl *getBlockDecl() const { return BD; } - + const void *getContextData() const { return ContextData; } void Profile(llvm::FoldingSetNodeID &ID) override; @@ -403,7 +403,7 @@ public: const ScopeContext *getScope(AnalysisDeclContext *ctx, const LocationContext *parent, const Stmt *s); - + const BlockInvocationContext * getBlockInvocationContext(AnalysisDeclContext *ctx, const LocationContext *parent, @@ -463,7 +463,7 @@ public: CFG::BuildOptions &getCFGBuildOptions() { return cfgBuildOptions; } - + /// Return true if faux bodies should be synthesized for well-known /// functions. bool synthesizeBodies() const { return SynthesizeBodies; } diff --git a/include/clang/Analysis/CFG.h b/include/clang/Analysis/CFG.h index f25789822d16..bf81d8358a54 100644 --- a/include/clang/Analysis/CFG.h +++ b/include/clang/Analysis/CFG.h @@ -15,9 +15,10 @@ #ifndef LLVM_CLANG_ANALYSIS_CFG_H #define LLVM_CLANG_ANALYSIS_CFG_H -#include "clang/AST/ExprCXX.h" #include "clang/Analysis/Support/BumpVector.h" #include "clang/Analysis/ConstructionContext.h" +#include "clang/AST/ExprCXX.h" +#include "clang/AST/ExprObjC.h" #include "clang/Basic/LLVM.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/GraphTraits.h" @@ -51,7 +52,7 @@ class FieldDecl; class LangOptions; class VarDecl; -/// CFGElement - Represents a top-level expression in a basic block. +/// Represents a top-level expression in a basic block. class CFGElement { public: enum Kind { @@ -144,9 +145,9 @@ protected: CFGStmt() = default; }; -/// CFGConstructor - Represents C++ constructor call. Maintains information -/// necessary to figure out what memory is being initialized by the -/// constructor expression. For now this is only used by the analyzer's CFG. +/// Represents C++ constructor call. Maintains information necessary to figure +/// out what memory is being initialized by the constructor expression. For now +/// this is only used by the analyzer's CFG. class CFGConstructor : public CFGStmt { public: explicit CFGConstructor(CXXConstructExpr *CE, const ConstructionContext *C) @@ -169,30 +170,34 @@ private: } }; -/// CFGCXXRecordTypedCall - Represents a function call that returns a C++ object -/// by value. This, like constructor, requires a construction context in order -/// to understand the storage of the returned object . In C such tracking is not -/// necessary because no additional effort is required for destroying the object -/// or modeling copy elision. Like CFGConstructor, this element is for now only -/// used by the analyzer's CFG. +/// Represents a function call that returns a C++ object by value. This, like +/// constructor, requires a construction context in order to understand the +/// storage of the returned object . In C such tracking is not necessary because +/// no additional effort is required for destroying the object or modeling copy +/// elision. Like CFGConstructor, this element is for now only used by the +/// analyzer's CFG. class CFGCXXRecordTypedCall : public CFGStmt { public: /// Returns true when call expression \p CE needs to be represented /// by CFGCXXRecordTypedCall, as opposed to a regular CFGStmt. - static bool isCXXRecordTypedCall(CallExpr *CE, const ASTContext &ACtx) { - return CE->getCallReturnType(ACtx).getCanonicalType()->getAsCXXRecordDecl(); - } - - explicit CFGCXXRecordTypedCall(CallExpr *CE, const ConstructionContext *C) - : CFGStmt(CE, CXXRecordTypedCall) { - // FIXME: This is not protected against squeezing a non-record-typed-call - // into the constructor. An assertion would require passing an ASTContext - // which would mean paying for something we don't use. + static bool isCXXRecordTypedCall(Expr *E) { + assert(isa<CallExpr>(E) || isa<ObjCMessageExpr>(E)); + // There is no such thing as reference-type expression. If the function + // returns a reference, it'll return the respective lvalue or xvalue + // instead, and we're only interested in objects. + return !E->isGLValue() && + E->getType().getCanonicalType()->getAsCXXRecordDecl(); + } + + explicit CFGCXXRecordTypedCall(Expr *E, const ConstructionContext *C) + : CFGStmt(E, CXXRecordTypedCall) { + assert(isCXXRecordTypedCall(E)); assert(C && (isa<TemporaryObjectConstructionContext>(C) || // These are possible in C++17 due to mandatory copy elision. isa<ReturnedValueConstructionContext>(C) || isa<VariableConstructionContext>(C) || - isa<ConstructorInitializerConstructionContext>(C))); + isa<ConstructorInitializerConstructionContext>(C) || + isa<ArgumentConstructionContext>(C))); Data2.setPointer(const_cast<ConstructionContext *>(C)); } @@ -210,8 +215,8 @@ private: } }; -/// CFGInitializer - Represents C++ base or member initializer from -/// constructor's initialization list. +/// Represents C++ base or member initializer from constructor's initialization +/// list. class CFGInitializer : public CFGElement { public: explicit CFGInitializer(CXXCtorInitializer *initializer) @@ -231,7 +236,7 @@ private: } }; -/// CFGNewAllocator - Represents C++ allocator call. +/// Represents C++ allocator call. class CFGNewAllocator : public CFGElement { public: explicit CFGNewAllocator(const CXXNewExpr *S) @@ -349,8 +354,8 @@ private: } }; -/// CFGImplicitDtor - Represents C++ object destructor implicitly generated -/// by compiler on various occasions. +/// Represents C++ object destructor implicitly generated by compiler on various +/// occasions. class CFGImplicitDtor : public CFGElement { protected: CFGImplicitDtor() = default; @@ -373,9 +378,9 @@ private: } }; -/// CFGAutomaticObjDtor - Represents C++ object destructor implicitly generated -/// for automatic object or temporary bound to const reference at the point -/// of leaving its local scope. +/// Represents C++ object destructor implicitly generated for automatic object +/// or temporary bound to const reference at the point of leaving its local +/// scope. class CFGAutomaticObjDtor: public CFGImplicitDtor { public: CFGAutomaticObjDtor(const VarDecl *var, const Stmt *stmt) @@ -400,8 +405,7 @@ private: } }; -/// CFGDeleteDtor - Represents C++ object destructor generated -/// from a call to delete. +/// Represents C++ object destructor generated from a call to delete. class CFGDeleteDtor : public CFGImplicitDtor { public: CFGDeleteDtor(const CXXRecordDecl *RD, const CXXDeleteExpr *DE) @@ -426,8 +430,8 @@ private: } }; -/// CFGBaseDtor - Represents C++ object destructor implicitly generated for -/// base object in destructor. +/// Represents C++ object destructor implicitly generated for base object in +/// destructor. class CFGBaseDtor : public CFGImplicitDtor { public: CFGBaseDtor(const CXXBaseSpecifier *base) @@ -447,8 +451,8 @@ private: } }; -/// CFGMemberDtor - Represents C++ object destructor implicitly generated for -/// member object in destructor. +/// Represents C++ object destructor implicitly generated for member object in +/// destructor. class CFGMemberDtor : public CFGImplicitDtor { public: CFGMemberDtor(const FieldDecl *field) @@ -468,8 +472,8 @@ private: } }; -/// CFGTemporaryDtor - Represents C++ object destructor implicitly generated -/// at the end of full expression for temporary object. +/// Represents C++ object destructor implicitly generated at the end of full +/// expression for temporary object. class CFGTemporaryDtor : public CFGImplicitDtor { public: CFGTemporaryDtor(CXXBindTemporaryExpr *expr) @@ -489,7 +493,7 @@ private: } }; -/// CFGTerminator - Represents CFGBlock terminator statement. +/// Represents CFGBlock terminator statement. /// /// TemporaryDtorsBranch bit is set to true if the terminator marks a branch /// in control flow of destructors of temporaries. In this case terminator @@ -520,7 +524,7 @@ public: explicit operator bool() const { return getStmt(); } }; -/// CFGBlock - Represents a single basic block in a source-level CFG. +/// Represents a single basic block in a source-level CFG. /// It consists of: /// /// (1) A set of statements/expressions (which may contain subexpressions). @@ -588,26 +592,24 @@ class CFGBlock { bool empty() const { return Impl.empty(); } }; - /// Stmts - The set of statements in the basic block. + /// The set of statements in the basic block. ElementList Elements; - /// Label - An (optional) label that prefixes the executable - /// statements in the block. When this variable is non-NULL, it is - /// either an instance of LabelStmt, SwitchCase or CXXCatchStmt. + /// An (optional) label that prefixes the executable statements in the block. + /// When this variable is non-NULL, it is either an instance of LabelStmt, + /// SwitchCase or CXXCatchStmt. Stmt *Label = nullptr; - /// Terminator - The terminator for a basic block that - /// indicates the type of control-flow that occurs between a block - /// and its successors. + /// The terminator for a basic block that indicates the type of control-flow + /// that occurs between a block and its successors. CFGTerminator Terminator; - /// LoopTarget - Some blocks are used to represent the "loop edge" to - /// the start of a loop from within the loop body. This Stmt* will be - /// refer to the loop statement for such blocks (and be null otherwise). + /// Some blocks are used to represent the "loop edge" to the start of a loop + /// from within the loop body. This Stmt* will be refer to the loop statement + /// for such blocks (and be null otherwise). const Stmt *LoopTarget = nullptr; - /// BlockID - A numerical ID assigned to a CFGBlock during construction - /// of the CFG. + /// A numerical ID assigned to a CFGBlock during construction of the CFG. unsigned BlockID; public: @@ -629,7 +631,7 @@ public: public: /// Construct an AdjacentBlock with a possibly unreachable block. AdjacentBlock(CFGBlock *B, bool IsReachable); - + /// Construct an AdjacentBlock with a reachable block and an alternate /// unreachable block. AdjacentBlock(CFGBlock *B, CFGBlock *AlternateBlock); @@ -665,13 +667,12 @@ public: }; private: - /// Predecessors/Successors - Keep track of the predecessor / successor - /// CFG blocks. + /// Keep track of the predecessor / successor CFG blocks. using AdjacentBlocks = BumpVector<AdjacentBlock>; AdjacentBlocks Preds; AdjacentBlocks Succs; - /// NoReturn - This bit is set when the basic block contains a function call + /// This bit is set when the basic block contains a function call /// or implicit destructor that is attributed as 'noreturn'. In that case, /// control cannot technically ever proceed past this block. All such blocks /// will have a single immediate successor: the exit block. This allows them @@ -682,7 +683,7 @@ private: /// storage if the memory usage of CFGBlock becomes an issue. unsigned HasNoReturnElement : 1; - /// Parent - The parent CFG that owns this CFGBlock. + /// The parent CFG that owns this CFGBlock. CFG *Parent; public: @@ -878,10 +879,10 @@ public: Elements.push_back(CFGConstructor(CE, CC), C); } - void appendCXXRecordTypedCall(CallExpr *CE, + void appendCXXRecordTypedCall(Expr *E, const ConstructionContext *CC, BumpVectorContext &C) { - Elements.push_back(CFGCXXRecordTypedCall(CE, CC), C); + Elements.push_back(CFGCXXRecordTypedCall(E, CC), C); } void appendInitializer(CXXCtorInitializer *initializer, @@ -992,7 +993,7 @@ public: bool isAlwaysTrue) {} }; -/// CFG - Represents a source-level, intra-procedural CFG that represents the +/// Represents a source-level, intra-procedural CFG that represents the /// control-flow of a Stmt. The Stmt can represent an entire function body, /// or a single expression. A CFG will always contain one empty block that /// represents the Exit point of the CFG. A CFG will also contain a designated @@ -1044,21 +1045,21 @@ public: } }; - /// buildCFG - Builds a CFG from an AST. + /// Builds a CFG from an AST. static std::unique_ptr<CFG> buildCFG(const Decl *D, Stmt *AST, ASTContext *C, const BuildOptions &BO); - /// createBlock - Create a new block in the CFG. The CFG owns the block; - /// the caller should not directly free it. + /// Create a new block in the CFG. The CFG owns the block; the caller should + /// not directly free it. CFGBlock *createBlock(); - /// setEntry - Set the entry block of the CFG. This is typically used - /// only during CFG construction. Most CFG clients expect that the - /// entry block has no predecessors and contains no statements. + /// Set the entry block of the CFG. This is typically used only during CFG + /// construction. Most CFG clients expect that the entry block has no + /// predecessors and contains no statements. void setEntry(CFGBlock *B) { Entry = B; } - /// setIndirectGotoBlock - Set the block used for indirect goto jumps. - /// This is typically used only during CFG construction. + /// Set the block used for indirect goto jumps. This is typically used only + /// during CFG construction. void setIndirectGotoBlock(CFGBlock *B) { IndirectGotoBlock = B; } //===--------------------------------------------------------------------===// @@ -1152,8 +1153,8 @@ public: template <typename CALLBACK> void VisitBlockStmts(CALLBACK& O) const { - for (const_iterator I=begin(), E=end(); I != E; ++I) - for (CFGBlock::const_iterator BI=(*I)->begin(), BE=(*I)->end(); + for (const_iterator I = begin(), E = end(); I != E; ++I) + for (CFGBlock::const_iterator BI = (*I)->begin(), BE = (*I)->end(); BI != BE; ++BI) { if (Optional<CFGStmt> stmt = BI->getAs<CFGStmt>()) O(const_cast<Stmt*>(stmt->getStmt())); @@ -1164,13 +1165,12 @@ public: // CFG Introspection. //===--------------------------------------------------------------------===// - /// getNumBlockIDs - Returns the total number of BlockIDs allocated (which - /// start at 0). + /// Returns the total number of BlockIDs allocated (which start at 0). unsigned getNumBlockIDs() const { return NumBlockIDs; } - /// size - Return the total number of CFGBlocks within the CFG - /// This is simply a renaming of the getNumBlockIDs(). This is necessary - /// because the dominator implementation needs such an interface. + /// Return the total number of CFGBlocks within the CFG This is simply a + /// renaming of the getNumBlockIDs(). This is necessary because the dominator + /// implementation needs such an interface. unsigned size() const { return NumBlockIDs; } //===--------------------------------------------------------------------===// diff --git a/include/clang/Analysis/CFGStmtMap.h b/include/clang/Analysis/CFGStmtMap.h index 4dfa91df0f42..78e637daf379 100644 --- a/include/clang/Analysis/CFGStmtMap.h +++ b/include/clang/Analysis/CFGStmtMap.h @@ -19,20 +19,18 @@ namespace clang { -class CFG; -class CFGBlock; class ParentMap; class Stmt; class CFGStmtMap { ParentMap *PM; void *M; - + CFGStmtMap(ParentMap *pm, void *m) : PM(pm), M(m) {} - + public: ~CFGStmtMap(); - + /// Returns a new CFGMap for the given CFG. It is the caller's /// responsibility to 'delete' this object when done using it. static CFGStmtMap *Build(CFG* C, ParentMap *PM); diff --git a/include/clang/Analysis/CloneDetection.h b/include/clang/Analysis/CloneDetection.h index 955777a11a65..915ec58a5144 100644 --- a/include/clang/Analysis/CloneDetection.h +++ b/include/clang/Analysis/CloneDetection.h @@ -332,7 +332,7 @@ struct FilenamePatternConstraint { StringRef IgnoredFilesPattern; std::shared_ptr<llvm::Regex> IgnoredFilesRegex; - FilenamePatternConstraint(StringRef IgnoredFilesPattern) + FilenamePatternConstraint(StringRef IgnoredFilesPattern) : IgnoredFilesPattern(IgnoredFilesPattern) { IgnoredFilesRegex = std::make_shared<llvm::Regex>("^(" + IgnoredFilesPattern.str() + "$)"); diff --git a/include/clang/Analysis/ConstructionContext.h b/include/clang/Analysis/ConstructionContext.h index 40cb0e7e5dda..aee67865df25 100644 --- a/include/clang/Analysis/ConstructionContext.h +++ b/include/clang/Analysis/ConstructionContext.h @@ -22,65 +22,200 @@ namespace clang { -/// Construction context is a linked list of multiple layers. Layers are -/// created gradually while traversing the AST, and layers that represent -/// the outmost AST nodes are built first, while the node that immediately -/// contains the constructor would be built last and capture the previous -/// layers as its parents. Construction context captures the last layer -/// (which has links to the previous layers) and classifies the seemingly -/// arbitrary chain of layers into one of the possible ways of constructing -/// an object in C++ for user-friendly experience. -class ConstructionContextLayer { +/// Represents a single point (AST node) in the program that requires attention +/// during construction of an object. ConstructionContext would be represented +/// as a list of such items. +class ConstructionContextItem { public: - typedef llvm::PointerUnion<Stmt *, CXXCtorInitializer *> TriggerTy; + enum ItemKind { + VariableKind, + NewAllocatorKind, + ReturnKind, + MaterializationKind, + TemporaryDestructorKind, + ElidedDestructorKind, + ElidableConstructorKind, + ArgumentKind, + STATEMENT_WITH_INDEX_KIND_BEGIN=ArgumentKind, + STATEMENT_WITH_INDEX_KIND_END=ArgumentKind, + STATEMENT_KIND_BEGIN = VariableKind, + STATEMENT_KIND_END = ArgumentKind, + InitializerKind, + INITIALIZER_KIND_BEGIN=InitializerKind, + INITIALIZER_KIND_END=InitializerKind + }; + + LLVM_DUMP_METHOD static StringRef getKindAsString(ItemKind K) { + switch (K) { + case VariableKind: return "construct into local variable"; + case NewAllocatorKind: return "construct into new-allocator"; + case ReturnKind: return "construct into return address"; + case MaterializationKind: return "materialize temporary"; + case TemporaryDestructorKind: return "destroy temporary"; + case ElidedDestructorKind: return "elide destructor"; + case ElidableConstructorKind: return "elide constructor"; + case ArgumentKind: return "construct into argument"; + case InitializerKind: return "construct into member variable"; + }; + llvm_unreachable("Unknown ItemKind"); + } private: + const void *const Data; + const ItemKind Kind; + const unsigned Index = 0; + + bool hasStatement() const { + return Kind >= STATEMENT_KIND_BEGIN && + Kind <= STATEMENT_KIND_END; + } + + bool hasIndex() const { + return Kind >= STATEMENT_WITH_INDEX_KIND_BEGIN && + Kind >= STATEMENT_WITH_INDEX_KIND_END; + } + + bool hasInitializer() const { + return Kind >= INITIALIZER_KIND_BEGIN && + Kind <= INITIALIZER_KIND_END; + } + +public: + // ConstructionContextItem should be simple enough so that it was easy to + // re-construct it from the AST node it captures. For that reason we provide + // simple implicit conversions from all sorts of supported AST nodes. + ConstructionContextItem(const DeclStmt *DS) + : Data(DS), Kind(VariableKind) {} + + ConstructionContextItem(const CXXNewExpr *NE) + : Data(NE), Kind(NewAllocatorKind) {} + + ConstructionContextItem(const ReturnStmt *RS) + : Data(RS), Kind(ReturnKind) {} + + ConstructionContextItem(const MaterializeTemporaryExpr *MTE) + : Data(MTE), Kind(MaterializationKind) {} + + ConstructionContextItem(const CXXBindTemporaryExpr *BTE, + bool IsElided = false) + : Data(BTE), + Kind(IsElided ? ElidedDestructorKind : TemporaryDestructorKind) {} + + ConstructionContextItem(const CXXConstructExpr *CE) + : Data(CE), Kind(ElidableConstructorKind) {} + + ConstructionContextItem(const CallExpr *CE, unsigned Index) + : Data(CE), Kind(ArgumentKind), Index(Index) {} + + ConstructionContextItem(const CXXConstructExpr *CE, unsigned Index) + : Data(CE), Kind(ArgumentKind), Index(Index) {} + + ConstructionContextItem(const ObjCMessageExpr *ME, unsigned Index) + : Data(ME), Kind(ArgumentKind), Index(Index) {} + + // A polymorphic version of the previous calls with dynamic type check. + ConstructionContextItem(const Expr *E, unsigned Index) + : Data(E), Kind(ArgumentKind), Index(Index) { + assert(isa<CallExpr>(E) || isa<CXXConstructExpr>(E) || + isa<ObjCMessageExpr>(E)); + } + + ConstructionContextItem(const CXXCtorInitializer *Init) + : Data(Init), Kind(InitializerKind), Index(0) {} + + ItemKind getKind() const { return Kind; } + + LLVM_DUMP_METHOD StringRef getKindAsString() const { + return getKindAsString(getKind()); + } + /// The construction site - the statement that triggered the construction /// for one of its parts. For instance, stack variable declaration statement /// triggers construction of itself or its elements if it's an array, /// new-expression triggers construction of the newly allocated object(s). - TriggerTy Trigger; - - /// Sometimes a single trigger is not enough to describe the construction - /// site. In this case we'd have a chain of "partial" construction context - /// layers. - /// Some examples: - /// - A constructor within in an aggregate initializer list within a variable - /// would have a construction context of the initializer list with - /// the parent construction context of a variable. - /// - A constructor for a temporary that needs to be both destroyed - /// and materialized into an elidable copy constructor would have a - /// construction context of a CXXBindTemporaryExpr with the parent - /// construction context of a MaterializeTemproraryExpr. - /// Not all of these are currently supported. - const ConstructionContextLayer *Parent = nullptr; + const Stmt *getStmt() const { + assert(hasStatement()); + return static_cast<const Stmt *>(Data); + } - ConstructionContextLayer(TriggerTy Trigger, - const ConstructionContextLayer *Parent) - : Trigger(Trigger), Parent(Parent) {} + const Stmt *getStmtOrNull() const { + return hasStatement() ? getStmt() : nullptr; + } -public: - static const ConstructionContextLayer * - create(BumpVectorContext &C, TriggerTy Trigger, - const ConstructionContextLayer *Parent = nullptr); + /// The construction site is not necessarily a statement. It may also be a + /// CXXCtorInitializer, which means that a member variable is being + /// constructed during initialization of the object that contains it. + const CXXCtorInitializer *getCXXCtorInitializer() const { + assert(hasInitializer()); + return static_cast<const CXXCtorInitializer *>(Data); + } - const ConstructionContextLayer *getParent() const { return Parent; } - bool isLast() const { return !Parent; } + /// If a single trigger statement triggers multiple constructors, they are + /// usually being enumerated. This covers function argument constructors + /// triggered by a call-expression and items in an initializer list triggered + /// by an init-list-expression. + unsigned getIndex() const { + // This is a fairly specific request. Let's make sure the user knows + // what he's doing. + assert(hasIndex()); + return Index; + } - const Stmt *getTriggerStmt() const { - return Trigger.dyn_cast<Stmt *>(); + void Profile(llvm::FoldingSetNodeID &ID) const { + ID.AddPointer(Data); + ID.AddInteger(Kind); + ID.AddInteger(Index); } - const CXXCtorInitializer *getTriggerInit() const { - return Trigger.dyn_cast<CXXCtorInitializer *>(); + bool operator==(const ConstructionContextItem &Other) const { + // For most kinds the Index comparison is trivially true, but + // checking kind separately doesn't seem to be less expensive + // than checking Index. Same in operator<(). + return std::make_tuple(Data, Kind, Index) == + std::make_tuple(Other.Data, Other.Kind, Other.Index); } - /// Returns true if these layers are equal as individual layers, even if - /// their parents are different. - bool isSameLayer(const ConstructionContextLayer *Other) const { - assert(Other); - return (Trigger == Other->Trigger); + bool operator<(const ConstructionContextItem &Other) const { + return std::make_tuple(Data, Kind, Index) < + std::make_tuple(Other.Data, Other.Kind, Other.Index); } +}; + +/// Construction context can be seen as a linked list of multiple layers. +/// Sometimes a single trigger is not enough to describe the construction +/// site. That's what causing us to have a chain of "partial" construction +/// context layers. Some examples: +/// - A constructor within in an aggregate initializer list within a variable +/// would have a construction context of the initializer list with +/// the parent construction context of a variable. +/// - A constructor for a temporary that needs to be both destroyed +/// and materialized into an elidable copy constructor would have a +/// construction context of a CXXBindTemporaryExpr with the parent +/// construction context of a MaterializeTemproraryExpr. +/// Not all of these are currently supported. +/// Layers are created gradually while traversing the AST, and layers that +/// represent the outmost AST nodes are built first, while the node that +/// immediately contains the constructor would be built last and capture the +/// previous layers as its parents. Construction context captures the last layer +/// (which has links to the previous layers) and classifies the seemingly +/// arbitrary chain of layers into one of the possible ways of constructing +/// an object in C++ for user-friendly experience. +class ConstructionContextLayer { + const ConstructionContextLayer *Parent = nullptr; + ConstructionContextItem Item; + + ConstructionContextLayer(ConstructionContextItem Item, + const ConstructionContextLayer *Parent) + : Parent(Parent), Item(Item) {} + +public: + static const ConstructionContextLayer * + create(BumpVectorContext &C, const ConstructionContextItem &Item, + const ConstructionContextLayer *Parent = nullptr); + + const ConstructionContextItem &getItem() const { return Item; } + const ConstructionContextLayer *getParent() const { return Parent; } + bool isLast() const { return !Parent; } /// See if Other is a proper initial segment of this construction context /// in terms of the parent chain - i.e. a few first parents coincide and @@ -114,7 +249,8 @@ public: SimpleReturnedValueKind, CXX17ElidedCopyReturnedValueKind, RETURNED_VALUE_BEGIN = SimpleReturnedValueKind, - RETURNED_VALUE_END = CXX17ElidedCopyReturnedValueKind + RETURNED_VALUE_END = CXX17ElidedCopyReturnedValueKind, + ArgumentKind }; protected: @@ -132,6 +268,23 @@ private: return new (CC) T(Args...); } + // A sub-routine of createFromLayers() that deals with temporary objects + // that need to be materialized. The BTE argument is for the situation when + // the object also needs to be bound for destruction. + static const ConstructionContext *createMaterializedTemporaryFromLayers( + BumpVectorContext &C, const MaterializeTemporaryExpr *MTE, + const CXXBindTemporaryExpr *BTE, + const ConstructionContextLayer *ParentLayer); + + // A sub-routine of createFromLayers() that deals with temporary objects + // that need to be bound for destruction. Automatically finds out if the + // object also needs to be materialized and delegates to + // createMaterializedTemporaryFromLayers() if necessary. + static const ConstructionContext * + createBoundTemporaryFromLayers( + BumpVectorContext &C, const CXXBindTemporaryExpr *BTE, + const ConstructionContextLayer *ParentLayer); + public: /// Consume the construction context layer, together with its parent layers, /// and wrap it up into a complete construction context. May return null @@ -469,6 +622,32 @@ public: } }; +class ArgumentConstructionContext : public ConstructionContext { + const Expr *CE; // The call of which the context is an argument. + unsigned Index; // Which argument we're constructing. + const CXXBindTemporaryExpr *BTE; // Whether the object needs to be destroyed. + + friend class ConstructionContext; // Allows to create<>() itself. + + explicit ArgumentConstructionContext(const Expr *CE, unsigned Index, + const CXXBindTemporaryExpr *BTE) + : ConstructionContext(ArgumentKind), CE(CE), + Index(Index), BTE(BTE) { + assert(isa<CallExpr>(CE) || isa<CXXConstructExpr>(CE) || + isa<ObjCMessageExpr>(CE)); + // BTE is optional. + } + +public: + const Expr *getCallLikeExpr() const { return CE; } + unsigned getIndex() const { return Index; } + const CXXBindTemporaryExpr *getCXXBindTemporaryExpr() const { return BTE; } + + static bool classof(const ConstructionContext *CC) { + return CC->getKind() == ArgumentKind; + } +}; + } // end namespace clang #endif // LLVM_CLANG_ANALYSIS_CONSTRUCTIONCONTEXT_H diff --git a/include/clang/Analysis/DomainSpecific/CocoaConventions.h b/include/clang/Analysis/DomainSpecific/CocoaConventions.h index 8b3fcff52d08..9326d1abbac1 100644 --- a/include/clang/Analysis/DomainSpecific/CocoaConventions.h +++ b/include/clang/Analysis/DomainSpecific/CocoaConventions.h @@ -7,7 +7,7 @@ // //===----------------------------------------------------------------------===// // -// This file implements cocoa naming convention analysis. +// This file implements cocoa naming convention analysis. // //===----------------------------------------------------------------------===// @@ -20,20 +20,20 @@ namespace clang { class FunctionDecl; class QualType; - + namespace ento { namespace cocoa { - + bool isRefType(QualType RetTy, StringRef Prefix, StringRef Name = StringRef()); - + bool isCocoaObjectRef(QualType T); } namespace coreFoundation { bool isCFObjectRef(QualType T); - + bool followsCreateRule(const FunctionDecl *FD); } diff --git a/include/clang/Analysis/DomainSpecific/ObjCNoReturn.h b/include/clang/Analysis/DomainSpecific/ObjCNoReturn.h index f9e800a4a412..e304d83615d4 100644 --- a/include/clang/Analysis/DomainSpecific/ObjCNoReturn.h +++ b/include/clang/Analysis/DomainSpecific/ObjCNoReturn.h @@ -21,7 +21,7 @@ namespace clang { class ASTContext; class ObjCMessageExpr; - + class ObjCNoReturn { /// Cached "raise" selector. Selector RaiseSel; @@ -36,7 +36,7 @@ class ObjCNoReturn { public: ObjCNoReturn(ASTContext &C); - + /// Return true if the given message expression is known to never /// return. bool isImplicitNoReturn(const ObjCMessageExpr *ME); diff --git a/include/clang/Analysis/ProgramPoint.h b/include/clang/Analysis/ProgramPoint.h index e8f0d61617eb..25ae93fae6b8 100644 --- a/include/clang/Analysis/ProgramPoint.h +++ b/include/clang/Analysis/ProgramPoint.h @@ -33,7 +33,7 @@ namespace clang { class AnalysisDeclContext; class FunctionDecl; class LocationContext; - + /// ProgramPoints can be "tagged" as representing points specific to a given /// analysis entity. Tags are abstract annotations, with an associated /// description and potentially other information. @@ -41,12 +41,12 @@ class ProgramPointTag { public: ProgramPointTag(void *tagKind = nullptr) : TagKind(tagKind) {} virtual ~ProgramPointTag(); - virtual StringRef getTagDescription() const = 0; + virtual StringRef getTagDescription() const = 0; protected: /// Used to implement 'isKind' in subclasses. const void *getTagKind() { return TagKind; } - + private: const void *TagKind; }; @@ -111,7 +111,7 @@ protected: assert(getLocationContext() == l); assert(getData1() == P); } - + ProgramPoint(const void *P1, const void *P2, Kind k, @@ -223,7 +223,7 @@ class BlockEntrance : public ProgramPoint { public: BlockEntrance(const CFGBlock *B, const LocationContext *L, const ProgramPointTag *tag = nullptr) - : ProgramPoint(B, BlockEntranceKind, L, tag) { + : ProgramPoint(B, BlockEntranceKind, L, tag) { assert(B && "BlockEntrance requires non-null block"); } @@ -235,7 +235,7 @@ public: const CFGBlock *B = getBlock(); return B->empty() ? Optional<CFGElement>() : B->front(); } - + private: friend class ProgramPoint; BlockEntrance() = default; @@ -350,7 +350,7 @@ protected: LocationCheck(const Stmt *S, const LocationContext *L, ProgramPoint::Kind K, const ProgramPointTag *tag) : StmtPoint(S, nullptr, K, L, tag) {} - + private: friend class ProgramPoint; static bool isKind(const ProgramPoint &location) { @@ -358,13 +358,13 @@ private: return k == PreLoadKind || k == PreStoreKind; } }; - + class PreLoad : public LocationCheck { public: PreLoad(const Stmt *S, const LocationContext *L, const ProgramPointTag *tag = nullptr) : LocationCheck(S, L, PreLoadKind, tag) {} - + private: friend class ProgramPoint; PreLoad() = default; @@ -378,7 +378,7 @@ public: PreStore(const Stmt *S, const LocationContext *L, const ProgramPointTag *tag = nullptr) : LocationCheck(S, L, PreStoreKind, tag) {} - + private: friend class ProgramPoint; PreStore() = default; @@ -405,7 +405,7 @@ private: class PostStore : public PostStmt { public: /// Construct the post store point. - /// \param Loc can be used to store the information about the location + /// \param Loc can be used to store the information about the location /// used in the form it was uttered in the code. PostStore(const Stmt *S, const LocationContext *L, const void *Loc, const ProgramPointTag *tag = nullptr) @@ -479,7 +479,7 @@ public: BlockEdge(const CFGBlock *B1, const CFGBlock *B2, const LocationContext *L) : ProgramPoint(B1, B2, BlockEdgeKind, L) { assert(B1 && "BlockEdge: source block must be non-null"); - assert(B2 && "BlockEdge: destination block must be non-null"); + assert(B2 && "BlockEdge: destination block must be non-null"); } const CFGBlock *getSrc() const { @@ -603,7 +603,7 @@ private: /// CallEnter uses the caller's location context. class CallEnter : public ProgramPoint { public: - CallEnter(const Stmt *stmt, const StackFrameContext *calleeCtx, + CallEnter(const Stmt *stmt, const StackFrameContext *calleeCtx, const LocationContext *callerCtx) : ProgramPoint(stmt, calleeCtx, CallEnterKind, callerCtx, nullptr) {} @@ -749,7 +749,7 @@ static bool isEqual(const clang::ProgramPoint &L, } }; - + template <> struct isPodLike<clang::ProgramPoint> { static const bool value = true; }; diff --git a/include/clang/Analysis/Support/BumpVector.h b/include/clang/Analysis/Support/BumpVector.h index 5940520855ef..00a7417e20f9 100644 --- a/include/clang/Analysis/Support/BumpVector.h +++ b/include/clang/Analysis/Support/BumpVector.h @@ -29,7 +29,7 @@ #include <type_traits> namespace clang { - + class BumpVectorContext { llvm::PointerIntPair<llvm::BumpPtrAllocator*, 1> Alloc; @@ -47,15 +47,15 @@ public: /// BumpPtrAllocator. This BumpPtrAllocator is not destroyed when the /// BumpVectorContext object is destroyed. BumpVectorContext(llvm::BumpPtrAllocator &A) : Alloc(&A, 0) {} - + ~BumpVectorContext() { if (Alloc.getInt()) delete Alloc.getPointer(); } - + llvm::BumpPtrAllocator &getAllocator() { return *Alloc.getPointer(); } }; - + template<typename T> class BumpVector { T *Begin = nullptr; @@ -67,34 +67,34 @@ public: explicit BumpVector(BumpVectorContext &C, unsigned N) { reserve(C, N); } - + ~BumpVector() { if (std::is_class<T>::value) { // Destroy the constructed elements in the vector. destroy_range(Begin, End); } } - + using size_type = size_t; using difference_type = ptrdiff_t; using value_type = T; using iterator = T *; using const_iterator = const T *; - + using const_reverse_iterator = std::reverse_iterator<const_iterator>; using reverse_iterator = std::reverse_iterator<iterator>; - + using reference = T &; using const_reference = const T &; using pointer = T *; using const_pointer = const T *; - + // forward iterator creation methods. iterator begin() { return Begin; } const_iterator begin() const { return Begin; } iterator end() { return End; } const_iterator end() const { return End; } - + // reverse iterator creation methods. reverse_iterator rbegin() { return reverse_iterator(end()); } const_reverse_iterator rbegin() const{ return const_reverse_iterator(end()); } @@ -102,7 +102,7 @@ public: const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } - + bool empty() const { return Begin == End; } size_type size() const { return End-Begin; } @@ -114,49 +114,49 @@ public: assert(Begin + idx < End); return Begin[idx]; } - + reference front() { return begin()[0]; } const_reference front() const { return begin()[0]; } - + reference back() { return end()[-1]; } const_reference back() const { return end()[-1]; } - + void pop_back() { --End; End->~T(); } - + T pop_back_val() { T Result = back(); pop_back(); return Result; } - + void clear() { if (std::is_class<T>::value) { destroy_range(Begin, End); } End = Begin; } - + /// data - Return a pointer to the vector's buffer, even if empty(). pointer data() { return pointer(Begin); } - + /// data - Return a pointer to the vector's buffer, even if empty(). const_pointer data() const { return const_pointer(Begin); } - + void push_back(const_reference Elt, BumpVectorContext &C) { if (End < Capacity) { Retry: @@ -165,7 +165,7 @@ public: return; } grow(C); - goto Retry; + goto Retry; } /// insert - Insert some number of copies of element into a position. Return @@ -193,18 +193,18 @@ public: /// capacity - Return the total number of elements in the currently allocated /// buffer. - size_t capacity() const { return Capacity - Begin; } - + size_t capacity() const { return Capacity - Begin; } + private: /// grow - double the size of the allocated memory, guaranteeing space for at /// least one more element or MinSize if specified. void grow(BumpVectorContext &C, size_type MinSize = 1); - + void construct_range(T *S, T *E, const T &Elt) { for (; S != E; ++S) new (S) T(Elt); } - + void destroy_range(T *S, T *E) { while (S != E) { --E; @@ -220,7 +220,7 @@ private: } } }; - + // Define this out-of-line to dissuade the C++ compiler from inlining it. template <typename T> void BumpVector<T>::grow(BumpVectorContext &C, size_t MinSize) { @@ -232,7 +232,7 @@ void BumpVector<T>::grow(BumpVectorContext &C, size_t MinSize) { // Allocate the memory from the BumpPtrAllocator. T *NewElts = C.getAllocator().template Allocate<T>(NewCapacity); - + // Copy the elements over. if (Begin != End) { if (std::is_class<T>::value) { diff --git a/include/clang/Basic/ABI.h b/include/clang/Basic/ABI.h index bd919ce24f81..dc0e49cded63 100644 --- a/include/clang/Basic/ABI.h +++ b/include/clang/Basic/ABI.h @@ -81,12 +81,12 @@ struct ReturnAdjustment { return memcmp(this, &RHS, sizeof(RHS)) < 0; } } Virtual; - + ReturnAdjustment() : NonVirtual(0) {} - + bool isEmpty() const { return !NonVirtual && Virtual.isEmpty(); } - friend bool operator==(const ReturnAdjustment &LHS, + friend bool operator==(const ReturnAdjustment &LHS, const ReturnAdjustment &RHS) { return LHS.NonVirtual == RHS.NonVirtual && LHS.Virtual.Equals(RHS.Virtual); } @@ -103,7 +103,7 @@ struct ReturnAdjustment { return LHS.NonVirtual == RHS.NonVirtual && LHS.Virtual.Less(RHS.Virtual); } }; - + /// A \c this pointer adjustment. struct ThisAdjustment { /// The non-virtual adjustment from the derived object to its @@ -149,12 +149,12 @@ struct ThisAdjustment { return memcmp(this, &RHS, sizeof(RHS)) < 0; } } Virtual; - + ThisAdjustment() : NonVirtual(0) { } bool isEmpty() const { return !NonVirtual && Virtual.isEmpty(); } - friend bool operator==(const ThisAdjustment &LHS, + friend bool operator==(const ThisAdjustment &LHS, const ThisAdjustment &RHS) { return LHS.NonVirtual == RHS.NonVirtual && LHS.Virtual.Equals(RHS.Virtual); } @@ -162,12 +162,12 @@ struct ThisAdjustment { friend bool operator!=(const ThisAdjustment &LHS, const ThisAdjustment &RHS) { return !(LHS == RHS); } - + friend bool operator<(const ThisAdjustment &LHS, const ThisAdjustment &RHS) { if (LHS.NonVirtual < RHS.NonVirtual) return true; - + return LHS.NonVirtual == RHS.NonVirtual && LHS.Virtual.Less(RHS.Virtual); } }; @@ -179,7 +179,7 @@ class CXXMethodDecl; struct ThunkInfo { /// The \c this pointer adjustment. ThisAdjustment This; - + /// The return adjustment. ReturnAdjustment Return; @@ -204,7 +204,7 @@ struct ThunkInfo { bool isEmpty() const { return This.isEmpty() && Return.isEmpty() && Method == nullptr; } -}; +}; } // end namespace clang diff --git a/include/clang/Basic/AllDiagnostics.h b/include/clang/Basic/AllDiagnostics.h index 20c29d459d22..afec2d7e0f2f 100644 --- a/include/clang/Basic/AllDiagnostics.h +++ b/include/clang/Basic/AllDiagnostics.h @@ -34,9 +34,9 @@ class StringSizerHelper { public: enum { Size = SizeOfStr }; }; -} // end namespace clang +} // end namespace clang #define STR_SIZE(str, fieldTy) clang::StringSizerHelper<sizeof(str)-1, \ - fieldTy>::Size + fieldTy>::Size #endif diff --git a/include/clang/Basic/Attr.td b/include/clang/Basic/Attr.td index 0bbe52bf5f36..fea8e129d7da 100644 --- a/include/clang/Basic/Attr.td +++ b/include/clang/Basic/Attr.td @@ -141,6 +141,13 @@ def HasFunctionProto : SubsetSubject<DeclBase, isa<BlockDecl>(S)}], "non-K&R-style functions">; +// A subject that matches the implicit object parameter of a non-static member +// function. Accepted as a function type attribute on the type of such a +// member function. +// FIXME: This does not actually ever match currently. +def ImplicitObjectParameter : SubsetSubject<Function, [{false}], + "implicit object parameters">; + // A single argument to an attribute class Argument<string name, bit optional, bit fake = 0> { string Name = name; @@ -456,7 +463,7 @@ class Attr { // Set to true if all of the attribute's arguments should be parsed in an // unevaluated context. bit ParseArgumentsAsUnevaluated = 0; - // Set to true if this attribute meaningful when applied to or inherited + // Set to true if this attribute meaningful when applied to or inherited // in a class template definition. bit MeaningfulToClassTemplateDefinition = 0; // Set to true if this attribute can be used with '#pragma clang attribute'. @@ -583,7 +590,7 @@ def AlignValue : Attr { // the future (and a corresponding C++ attribute), but this can be done // later once we decide if we also want them to have slightly-different // semantics than Intel's align_value. - // + // // Does not get a [[]] spelling because the attribute is not exposed as such // by Intel. GNU<"align_value"> @@ -1211,6 +1218,13 @@ def LayoutVersion : InheritableAttr, TargetSpecificAttr<TargetMicrosoftCXXABI> { let Documentation = [LayoutVersionDocs]; } +def LifetimeBound : InheritableAttr { + let Spellings = [Clang<"lifetimebound", 0>]; + let Subjects = SubjectList<[ParmVar, ImplicitObjectParameter], ErrorDiag>; + let Documentation = [LifetimeBoundDocs]; + let LangOpts = [CPlusPlus]; +} + def TrivialABI : InheritableAttr { // This attribute does not have a C [[]] spelling because it requires the // CPlusPlus language option. @@ -1703,7 +1717,7 @@ def Overloadable : Attr { let Documentation = [OverloadableDocs]; } -def Override : InheritableAttr { +def Override : InheritableAttr { let Spellings = [Keyword<"override">]; let SemaHandler = 0; let Documentation = [Undocumented]; @@ -1782,7 +1796,7 @@ def RequireConstantInit : InheritableAttr { def WorkGroupSizeHint : InheritableAttr { // Does not have a [[]] spelling because it is an OpenCL-related attribute. let Spellings = [GNU<"work_group_size_hint">]; - let Args = [UnsignedArgument<"XDim">, + let Args = [UnsignedArgument<"XDim">, UnsignedArgument<"YDim">, UnsignedArgument<"ZDim">]; let Subjects = SubjectList<[Function], ErrorDiag>; diff --git a/include/clang/Basic/AttrDocs.td b/include/clang/Basic/AttrDocs.td index 5a5ab78b49d1..bb2993eab4bc 100644 --- a/include/clang/Basic/AttrDocs.td +++ b/include/clang/Basic/AttrDocs.td @@ -2362,6 +2362,22 @@ It is only supported when using the Microsoft C++ ABI. }]; } +def LifetimeBoundDocs : Documentation { + let Category = DocCatFunction; + let Content = [{ +The ``lifetimebound`` attribute indicates that a resource owned by +a function parameter or implicit object parameter +is retained by the return value of the annotated function +(or, for a parameter of a constructor, in the value of the constructed object). +It is only supported in C++. + +This attribute provides an experimental implementation of the facility +described in the C++ committee paper [http://wg21.link/p0936r0](P0936R0), +and is subject to change as the design of the corresponding functionality +changes. + }]; +} + def TrivialABIDocs : Documentation { let Category = DocCatVariable; let Content = [{ diff --git a/include/clang/Basic/Builtins.def b/include/clang/Basic/Builtins.def index edd823754a37..c4d11cd827c1 100644 --- a/include/clang/Basic/Builtins.def +++ b/include/clang/Basic/Builtins.def @@ -471,6 +471,8 @@ BUILTIN(__builtin_wcslen, "zwC*", "nF") BUILTIN(__builtin_wcsncmp, "iwC*wC*z", "nF") BUILTIN(__builtin_wmemchr, "w*wC*wz", "nF") BUILTIN(__builtin_wmemcmp, "iwC*wC*z", "nF") +BUILTIN(__builtin_wmemcpy, "w*w*wC*z", "nF") +BUILTIN(__builtin_wmemmove, "w*w*wC*z", "nF") BUILTIN(__builtin_return_address, "v*IUi", "n") BUILTIN(__builtin_extract_return_addr, "v*v*", "n") BUILTIN(__builtin_frame_address, "v*IUi", "n") @@ -908,6 +910,8 @@ LIBBUILTIN(wcslen, "zwC*", "f", "wchar.h", ALL_LANGUAGES) LIBBUILTIN(wcsncmp, "iwC*wC*z", "f", "wchar.h", ALL_LANGUAGES) LIBBUILTIN(wmemchr, "w*wC*wz", "f", "wchar.h", ALL_LANGUAGES) LIBBUILTIN(wmemcmp, "iwC*wC*z", "f", "wchar.h", ALL_LANGUAGES) +LIBBUILTIN(wmemcpy, "w*w*wC*z", "f", "wchar.h", ALL_LANGUAGES) +LIBBUILTIN(wmemmove,"w*w*wC*z", "f", "wchar.h", ALL_LANGUAGES) // C99 // In some systems setjmp is a macro that expands to _setjmp. We undefine @@ -956,7 +960,7 @@ LIBBUILTIN(strlcpy, "zc*cC*z", "f", "string.h", ALL_GNU_LANGUAGES) LIBBUILTIN(strlcat, "zc*cC*z", "f", "string.h", ALL_GNU_LANGUAGES) // id objc_msgSend(id, SEL, ...) LIBBUILTIN(objc_msgSend, "GGH.", "f", "objc/message.h", OBJC_LANG) -// long double objc_msgSend_fpret(id self, SEL op, ...) +// long double objc_msgSend_fpret(id self, SEL op, ...) LIBBUILTIN(objc_msgSend_fpret, "LdGH.", "f", "objc/message.h", OBJC_LANG) // _Complex long double objc_msgSend_fp2ret(id self, SEL op, ...) LIBBUILTIN(objc_msgSend_fp2ret, "XLdGH.", "f", "objc/message.h", OBJC_LANG) diff --git a/include/clang/Basic/BuiltinsAMDGPU.def b/include/clang/Basic/BuiltinsAMDGPU.def index 46cd738ae43f..4a447eb9f6a8 100644 --- a/include/clang/Basic/BuiltinsAMDGPU.def +++ b/include/clang/Basic/BuiltinsAMDGPU.def @@ -124,13 +124,13 @@ TARGET_BUILTIN(__builtin_amdgcn_fmed3h, "hhhh", "nc", "gfx9-insts") // Deep learning builtins. //===----------------------------------------------------------------------===// -TARGET_BUILTIN(__builtin_amdgcn_fdot2, "fV2hV2hf", "nc", "dl-insts") -TARGET_BUILTIN(__builtin_amdgcn_sdot2, "SiV2SsV2SsSi", "nc", "dl-insts") -TARGET_BUILTIN(__builtin_amdgcn_udot2, "UiV2UsV2UsUi", "nc", "dl-insts") -TARGET_BUILTIN(__builtin_amdgcn_sdot4, "SiSiSiSi", "nc", "dl-insts") -TARGET_BUILTIN(__builtin_amdgcn_udot4, "UiUiUiUi", "nc", "dl-insts") -TARGET_BUILTIN(__builtin_amdgcn_sdot8, "SiSiSiSi", "nc", "dl-insts") -TARGET_BUILTIN(__builtin_amdgcn_udot8, "UiUiUiUi", "nc", "dl-insts") +TARGET_BUILTIN(__builtin_amdgcn_fdot2, "fV2hV2hfIb", "nc", "dl-insts") +TARGET_BUILTIN(__builtin_amdgcn_sdot2, "SiV2SsV2SsSiIb", "nc", "dl-insts") +TARGET_BUILTIN(__builtin_amdgcn_udot2, "UiV2UsV2UsUiIb", "nc", "dl-insts") +TARGET_BUILTIN(__builtin_amdgcn_sdot4, "SiSiSiSiIb", "nc", "dl-insts") +TARGET_BUILTIN(__builtin_amdgcn_udot4, "UiUiUiUiIb", "nc", "dl-insts") +TARGET_BUILTIN(__builtin_amdgcn_sdot8, "SiSiSiSiIb", "nc", "dl-insts") +TARGET_BUILTIN(__builtin_amdgcn_udot8, "UiUiUiUiIb", "nc", "dl-insts") //===----------------------------------------------------------------------===// // Special builtins. diff --git a/include/clang/Basic/BuiltinsPPC.def b/include/clang/Basic/BuiltinsPPC.def index 8cd8a2be2003..9be760853d50 100644 --- a/include/clang/Basic/BuiltinsPPC.def +++ b/include/clang/Basic/BuiltinsPPC.def @@ -58,7 +58,7 @@ BUILTIN(__builtin_altivec_vctuxs, "V4UiV4fIi", "") BUILTIN(__builtin_altivec_dss, "vUi", "") BUILTIN(__builtin_altivec_dssall, "v", "") -BUILTIN(__builtin_altivec_dst, "vvC*iUi", "") +BUILTIN(__builtin_altivec_dst, "vvC*iUi", "") BUILTIN(__builtin_altivec_dstt, "vvC*iUi", "") BUILTIN(__builtin_altivec_dstst, "vvC*iUi", "") BUILTIN(__builtin_altivec_dststt, "vvC*iUi", "") diff --git a/include/clang/Basic/Diagnostic.h b/include/clang/Basic/Diagnostic.h index 5205b4c210a6..d30ac14e02fe 100644 --- a/include/clang/Basic/Diagnostic.h +++ b/include/clang/Basic/Diagnostic.h @@ -25,7 +25,7 @@ #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/iterator_range.h" -#include "llvm/Support/Compiler.h" +#include "llvm/Support/Compiler.h" #include <cassert> #include <cstdint> #include <limits> @@ -86,7 +86,7 @@ public: bool isNull() const { return !RemoveRange.isValid(); } - + /// Create a code modification hint that inserts the given /// code string at a specific location. static FixItHint CreateInsertion(SourceLocation InsertionLoc, @@ -99,7 +99,7 @@ public: Hint.BeforePreviousInsertions = BeforePreviousInsertions; return Hint; } - + /// Create a code modification hint that inserts the given /// code from \p FromRange at a specific location. static FixItHint CreateInsertionFromRange(SourceLocation InsertionLoc, @@ -123,7 +123,7 @@ public: static FixItHint CreateRemoval(SourceRange RemoveRange) { return CreateRemoval(CharSourceRange::getTokenRange(RemoveRange)); } - + /// Create a code modification hint that replaces the given /// source range with the given code string. static FixItHint CreateReplacement(CharSourceRange RemoveRange, @@ -133,7 +133,7 @@ public: Hint.CodeToInsert = Code; return Hint; } - + static FixItHint CreateReplacement(SourceRange RemoveRange, StringRef Code) { return CreateReplacement(CharSourceRange::getTokenRange(RemoveRange), Code); @@ -348,7 +348,7 @@ private: unsigned Offset; DiagStatePoint(DiagState *State, unsigned Offset) - : State(State), Offset(Offset) {} + : State(State), Offset(Offset) {} }; /// Description of the diagnostic states and state transitions for a @@ -420,7 +420,7 @@ private: /// Indicates that an unrecoverable error has occurred. bool UnrecoverableErrorOccurred; - + /// Counts for DiagnosticErrorTrap to check whether an error occurred /// during a parsing section, e.g. during parsing a function. unsigned TrapNumErrorsOccurred; @@ -556,7 +556,7 @@ public: /// /// Zero disables the limit. void setErrorLimit(unsigned Limit) { ErrorLimit = Limit; } - + /// Specify the maximum number of template instantiation /// notes to emit along with a given diagnostic. void setTemplateBacktraceLimit(unsigned Limit) { @@ -626,11 +626,11 @@ public: return GetCurDiagState()->SuppressSystemWarnings; } - /// Suppress all diagnostics, to silence the front end when we + /// Suppress all diagnostics, to silence the front end when we /// know that we don't want any more diagnostics to be passed along to the /// client - void setSuppressAllDiagnostics(bool Val = true) { - SuppressAllDiagnostics = Val; + void setSuppressAllDiagnostics(bool Val = true) { + SuppressAllDiagnostics = Val; } bool getSuppressAllDiagnostics() const { return SuppressAllDiagnostics; } @@ -638,12 +638,12 @@ public: /// template types. void setElideType(bool Val = true) { ElideType = Val; } bool getElideType() { return ElideType; } - + /// Set tree printing, to outputting the template difference in a /// tree format. void setPrintTemplateTree(bool Val = false) { PrintTemplateTree = Val; } bool getPrintTemplateTree() { return PrintTemplateTree; } - + /// Set color printing, so the type diffing will inject color markers /// into the output. void setShowColors(bool Val = false) { ShowColors = Val; } @@ -657,7 +657,7 @@ public: ShowOverloads = Val; } OverloadsShown getShowOverloads() const { return ShowOverloads; } - + /// Pretend that the last diagnostic issued was ignored, so any /// subsequent notes will be suppressed, or restore a prior ignoring /// state after ignoring some diagnostics and their notes, possibly in @@ -751,12 +751,12 @@ public: return UncompilableErrorOccurred; } bool hasFatalErrorOccurred() const { return FatalErrorOccurred; } - + /// Determine whether any kind of unrecoverable error has occurred. bool hasUnrecoverableErrorOccurred() const { return FatalErrorOccurred || UnrecoverableErrorOccurred; } - + unsigned getNumWarnings() const { return NumWarnings; } void setNumWarnings(unsigned NumWarnings) { @@ -799,10 +799,10 @@ public: LastDiagLevel = Other.LastDiagLevel; } - /// Reset the state of the diagnostic object to its initial + /// Reset the state of the diagnostic object to its initial /// configuration. void Reset(); - + //===--------------------------------------------------------------------===// // DiagnosticsEngine classification and reporting interfaces. // @@ -875,7 +875,7 @@ public: /// DiagnosticsEngine object itself. void SetDelayedDiagnostic(unsigned DiagID, StringRef Arg1 = "", StringRef Arg2 = ""); - + /// Clear out the current diagnostic. void Clear() { CurDiagID = std::numeric_limits<unsigned>::max(); } @@ -894,7 +894,7 @@ private: friend class DiagnosticErrorTrap; friend class DiagnosticIDs; friend class PartialDiagnostic; - + /// Report the delayed diagnostic. void ReportDelayed(); @@ -1042,7 +1042,7 @@ public: class DiagnosticBuilder { friend class DiagnosticsEngine; friend class PartialDiagnostic; - + mutable DiagnosticsEngine *DiagObj = nullptr; mutable unsigned NumArgs = 0; @@ -1105,7 +1105,7 @@ protected: return Result; } - + public: /// Copy constructor. When copied, this "takes" the diagnostic info from the /// input and neuters it. @@ -1430,8 +1430,8 @@ public: }; /** - * Represents a diagnostic in a form that can be retained until its - * corresponding source manager is destroyed. + * Represents a diagnostic in a form that can be retained until its + * corresponding source manager is destroyed. */ class StoredDiagnostic { unsigned ID; @@ -1444,9 +1444,9 @@ class StoredDiagnostic { public: StoredDiagnostic() = default; StoredDiagnostic(DiagnosticsEngine::Level Level, const Diagnostic &Info); - StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID, + StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID, StringRef Message); - StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID, + StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID, StringRef Message, FullSourceLoc Loc, ArrayRef<CharSourceRange> Ranges, ArrayRef<FixItHint> Fixits); @@ -1466,7 +1466,7 @@ public: range_iterator range_begin() const { return Ranges.begin(); } range_iterator range_end() const { return Ranges.end(); } unsigned range_size() const { return Ranges.size(); } - + ArrayRef<CharSourceRange> getRanges() const { return llvm::makeArrayRef(Ranges); } @@ -1476,7 +1476,7 @@ public: fixit_iterator fixit_begin() const { return FixIts.begin(); } fixit_iterator fixit_end() const { return FixIts.end(); } unsigned fixit_size() const { return FixIts.size(); } - + ArrayRef<FixItHint> getFixIts() const { return llvm::makeArrayRef(FixIts); } @@ -1488,7 +1488,7 @@ class DiagnosticConsumer { protected: unsigned NumWarnings = 0; ///< Number of warnings reported unsigned NumErrors = 0; ///< Number of errors reported - + public: DiagnosticConsumer() = default; virtual ~DiagnosticConsumer(); @@ -1506,7 +1506,7 @@ public: /// in between BeginSourceFile() and EndSourceFile(). /// /// \param LangOpts The language options for the source file being processed. - /// \param PP The preprocessor object being used for the source; this is + /// \param PP The preprocessor object being used for the source; this is /// optional, e.g., it may not be present when processing AST source files. virtual void BeginSourceFile(const LangOptions &LangOpts, const Preprocessor *PP = nullptr) {} diff --git a/include/clang/Basic/DiagnosticASTKinds.td b/include/clang/Basic/DiagnosticASTKinds.td index 4fa1db96cb89..3358fc3d70c7 100644 --- a/include/clang/Basic/DiagnosticASTKinds.td +++ b/include/clang/Basic/DiagnosticASTKinds.td @@ -163,12 +163,26 @@ def note_constexpr_unsupported_unsized_array : Note< def note_constexpr_unsized_array_indexed : Note< "indexing of array without known bound is not allowed " "in a constant expression">; +def note_constexpr_memcpy_type_pun : Note< + "cannot constant evaluate '%select{memcpy|memmove}0' from object of " + "type %1 to object of type %2">; +def note_constexpr_memcpy_nontrivial : Note< + "cannot constant evaluate '%select{memcpy|memmove}0' between objects of " + "non-trivially-copyable type %1">; +def note_constexpr_memcpy_overlap : Note< + "'%select{memcpy|wmemcpy}0' between overlapping memory regions">; +def note_constexpr_memcpy_unsupported : Note< + "'%select{%select{memcpy|wmemcpy}1|%select{memmove|wmemmove}1}0' " + "not supported: %select{" + "size to copy (%4) is not a multiple of size of element type %3 (%5)|" + "source is not a contiguous array of at least %4 elements of type %3|" + "destination is not a contiguous array of at least %4 elements of type %3}2">; def warn_integer_constant_overflow : Warning< "overflow in expression; result is %0 with type %1">, InGroup<DiagGroup<"integer-overflow">>; -// This is a temporary diagnostic, and shall be removed once our +// This is a temporary diagnostic, and shall be removed once our // implementation is complete, and like the preceding constexpr notes belongs // in Sema. def note_unimplemented_constexpr_lambda_feature_ast : Note< diff --git a/include/clang/Basic/DiagnosticCommentKinds.td b/include/clang/Basic/DiagnosticCommentKinds.td index ab24582c1180..ebe62e4738f0 100644 --- a/include/clang/Basic/DiagnosticCommentKinds.td +++ b/include/clang/Basic/DiagnosticCommentKinds.td @@ -83,19 +83,19 @@ def warn_doc_function_method_decl_mismatch : Warning< "%select{a function|a function|an Objective-C method|an Objective-C method|" "a pointer to function}2 declaration">, InGroup<Documentation>, DefaultIgnore; - + def warn_doc_api_container_decl_mismatch : Warning< "'%select{\\|@}0%select{class|interface|protocol|struct|union}1' " "command should not be used in a comment attached to a " "non-%select{class|interface|protocol|struct|union}2 declaration">, InGroup<Documentation>, DefaultIgnore; - + def warn_doc_container_decl_mismatch : Warning< "'%select{\\|@}0%select{classdesign|coclass|dependency|helper" "|helperclass|helps|instancesize|ownership|performance|security|superclass}1' " "command should not be used in a comment attached to a non-container declaration">, InGroup<Documentation>, DefaultIgnore; - + def warn_doc_param_duplicate : Warning< "parameter '%0' is already documented">, InGroup<Documentation>, DefaultIgnore; diff --git a/include/clang/Basic/DiagnosticCommonKinds.td b/include/clang/Basic/DiagnosticCommonKinds.td index 61a73541d0b3..b98b183c9d6f 100644 --- a/include/clang/Basic/DiagnosticCommonKinds.td +++ b/include/clang/Basic/DiagnosticCommonKinds.td @@ -16,7 +16,7 @@ let Component = "Common" in { // Basic. def fatal_too_many_errors - : Error<"too many errors emitted, stopping now">, DefaultFatal; + : Error<"too many errors emitted, stopping now">, DefaultFatal; def note_declared_at : Note<"declared here">; def note_previous_definition : Note<"previous definition is here">; @@ -97,11 +97,11 @@ def remark_module_lock_timeout : Remark< def err_module_shadowed : Error<"import of shadowed module '%0'">, DefaultFatal; def err_module_build_shadowed_submodule : Error< "build a shadowed submodule '%0'">, DefaultFatal; -def err_module_cycle : Error<"cyclic dependency in module '%0': %1">, +def err_module_cycle : Error<"cyclic dependency in module '%0': %1">, DefaultFatal; def err_module_prebuilt : Error< "error in loading module '%0' from prebuilt module path">, DefaultFatal; -def note_pragma_entered_here : Note<"#pragma entered here">; +def note_pragma_entered_here : Note<"#pragma entered here">; def note_decl_hiding_tag_type : Note< "%1 %0 is hidden by a non-type declaration of %0 here">; def err_attribute_not_type_attr : Error< @@ -115,7 +115,7 @@ let CategoryName = "Nullability Issue" in { def warn_nullability_duplicate : Warning< "duplicate nullability specifier %0">, InGroup<Nullability>; - + def warn_conflicting_nullability_attr_overriding_ret_types : Warning< "conflicting nullability specifier on return types, %0 " "conflicts with existing specifier %1">, @@ -223,7 +223,7 @@ def err_unable_to_rename_temp : Error< "unable to rename temporary '%0' to output file '%1': '%2'">; def err_unable_to_make_temp : Error< "unable to make temporary file: %0">; - + // Modules def err_module_format_unhandled : Error< "no handler registered for module format '%0'">, DefaultFatal; diff --git a/include/clang/Basic/DiagnosticDriverKinds.td b/include/clang/Basic/DiagnosticDriverKinds.td index a6be0595e1ae..7f75f45c6578 100644 --- a/include/clang/Basic/DiagnosticDriverKinds.td +++ b/include/clang/Basic/DiagnosticDriverKinds.td @@ -208,7 +208,7 @@ def err_drv_omp_host_target_not_supported : Error< def err_drv_expecting_fopenmp_with_fopenmp_targets : Error< "The option -fopenmp-targets must be used in conjunction with a -fopenmp option compatible with offloading, please use -fopenmp=libomp or -fopenmp=libiomp5.">; def warn_drv_omp_offload_target_duplicate : Warning< - "The OpenMP offloading target '%0' is similar to target '%1' already specified - will be ignored.">, + "The OpenMP offloading target '%0' is similar to target '%1' already specified - will be ignored.">, InGroup<OpenMPTarget>; def warn_drv_omp_offload_target_missingbcruntime : Warning< "No library '%0' found in the default clang lib directory or in LIBRARY_PATH. Expect degraded performance due to no inlining of runtime functions on target devices.">, @@ -226,6 +226,9 @@ def warn_ignored_clang_option : Warning<"the flag '%0' has been deprecated and w def warn_drv_unsupported_opt_for_target : Warning< "optimization flag '%0' is not supported for target '%1'">, InGroup<IgnoredOptimizationArgument>; +def warn_drv_unsupported_debug_info_opt_for_target : Warning< + "debug information option '%0' is not supported for target '%1'">, + InGroup<UnsupportedTargetOpt>; def warn_c_kext : Warning< "ignoring -fapple-kext which is valid for C++ and Objective-C++ only">; def warn_drv_input_file_unused : Warning< diff --git a/include/clang/Basic/DiagnosticFrontendKinds.td b/include/clang/Basic/DiagnosticFrontendKinds.td index 6add448871fe..66287933b7ca 100644 --- a/include/clang/Basic/DiagnosticFrontendKinds.td +++ b/include/clang/Basic/DiagnosticFrontendKinds.td @@ -36,7 +36,7 @@ def remark_fe_backend_plugin: Remark<"%0">, BackendInfo, InGroup<RemarkBackendPl def note_fe_backend_plugin: Note<"%0">, BackendInfo; def warn_fe_override_module : Warning< - "overriding the module target triple with %0">, + "overriding the module target triple with %0">, InGroup<DiagGroup<"override-module">>; def remark_fe_backend_optimization_remark : Remark<"%0">, BackendInfo, @@ -190,10 +190,10 @@ def err_module_interface_requires_modules_ts : Error< def warn_module_config_mismatch : Warning< "module file %0 cannot be loaded due to a configuration mismatch with the current " "compilation">, InGroup<DiagGroup<"module-file-config-mismatch">>, DefaultError; -def err_module_map_not_found : Error<"module map file '%0' not found">, +def err_module_map_not_found : Error<"module map file '%0' not found">, DefaultFatal; def err_missing_module_name : Error< - "no module name provided; specify one with -fmodule-name=">, + "no module name provided; specify one with -fmodule-name=">, DefaultFatal; def err_missing_module : Error< "no module named '%0' declared in module map file '%1'">, DefaultFatal; diff --git a/include/clang/Basic/DiagnosticGroups.td b/include/clang/Basic/DiagnosticGroups.td index 7087db7f0fb8..2156ef93c19f 100644 --- a/include/clang/Basic/DiagnosticGroups.td +++ b/include/clang/Basic/DiagnosticGroups.td @@ -72,6 +72,7 @@ def UnsupportedNan : DiagGroup<"unsupported-nan">; def UnsupportedAbs : DiagGroup<"unsupported-abs">; def UnsupportedCB : DiagGroup<"unsupported-cb">; def UnsupportedGPOpt : DiagGroup<"unsupported-gpopt">; +def UnsupportedTargetOpt : DiagGroup<"unsupported-target-opt">; def NonLiteralNullConversion : DiagGroup<"non-literal-null-conversion">; def NullConversion : DiagGroup<"null-conversion">; def ImplicitConversionFloatingPointToBool : @@ -287,7 +288,7 @@ def IgnoredQualifiers : DiagGroup<"ignored-qualifiers">; def : DiagGroup<"import">; def GNUIncludeNext : DiagGroup<"gnu-include-next">; def IncompatibleMSStruct : DiagGroup<"incompatible-ms-struct">; -def IncompatiblePointerTypesDiscardsQualifiers +def IncompatiblePointerTypesDiscardsQualifiers : DiagGroup<"incompatible-pointer-types-discards-qualifiers">; def IncompatibleFunctionPointerTypes : DiagGroup<"incompatible-function-pointer-types">; @@ -799,14 +800,14 @@ def Most : DiagGroup<"most", [ UserDefinedWarnings ]>; -// Thread Safety warnings +// Thread Safety warnings def ThreadSafetyAttributes : DiagGroup<"thread-safety-attributes">; def ThreadSafetyAnalysis : DiagGroup<"thread-safety-analysis">; def ThreadSafetyPrecise : DiagGroup<"thread-safety-precise">; def ThreadSafetyReference : DiagGroup<"thread-safety-reference">; def ThreadSafetyNegative : DiagGroup<"thread-safety-negative">; def ThreadSafety : DiagGroup<"thread-safety", - [ThreadSafetyAttributes, + [ThreadSafetyAttributes, ThreadSafetyAnalysis, ThreadSafetyPrecise, ThreadSafetyReference]>; diff --git a/include/clang/Basic/DiagnosticIDs.h b/include/clang/Basic/DiagnosticIDs.h index b610af953fba..983dcb21cfdf 100644 --- a/include/clang/Basic/DiagnosticIDs.h +++ b/include/clang/Basic/DiagnosticIDs.h @@ -214,7 +214,7 @@ public: bool ignored; return isBuiltinExtensionDiag(DiagID, ignored); } - + /// Determine whether the given built-in diagnostic ID is for an /// extension of some sort, and whether it is enabled by default. /// @@ -223,14 +223,14 @@ public: /// treated as a warning/error by default. /// static bool isBuiltinExtensionDiag(unsigned DiagID, bool &EnabledByDefault); - + /// Return the lowest-level warning option that enables the specified /// diagnostic. /// /// If there is no -Wfoo flag that controls the diagnostic, this returns null. static StringRef getWarningOptionForDiag(unsigned DiagID); - + /// Return the category number that a specified \p DiagID belongs to, /// or 0 if no category. static unsigned getCategoryNumberForDiag(unsigned DiagID); @@ -240,7 +240,7 @@ public: /// Given a category ID, return the name of the category. static StringRef getCategoryNameFromID(unsigned CategoryID); - + /// Return true if a given diagnostic falls into an ARC diagnostic /// category. static bool isARCDiagnostic(unsigned DiagID); @@ -251,26 +251,26 @@ public: /// The diagnostic should not be reported, but it should cause /// template argument deduction to fail. /// - /// The vast majority of errors that occur during template argument + /// The vast majority of errors that occur during template argument /// deduction fall into this category. SFINAE_SubstitutionFailure, - + /// The diagnostic should be suppressed entirely. /// /// Warnings generally fall into this category. SFINAE_Suppress, - + /// The diagnostic should be reported. /// - /// The diagnostic should be reported. Various fatal errors (e.g., + /// The diagnostic should be reported. Various fatal errors (e.g., /// template instantiation depth exceeded) fall into this category. SFINAE_Report, - + /// The diagnostic is an access-control diagnostic, which will be /// substitution failures in some contexts and reported in others. SFINAE_AccessControl }; - + /// Determines whether the given built-in diagnostic ID is /// for an error that is suppressed if it occurs during C++ template /// argument deduction. @@ -306,7 +306,7 @@ public: private: /// Classify the specified diagnostic ID into a Level, consumable by /// the DiagnosticClient. - /// + /// /// The classification is based on the way the client configured the /// DiagnosticsEngine object. /// diff --git a/include/clang/Basic/DiagnosticLexKinds.td b/include/clang/Basic/DiagnosticLexKinds.td index b5b5e8f654bc..1c960711bccb 100644 --- a/include/clang/Basic/DiagnosticLexKinds.td +++ b/include/clang/Basic/DiagnosticLexKinds.td @@ -53,7 +53,7 @@ def ext_multi_line_line_comment : Extension<"multi-line // comment">, def ext_line_comment : Extension< "// comments are not allowed in this language">, InGroup<Comment>; -def ext_no_newline_eof : Extension<"no newline at end of file">, +def ext_no_newline_eof : Extension<"no newline at end of file">, InGroup<NewlineEOF>; def warn_no_newline_eof : Warning<"no newline at end of file">, InGroup<NewlineEOF>, DefaultIgnore; @@ -294,7 +294,7 @@ def pp_nonportable_path : NonportablePath, InGroup<DiagGroup<"nonportable-include-path">>; def pp_nonportable_system_path : NonportablePath, DefaultIgnore, InGroup<DiagGroup<"nonportable-system-include-path">>; - + def pp_pragma_once_in_main_file : Warning<"#pragma once in main file">, InGroup<DiagGroup<"pragma-once-outside-header">>; def pp_pragma_sysheader_in_main_file : Warning< @@ -353,7 +353,7 @@ def ext_pp_warning_directive : Extension<"#warning is a language extension">; def ext_pp_extra_tokens_at_eol : ExtWarn< "extra tokens at end of #%0 directive">, InGroup<ExtraTokens>; - + def ext_pp_comma_expr : Extension<"comma operator in operand of #if">; def ext_pp_bad_vaargs_use : Extension< "__VA_ARGS__ can only appear in the expansion of a C99 variadic macro">; @@ -594,7 +594,7 @@ def err_pp_illegal_floating_literal : Error< def err_pp_line_requires_integer : Error< "#line directive requires a positive integer argument">; def ext_pp_line_zero : Extension< - "#line directive with zero argument is a GNU extension">, + "#line directive with zero argument is a GNU extension">, InGroup<GNUZeroLineDirective>; def err_pp_line_invalid_filename : Error< "invalid filename for #line directive">; @@ -736,7 +736,7 @@ def warn_auto_module_import : Warning< def note_implicit_top_level_module_import_here : Note< "submodule of top-level module '%0' implicitly imported here">; def warn_uncovered_module_header : Warning< - "umbrella header for module '%0' does not include header '%1'">, + "umbrella header for module '%0' does not include header '%1'">, InGroup<IncompleteUmbrella>; def warn_mmap_umbrella_dir_not_found : Warning< "umbrella directory '%0' not found">, @@ -755,7 +755,7 @@ def warn_non_modular_include_in_module : Warning< "include of non-modular header inside module '%0': '%1'">, InGroup<NonModularIncludeInModule>, DefaultIgnore; def warn_module_conflict : Warning< - "module '%0' conflicts with already-imported module '%1': %2">, + "module '%0' conflicts with already-imported module '%1': %2">, InGroup<ModuleConflict>; def warn_header_guard : Warning< diff --git a/include/clang/Basic/DiagnosticOptions.def b/include/clang/Basic/DiagnosticOptions.def index 2467b24fd909..22645654afd8 100644 --- a/include/clang/Basic/DiagnosticOptions.def +++ b/include/clang/Basic/DiagnosticOptions.def @@ -61,9 +61,9 @@ DIAGOPT(ShowOptionNames, 1, 0) /// Show the option name for mappable DIAGOPT(ShowNoteIncludeStack, 1, 0) /// Show include stacks for notes. VALUE_DIAGOPT(ShowCategories, 2, 0) /// Show categories: 0 -> none, 1 -> Number, /// 2 -> Full Name. - -ENUM_DIAGOPT(Format, TextDiagnosticFormat, 2, Clang) /// Format for diagnostics: - + +ENUM_DIAGOPT(Format, TextDiagnosticFormat, 2, Clang) /// Format for diagnostics: + DIAGOPT(ShowColors, 1, 0) /// Show diagnostics with ANSI color sequences. ENUM_DIAGOPT(ShowOverloads, OverloadsShown, 1, Ovl_All) /// Overload candidates to show. diff --git a/include/clang/Basic/DiagnosticOptions.h b/include/clang/Basic/DiagnosticOptions.h index 391e252eaddd..4c5bcb4e8793 100644 --- a/include/clang/Basic/DiagnosticOptions.h +++ b/include/clang/Basic/DiagnosticOptions.h @@ -91,7 +91,7 @@ protected: public: /// The file to log diagnostic output to. std::string DiagnosticLogFile; - + /// The file to serialize diagnostics to (non-appending). std::string DiagnosticSerializationFile; diff --git a/include/clang/Basic/DiagnosticParseKinds.td b/include/clang/Basic/DiagnosticParseKinds.td index dd4c81922592..609dca4f075c 100644 --- a/include/clang/Basic/DiagnosticParseKinds.td +++ b/include/clang/Basic/DiagnosticParseKinds.td @@ -86,7 +86,7 @@ def err_enumerator_list_missing_comma : Error< def err_enumerator_unnamed_no_def : Error< "unnamed enumeration must be a definition">; def ext_cxx11_enum_fixed_underlying_type : Extension< - "enumeration types with a fixed underlying type are a C++11 extension">, + "enumeration types with a fixed underlying type are a C++11 extension">, InGroup<CXX11>; def ext_c_enum_fixed_underlying_type : Extension< "enumeration types with a fixed underlying type are a Microsoft extension">, @@ -101,7 +101,7 @@ def ext_alignof_expr : ExtWarn< "%0 applied to an expression is a GNU extension">, InGroup<GNUAlignofExpression>; def warn_microsoft_dependent_exists : Warning< - "dependent %select{__if_not_exists|__if_exists}0 declarations are ignored">, + "dependent %select{__if_not_exists|__if_exists}0 declarations are ignored">, InGroup<DiagGroup<"microsoft-exists">>; def warn_microsoft_qualifiers_ignored : Warning< "qualifiers after comma in declarator list are ignored">, @@ -134,14 +134,14 @@ def ext_gnu_conditional_expr : Extension< "use of GNU ?: conditional expression extension, omitting middle operand">, InGroup<GNUConditionalOmittedOperand>; def ext_gnu_empty_initializer : Extension< "use of GNU empty initializer extension">, InGroup<GNUEmptyInitializer>; -def ext_gnu_array_range : Extension<"use of GNU array range extension">, +def ext_gnu_array_range : Extension<"use of GNU array range extension">, InGroup<GNUDesignator>; def ext_gnu_missing_equal_designator : ExtWarn< - "use of GNU 'missing =' extension in designator">, + "use of GNU 'missing =' extension in designator">, InGroup<GNUDesignator>; def err_expected_equal_designator : Error<"expected '=' or another designator">; def ext_gnu_old_style_field_designator : ExtWarn< - "use of GNU old-style field designator extension">, + "use of GNU old-style field designator extension">, InGroup<GNUDesignator>; def ext_gnu_case_range : Extension<"use of GNU case range extension">, InGroup<GNUCaseRange>; @@ -168,16 +168,16 @@ def err_unexpected_semi : Error<"unexpected ';' before %0">; def err_expected_fn_body : Error< "expected function body after function declarator">; def warn_attribute_on_function_definition : Warning< - "GCC does not allow %0 attribute in this position on a function definition">, + "GCC does not allow %0 attribute in this position on a function definition">, InGroup<GccCompat>; def warn_gcc_attribute_location : Warning< - "GCC does not allow an attribute in this position on a function declaration">, + "GCC does not allow an attribute in this position on a function declaration">, InGroup<GccCompat>; def warn_gcc_variable_decl_in_for_loop : Warning< "GCC does not allow variable declarations in for loop initializers before " "C99">, InGroup<GccCompat>; def warn_attribute_no_decl : Warning< - "attribute %0 ignored, because it is not attached to a declaration">, + "attribute %0 ignored, because it is not attached to a declaration">, InGroup<IgnoredAttributes>; def err_ms_attributes_not_enabled : Error< "'__declspec' attributes are not enabled; use '-fdeclspec' or " @@ -319,7 +319,7 @@ def warn_cxx98_compat_decltype : Warning< def err_unexpected_scope_on_base_decltype : Error< "unexpected namespace scope prior to decltype">; def err_expected_class_name : Error<"expected class name">; -def err_expected_class_name_not_template : +def err_expected_class_name_not_template : Error<"'typename' is redundant; base classes are implicitly types">; def err_unspecified_vla_size_with_static : Error< "'static' may not be used with an unspecified variable length array size">; @@ -395,7 +395,7 @@ def warn_arc_bridge_cast_nonarc : Warning< "'%0' casts have no effect when not using ARC">, InGroup<DiagGroup<"arc-bridge-casts-disallowed-in-nonarc">>; } - + def err_objc_illegal_visibility_spec : Error< "illegal visibility specification">; def err_objc_illegal_interface_qual : Error<"illegal interface qualifier">; @@ -687,7 +687,7 @@ def warn_cxx98_compat_extern_template : Warning< def warn_static_inline_explicit_inst_ignored : Warning< "ignoring '%select{static|inline}0' keyword on explicit template " "instantiation">, InGroup<DiagGroup<"static-inline-explicit-instantiation">>; - + // Constructor template diagnostics. def err_out_of_line_constructor_template_id : Error< "out-of-line constructor for %0 cannot have template arguments">; @@ -703,7 +703,7 @@ def err_expected_type_name_after_typename : Error< "expected an identifier or template-id after '::'">; def err_explicit_spec_non_template : Error< "explicit %select{specialization|instantiation}0 of non-template %1 %2">; - + def err_default_template_template_parameter_not_template : Error< "default template argument for a template template parameter must be a class " "template">; @@ -850,7 +850,7 @@ def err_zero_version : Error< "version number must have non-zero major, minor, or sub-minor version">; def err_availability_expected_platform : Error< "expected a platform name, e.g., 'macos'">; - + // objc_bridge_related attribute def err_objcbridge_related_expected_related_class : Error< "expected a related ObjectiveC class name, e.g., 'NSColor'">; @@ -994,7 +994,7 @@ def warn_pragma_init_seg_unsupported_target : Warning< // - #pragma fp_contract def err_pragma_fp_contract_scope : Error< "'#pragma fp_contract' can only appear at file scope or at the start of a " - "compound statement">; + "compound statement">; // - #pragma stdc unknown def ext_stdc_pragma_ignored : ExtWarn<"unknown pragma in STDC namespace">, InGroup<UnknownPragmas>; diff --git a/include/clang/Basic/DiagnosticSemaKinds.td b/include/clang/Basic/DiagnosticSemaKinds.td index d0a2bec78052..586f65e9201c 100644 --- a/include/clang/Basic/DiagnosticSemaKinds.td +++ b/include/clang/Basic/DiagnosticSemaKinds.td @@ -243,7 +243,7 @@ def err_invalid_vector_double_decl_spec : Error < "(available on POWER7 or later)">; def err_invalid_vector_long_long_decl_spec : Error < "use of 'long long' with '__vector bool' requires VSX support (available on " - "POWER7 or later) or extended Altivec support (available on POWER8 or later) " + "POWER7 or later) or extended Altivec support (available on POWER8 or later) " "to be enabled">; def err_invalid_vector_long_double_decl_spec : Error< "cannot use 'long double' with '__vector'">; @@ -388,7 +388,7 @@ def err_inline_non_function : Error< "'inline' can only appear on functions%select{| and non-local variables}0">; def err_noreturn_non_function : Error< "'_Noreturn' can only appear on functions">; -def warn_qual_return_type : Warning< +def warn_qual_return_type : Warning< "'%0' type qualifier%s1 on return type %plural{1:has|:have}1 no effect">, InGroup<IgnoredQualifiers>, DefaultIgnore; def warn_deprecated_redundant_constexpr_static_def : Warning< @@ -640,8 +640,8 @@ def warn_dyn_class_memaccess : Warning< def note_bad_memaccess_silence : Note< "explicitly cast the pointer to silence this warning">; def warn_sizeof_pointer_expr_memaccess : Warning< - "'%0' call operates on objects of type %1 while the size is based on a " - "different type %2">, + "'%0' call operates on objects of type %1 while the size is based on a " + "different type %2">, InGroup<SizeofPointerMemaccess>; def warn_sizeof_pointer_expr_memaccess_note : Note< "did you mean to %select{dereference the argument to 'sizeof' (and multiply " @@ -679,14 +679,14 @@ def note_suspicious_bzero_size_silence : Note< "parenthesize the second argument to silence">; def warn_strncat_large_size : Warning< - "the value of the size argument in 'strncat' is too large, might lead to a " + "the value of the size argument in 'strncat' is too large, might lead to a " "buffer overflow">, InGroup<StrncatSize>; -def warn_strncat_src_size : Warning<"size argument in 'strncat' call appears " +def warn_strncat_src_size : Warning<"size argument in 'strncat' call appears " "to be size of the source">, InGroup<StrncatSize>; def warn_strncat_wrong_size : Warning< "the value of the size argument to 'strncat' is wrong">, InGroup<StrncatSize>; def note_strncat_wrong_size : Note< - "change the argument to be the free space in the destination buffer minus " + "change the argument to be the free space in the destination buffer minus " "the terminating null byte">; def warn_assume_side_effects : Warning< @@ -1030,15 +1030,15 @@ def note_property_attribute : Note<"property %0 is declared " "%select{deprecated|unavailable|partial}1 here">; def err_setter_type_void : Error<"type of setter must be void">; def err_duplicate_method_decl : Error<"duplicate declaration of method %0">; -def warn_duplicate_method_decl : - Warning<"multiple declarations of method %0 found and ignored">, +def warn_duplicate_method_decl : + Warning<"multiple declarations of method %0 found and ignored">, InGroup<MethodDuplicate>, DefaultIgnore; def warn_objc_cdirective_format_string : Warning<"using %0 directive in %select{NSString|CFString}1 " "which is being passed as a formatting argument to the formatting " "%select{method|CFfunction}2">, InGroup<ObjCCStringFormat>, DefaultIgnore; -def err_objc_var_decl_inclass : +def err_objc_var_decl_inclass : Error<"cannot declare variable inside @interface or @protocol">; def err_missing_method_context : Error< "missing context for method declaration">; @@ -1250,7 +1250,7 @@ def warn_auto_implicit_atomic_property : Warning< "property is assumed atomic when auto-synthesizing the property">, InGroup<ImplicitAtomic>, DefaultIgnore; def warn_unimplemented_selector: Warning< - "no method with selector %0 is implemented in this translation unit">, + "no method with selector %0 is implemented in this translation unit">, InGroup<Selector>, DefaultIgnore; def warn_unimplemented_protocol_method : Warning< "method %0 in protocol %1 not implemented">, InGroup<Protocol>; @@ -1379,7 +1379,7 @@ def err_capture_default_non_local : Error< "non-local lambda expression cannot have a capture-default">; def err_multiple_final_overriders : Error< - "virtual function %q0 has more than one final overrider in %1">; + "virtual function %q0 has more than one final overrider in %1">; def note_final_overrider : Note<"final overrider of %q0 in %1">; def err_type_defined_in_type_specifier : Error< @@ -1421,7 +1421,7 @@ def warn_weak_template_vtable : Warning< def ext_using_undefined_std : ExtWarn< "using directive refers to implicitly-defined namespace 'std'">; - + // C++ exception specifications def err_exception_spec_in_typedef : Error< "exception specifications are not allowed in %select{typedefs|type aliases}0">; @@ -1475,7 +1475,7 @@ def ext_ms_using_declaration_inaccessible : ExtWarn< "to accessible member '%1') is a Microsoft compatibility extension">, AccessControl, InGroup<MicrosoftUsingDecl>; def err_access_ctor : Error< - "calling a %select{private|protected}0 constructor of class %2">, + "calling a %select{private|protected}0 constructor of class %2">, AccessControl; def ext_rvalue_to_reference_access_ctor : Extension< "C++98 requires an accessible copy constructor for class %2 when binding " @@ -1498,7 +1498,7 @@ def err_access_friend_function : Error< AccessControl; def err_access_dtor : Error< - "calling a %select{private|protected}1 destructor of class %0">, + "calling a %select{private|protected}1 destructor of class %0">, AccessControl; def err_access_dtor_base : Error<"base class %0 has %select{private|protected}1 destructor">, @@ -1540,7 +1540,7 @@ def note_access_protected_restricted_object : Note< def warn_cxx98_compat_sfinae_access_control : Warning< "substitution failure due to access control is incompatible with C++98">, InGroup<CXX98Compat>, DefaultIgnore, NoSFINAE; - + // C++ name lookup def err_incomplete_nested_name_spec : Error< "incomplete type %0 named in nested name specifier">; @@ -1733,6 +1733,8 @@ def warn_overriding_method_missing_noescape : Warning< "__attribute__((noescape))">, InGroup<MissingNoEscape>; def note_overridden_marked_noescape : Note< "parameter of overridden method is annotated with __attribute__((noescape))">; +def note_cat_conform_to_noescape_prot : Note< + "%select{category|class extension}0 conforms to protocol %1 which defines method %2">; def err_covariant_return_inaccessible_base : Error< "invalid covariant return for virtual function: %1 is a " @@ -1979,7 +1981,7 @@ def note_explicit_ctor_deduction_guide_here : Note< // C++11 decltype def err_decltype_in_declarator : Error< "'decltype' cannot be used to name a declaration">; - + // C++11 auto def warn_cxx98_compat_auto_type_specifier : Warning< "'auto' type specifier is incompatible with C++98">, @@ -2632,7 +2634,7 @@ def warn_objc_literal_comparison : Warning< def err_missing_atsign_prefix : Error< "string literal must be prefixed by '@' ">; def warn_objc_string_literal_comparison : Warning< - "direct comparison of a string literal has undefined behavior">, + "direct comparison of a string literal has undefined behavior">, InGroup<ObjCStringComparison>; def warn_concatenated_nsarray_literal : Warning< "concatenated NSString literal for an NSArray expression - " @@ -2746,7 +2748,7 @@ def warn_cxx11_gnu_attribute_on_type : Warning< "attribute %0 ignored, because it cannot be applied to a type">, InGroup<IgnoredAttributes>; def warn_unhandled_ms_attribute_ignored : Warning< - "__declspec attribute %0 is not supported">, + "__declspec attribute %0 is not supported">, InGroup<IgnoredAttributes>; def err_decl_attribute_invalid_on_stmt : Error< "%0 attribute cannot be applied to a statement">; @@ -3001,7 +3003,7 @@ def err_attribute_argument_out_of_range : Error< "1:can only be 1, since there is one parameter|" ":must be between 1 and %2}2">; -// Thread Safety Analysis +// Thread Safety Analysis def warn_unlock_but_no_lock : Warning<"releasing %0 '%1' that was not held">, InGroup<ThreadSafetyAnalysis>, DefaultIgnore; def warn_unlock_kind_mismatch : Warning< @@ -3015,7 +3017,7 @@ def warn_no_unlock : Warning< InGroup<ThreadSafetyAnalysis>, DefaultIgnore; def warn_expecting_locked : Warning< "expecting %0 '%1' to be held at the end of function">, - InGroup<ThreadSafetyAnalysis>, DefaultIgnore; + InGroup<ThreadSafetyAnalysis>, DefaultIgnore; // FIXME: improve the error message about locks not in scope def warn_lock_some_predecessors : Warning< "%0 '%1' is not held on every path through here">, @@ -3092,13 +3094,13 @@ def warn_fun_requires_lock_precise : def note_found_mutex_near_match : Note<"found near match '%0'">; // Verbose thread safety warnings -def warn_thread_safety_verbose : Warning<"Thread safety verbose warning.">, +def warn_thread_safety_verbose : Warning<"Thread safety verbose warning.">, InGroup<ThreadSafetyVerbose>, DefaultIgnore; def note_thread_warning_in_fun : Note<"Thread warning in function %0">; def note_guarded_by_declared_here : Note<"Guarded_by declared here.">; -// Dummy warning that will trigger "beta" warnings from the analysis if enabled. -def warn_thread_safety_beta : Warning<"Thread safety beta warning.">, +// Dummy warning that will trigger "beta" warnings from the analysis if enabled. +def warn_thread_safety_beta : Warning<"Thread safety beta warning.">, InGroup<ThreadSafetyBeta>, DefaultIgnore; // Consumed warnings @@ -3354,7 +3356,7 @@ def err_attribute_sentinel_not_zero_or_one : Error< "'sentinel' parameter 2 not 0 or 1">; def warn_cleanup_ext : Warning< "GCC does not allow the 'cleanup' attribute argument to be anything other " - "than a simple identifier">, + "than a simple identifier">, InGroup<GccCompat>; def err_attribute_cleanup_arg_not_function : Error< "'cleanup' argument %select{|%1 |%1 }0is not a %select{||single }0function">; @@ -3389,7 +3391,7 @@ def warn_iboutlet_object_type : Warning< def warn_iboutletcollection_property_assign : Warning< "IBOutletCollection properties should be copy/strong and not assign">, InGroup<ObjCInvalidIBOutletProperty>; - + def err_attribute_overloadable_mismatch : Error< "redeclaration of %0 must %select{not |}1have the 'overloadable' attribute">; def note_attribute_overloadable_prev_overload : Note< @@ -3854,7 +3856,7 @@ def note_template_param_different_kind : Note< def err_invalid_decl_specifier_in_nontype_parm : Error< "invalid declaration specifier in template non-type parameter">; - + def err_template_nontype_parm_different_type : Error< "template non-type parameter has a different type %0 in template " "%select{|template parameter }1redeclaration">; @@ -4156,7 +4158,7 @@ def err_dependent_typed_non_type_arg_in_partial_spec : Error< def err_partial_spec_args_match_primary_template : Error< "%select{class|variable}0 template partial specialization does not " "specialize any template argument; to %select{declare|define}1 the " - "primary template, remove the template argument list">; + "primary template, remove the template argument list">; def ext_partial_spec_not_more_specialized_than_primary : ExtWarn< "%select{class|variable}0 template partial specialization is not " "more specialized than the primary template">, DefaultError, @@ -4191,7 +4193,7 @@ def err_var_spec_no_template : Error< def err_var_spec_no_template_but_method : Error< "no variable template matches specialization; " "did you mean to use %0 as function template instead?">; - + // C++ Function template specializations def err_function_template_spec_no_match : Error< "no function template matches function template specialization %0">; @@ -4312,12 +4314,12 @@ def err_explicit_instantiation_out_of_scope : Error< def err_explicit_instantiation_must_be_global : Error< "explicit instantiation of %0 must occur at global scope">; def warn_explicit_instantiation_out_of_scope_0x : Warning< - "explicit instantiation of %0 not in a namespace enclosing %1">, + "explicit instantiation of %0 not in a namespace enclosing %1">, InGroup<CXX11Compat>, DefaultIgnore; def warn_explicit_instantiation_must_be_global_0x : Warning< - "explicit instantiation of %0 must occur at global scope">, + "explicit instantiation of %0 must occur at global scope">, InGroup<CXX11Compat>, DefaultIgnore; - + def err_explicit_instantiation_requires_name : Error< "explicit instantiation declaration requires a name">; def err_explicit_instantiation_of_typedef : Error< @@ -4378,7 +4380,7 @@ def err_mismatched_exception_spec_explicit_instantiation : Error< def ext_mismatched_exception_spec_explicit_instantiation : ExtWarn< err_mismatched_exception_spec_explicit_instantiation.Text>, InGroup<MicrosoftExceptionSpec>; - + // C++ typename-specifiers def err_typename_nested_not_found : Error<"no type named %0 in %1">; def err_typename_nested_not_found_enable_if : Error< @@ -4456,7 +4458,7 @@ def note_template_parameter_pack_non_pack : Note< def note_template_parameter_pack_here : Note< "previous %select{template type|non-type template|template template}0 " "parameter%select{| pack}1 declared here">; - + def err_unexpanded_parameter_pack : Error< "%select{expression|base type|declaration type|data member type|bit-field " "size|static assertion|fixed underlying type|enumerator value|" @@ -4560,7 +4562,7 @@ def warn_missing_prototype : Warning< "no previous prototype for function %0">, InGroup<DiagGroup<"missing-prototypes">>, DefaultIgnore; def note_declaration_not_a_prototype : Note< - "this declaration is not a prototype; add 'void' to make it a prototype for a zero-parameter function">; + "this declaration is not a prototype; add 'void' to make it a prototype for a zero-parameter function">; def warn_strict_prototypes : Warning< "this %select{function declaration is not|block declaration is not|" "old-style function definition is not preceded by}0 a prototype">, @@ -4768,7 +4770,7 @@ def ext_ms_forward_ref_enum : ExtWarn< def ext_forward_ref_enum_def : Extension< "redeclaration of already-defined enum %0 is a GNU extension">, InGroup<GNURedeclaredEnum>; - + def err_redefinition_of_enumerator : Error<"redefinition of enumerator %0">; def err_duplicate_member : Error<"duplicate member %0">; def err_misplaced_ivar : Error< @@ -4787,7 +4789,7 @@ def ext_enumerator_increment_too_large : ExtWarn< def warn_flag_enum_constant_out_of_range : Warning< "enumeration value %0 is out of range of flags in enumeration type %1">, InGroup<FlagEnum>; - + def warn_illegal_constant_array_size : Extension< "size of static array must be an integer constant expression">; def err_vm_decl_in_file_scope : Error< @@ -4892,7 +4894,7 @@ def err_illegal_initializer : Error< "illegal initializer (only variables can be initialized)">; def err_illegal_initializer_type : Error<"illegal initializer type %0">; def ext_init_list_type_narrowing : ExtWarn< - "type %0 cannot be narrowed to %1 in initializer list">, + "type %0 cannot be narrowed to %1 in initializer list">, InGroup<CXX11Narrowing>, DefaultError, SFINAEFailure; def ext_init_list_variable_narrowing : ExtWarn< "non-constant-expression cannot be narrowed from type %0 to %1 in " @@ -5230,9 +5232,9 @@ def err_arc_illegal_method_def : Error< def warn_arc_strong_pointer_objc_pointer : Warning< "method parameter of type %0 with no explicit ownership">, InGroup<DiagGroup<"explicit-ownership-type">>, DefaultIgnore; - + } // end "ARC Restrictions" category - + def err_arc_lost_method_convention : Error< "method was declared as %select{an 'alloc'|a 'copy'|an 'init'|a 'new'}0 " "method, but its implementation doesn't match because %select{" @@ -5301,7 +5303,7 @@ def warn_receiver_forward_instance : Warning< InGroup<ForwardClassReceiver>, DefaultIgnore; def err_arc_collection_forward : Error< "collection expression type %0 is a forward declaration">; -def err_arc_multiple_method_decl : Error< +def err_arc_multiple_method_decl : Error< "multiple methods named %0 found with mismatched result, " "parameter type or attributes">; def warn_arc_lifetime_result_type : Warning< @@ -5694,7 +5696,7 @@ def warn_namespace_member_extra_qualification : Warning< "extra qualification on member %0">, InGroup<DiagGroup<"extra-qualification">>; def err_member_qualification : Error< - "non-friend class member %0 cannot have a qualified name">; + "non-friend class member %0 cannot have a qualified name">; def note_member_def_close_match : Note<"member declaration nearly matches">; def note_member_def_close_const_match : Note< "member declaration does not match because " @@ -5800,7 +5802,7 @@ def err_typecheck_invalid_lvalue_addrof_addrof_function : Error< def err_typecheck_invalid_lvalue_addrof : Error< "cannot take the address of an rvalue of type %0">; def ext_typecheck_addrof_temporary : ExtWarn< - "taking the address of a temporary object of type %0">, + "taking the address of a temporary object of type %0">, InGroup<AddressOfTemporary>, DefaultError; def err_typecheck_addrof_temporary : Error< "taking the address of a temporary object of type %0">; @@ -5911,7 +5913,7 @@ def warn_mixed_sign_comparison : Warning< "comparison of integers of different signs: %0 and %1">, InGroup<SignCompare>, DefaultIgnore; def warn_out_of_range_compare : Warning< - "result of comparison of %select{constant %0|true|false}1 with " + "result of comparison of %select{constant %0|true|false}1 with " "%select{expression of type %2|boolean expression}3 is always %4">, InGroup<TautologicalOutOfRangeCompare>; def warn_tautological_bool_compare : Warning<warn_out_of_range_compare.Text>, @@ -6069,7 +6071,7 @@ def err_no_subobject_property_setting : Error< "expression is not assignable">; def err_qualified_objc_access : Error< "%select{property|instance variable}0 access cannot be qualified with '%1'">; - + def ext_freestanding_complex : Extension< "complex numbers are an extension in a freestanding C99 implementation">; @@ -6235,13 +6237,13 @@ def warn_cxx98_compat_cast_fn_obj : Warning< def err_bad_reinterpret_cast_small_int : Error< "cast from pointer to smaller type %2 loses information">; def err_bad_cxx_cast_vector_to_scalar_different_size : Error< - "%select{||reinterpret_cast||C-style cast|}0 from vector %1 " + "%select{||reinterpret_cast||C-style cast|}0 from vector %1 " "to scalar %2 of different size">; def err_bad_cxx_cast_scalar_to_vector_different_size : Error< - "%select{||reinterpret_cast||C-style cast|}0 from scalar %1 " + "%select{||reinterpret_cast||C-style cast|}0 from scalar %1 " "to vector %2 of different size">; def err_bad_cxx_cast_vector_to_vector_different_size : Error< - "%select{||reinterpret_cast||C-style cast|}0 from vector %1 " + "%select{||reinterpret_cast||C-style cast|}0 from vector %1 " "to vector %2 of different size">; def err_bad_lvalue_to_rvalue_cast : Error< "cannot cast from lvalue of type %1 to rvalue reference type %2; types are " @@ -6643,7 +6645,7 @@ def err_typecheck_nonviable_condition_incomplete : Error< def err_typecheck_deleted_function : Error< "conversion function %diff{from $ to $|between types}0,1 " "invokes a deleted function">; - + def err_expected_class_or_namespace : Error<"%0 is not a class" "%select{ or namespace|, namespace, or enumeration}1">; def err_invalid_declarator_scope : Error<"cannot define or redeclare %0 here " @@ -7011,11 +7013,11 @@ def err_typecheck_call_too_many_args_at_most_suggest : Error< "too many %select{|||execution configuration }0arguments to " "%select{function|block|method|kernel function}0 call, " "expected at most %1, have %2; did you mean %3?">; - + def err_arc_typecheck_convert_incompatible_pointer : Error< "incompatible pointer types passing retainable parameter of type %0" "to a CF function expecting %1 type">; - + def err_builtin_fn_use : Error<"builtin functions must be directly called">; def warn_call_wrong_number_of_arguments : Warning< @@ -7129,7 +7131,8 @@ def err_shared_var_init : Error< "initialization is not supported for __shared__ variables.">; def err_device_static_local_var : Error< "within a %select{__device__|__global__|__host__|__host__ __device__}0 " - "function, only __shared__ variables may be marked 'static'">; + "function, only __shared__ variables or const variables without device " + "memory qualifier may be marked 'static'">; def err_cuda_vla : Error< "cannot use variable-length arrays in " "%select{__device__|__global__|__host__|__host__ __device__}0 functions">; @@ -7505,8 +7508,8 @@ def err_reference_to_local_in_enclosing_context : Error< "%select{%3|block literal|lambda expression|context}2">; def err_static_data_member_not_allowed_in_local_class : Error< - "static data member %0 not allowed in local class %1">; - + "static data member %0 not allowed in local class %1">; + // C++ derived classes def err_base_clause_on_union : Error<"unions cannot have base classes">; def err_base_must_be_class : Error<"base specifier must name a class">; @@ -7851,6 +7854,13 @@ def warn_null_ret : Warning< "null returned from %select{function|method}0 that requires a non-null return value">, InGroup<NonNull>; +def err_lifetimebound_no_object_param : Error< + "'lifetimebound' attribute cannot be applied; %select{static |non-}0member " + "function has no implicit object parameter">; +def err_lifetimebound_ctor_dtor : Error< + "'lifetimebound' attribute cannot be applied to a " + "%select{constructor|destructor}0">; + // CHECK: returning address/reference of stack memory def warn_ret_stack_addr_ref : Warning< "%select{address of|reference to}0 stack memory associated with " @@ -7865,7 +7875,8 @@ def warn_ret_addr_label : Warning< def err_ret_local_block : Error< "returning block that lives on the local stack">; def note_local_var_initializer : Note< - "%select{via initialization of|binding reference}0 variable %1 here">; + "%select{via initialization of|binding reference}0 variable " + "%select{%2 |}1here">; def note_init_with_default_member_initalizer : Note< "initializing field %0 with default member initializer">; @@ -7897,13 +7908,14 @@ def note_lifetime_extending_member_declared_here : Note< "member with %select{reference|'std::initializer_list'}0 subobject}1 " "declared here">; def warn_dangling_variable : Warning< - "%select{temporary %select{whose address is used as value of|bound to}3 " - "%select{%select{|reference }3member of local variable|" - "local %select{variable|reference}3}1|" + "%select{temporary %select{whose address is used as value of|" + "%select{|implicitly }2bound to}4 " + "%select{%select{|reference }4member of local variable|" + "local %select{variable|reference}4}1|" "array backing " "%select{initializer list subobject of local variable|" "local initializer list}1}0 " - "%2 will be destroyed at the end of the full-expression">, + "%select{%3 |}2will be destroyed at the end of the full-expression">, InGroup<Dangling>; def warn_new_dangling_reference : Warning< "temporary bound to reference member of allocated object " @@ -8219,7 +8231,7 @@ def err_vector_incorrect_num_initializers : Error< def err_altivec_empty_initializer : Error<"expected initializer">; def err_invalid_neon_type_code : Error< - "incompatible constant for this __builtin_neon function">; + "incompatible constant for this __builtin_neon function">; def err_argument_invalid_range : Error< "argument value %0 is outside the valid range [%1, %2]">; def warn_argument_invalid_range : Warning< @@ -8275,7 +8287,7 @@ def err_constant_integer_arg_type : Error< def ext_mixed_decls_code : Extension< "ISO C90 forbids mixing declarations and code">, InGroup<DiagGroup<"declaration-after-statement">>; - + def err_non_local_variable_decl_in_for : Error< "declaration of non-local variable in 'for' loop">; def err_non_variable_decl_in_for : Error< @@ -8343,7 +8355,7 @@ def warn_nsconsumed_attribute_mismatch : Warning< err_nsconsumed_attribute_mismatch.Text>, InGroup<NSConsumedMismatch>; def warn_nsreturns_retained_attribute_mismatch : Warning< err_nsreturns_retained_attribute_mismatch.Text>, InGroup<NSReturnsMismatch>; - + def note_getter_unavailable : Note< "or because setter is declared here, but no getter method %0 is found">; def err_invalid_protocol_qualifiers : Error< @@ -8599,7 +8611,7 @@ def err_opencl_extern_block_declaration : Error< def err_opencl_block_ref_block : Error< "cannot refer to a block inside block">; -// OpenCL v2.0 s6.13.9 - Address space qualifier functions. +// OpenCL v2.0 s6.13.9 - Address space qualifier functions. def err_opencl_builtin_to_addr_arg_num : Error< "invalid number of arguments to function: %0">; def err_opencl_builtin_to_addr_invalid_arg : Error< diff --git a/include/clang/Basic/DiagnosticSerializationKinds.td b/include/clang/Basic/DiagnosticSerializationKinds.td index 3a552e2f3db4..54237d16f5c1 100644 --- a/include/clang/Basic/DiagnosticSerializationKinds.td +++ b/include/clang/Basic/DiagnosticSerializationKinds.td @@ -49,7 +49,7 @@ def err_pch_diagopt_mismatch : Error<"%0 is currently enabled, but was not in " "the PCH file">; def err_pch_modulecache_mismatch : Error<"PCH was compiled with module cache " "path '%0', but the path is currently '%1'">; - + def err_pch_version_too_old : Error< "PCH file uses an older PCH format that is no longer supported">; def err_pch_version_too_new : Error< diff --git a/include/clang/Basic/FileSystemStatCache.h b/include/clang/Basic/FileSystemStatCache.h index 45aded527c1b..1ec344623a0d 100644 --- a/include/clang/Basic/FileSystemStatCache.h +++ b/include/clang/Basic/FileSystemStatCache.h @@ -62,7 +62,7 @@ protected: public: virtual ~FileSystemStatCache() = default; - + enum LookupResult { /// We know the file exists and its cached stat data. CacheExists, @@ -90,10 +90,10 @@ public: void setNextStatCache(std::unique_ptr<FileSystemStatCache> Cache) { NextStatCache = std::move(Cache); } - + /// Retrieve the next stat call cache in the chain. FileSystemStatCache *getNextStatCache() { return NextStatCache.get(); } - + /// Retrieve the next stat call cache in the chain, transferring /// ownership of this cache (and, transitively, all of the remaining caches) /// to the caller. diff --git a/include/clang/Basic/IdentifierTable.h b/include/clang/Basic/IdentifierTable.h index f43df5c64829..c2e9c71b0f0d 100644 --- a/include/clang/Basic/IdentifierTable.h +++ b/include/clang/Basic/IdentifierTable.h @@ -63,7 +63,7 @@ class IdentifierInfo { bool IsPoisoned : 1; // True if identifier is poisoned. bool IsCPPOperatorKeyword : 1; // True if ident is a C++ operator keyword. bool NeedsHandleIdentifier : 1; // See "RecomputeNeedsHandleIdentifier". - bool IsFromAST : 1; // True if identifier was loaded (at least + bool IsFromAST : 1; // True if identifier was loaded (at least // partially) from an AST file. bool ChangedAfterLoad : 1; // True if identifier has changed from the // definition loaded from an AST file. @@ -308,7 +308,7 @@ public: bool hasChangedSinceDeserialization() const { return ChangedAfterLoad; } - + /// Note that this identifier has changed since it was loaded from /// an AST file. void setChangedSinceDeserialization() { @@ -320,7 +320,7 @@ public: bool hasFETokenInfoChangedSinceDeserialization() const { return FEChangedAfterLoad; } - + /// Note that the frontend token information for this identifier has /// changed since it was loaded from an AST file. void setFETokenInfoChangedSinceDeserialization() { @@ -330,7 +330,7 @@ public: /// Determine whether the information for this identifier is out of /// date with respect to the external source. bool isOutOfDate() const { return OutOfDate; } - + /// Set whether the information for this identifier is out of /// date with respect to the external source. void setOutOfDate(bool OOD) { @@ -340,10 +340,10 @@ public: else RecomputeNeedsHandleIdentifier(); } - + /// Determine whether this is the contextual keyword \c import. bool isModulesImport() const { return IsModulesImport; } - + /// Set whether this identifier is the contextual keyword \c import. void setModulesImport(bool I) { IsModulesImport = I; @@ -419,7 +419,7 @@ public: class IdentifierIterator { protected: IdentifierIterator() = default; - + public: IdentifierIterator(const IdentifierIterator &) = delete; IdentifierIterator &operator=(const IdentifierIterator &) = delete; @@ -490,7 +490,7 @@ public: IdentifierInfoLookup *getExternalIdentifierLookup() const { return ExternalLookup; } - + llvm::BumpPtrAllocator& getAllocator() { return HashTable.getAllocator(); } @@ -572,7 +572,7 @@ public: void AddKeywords(const LangOptions &LangOpts); }; -/// A family of Objective-C methods. +/// A family of Objective-C methods. /// /// These families have no inherent meaning in the language, but are /// nonetheless central enough in the existing implementations to @@ -687,13 +687,13 @@ class Selector { MultiKeywordSelector *getMultiKeywordSelector() const { return reinterpret_cast<MultiKeywordSelector *>(InfoPtr & ~ArgFlags); } - + unsigned getIdentifierInfoFlag() const { return InfoPtr & ArgFlags; } static ObjCMethodFamily getMethodFamilyImpl(Selector sel); - + static ObjCStringFormatFamily getStringFormatFamilyImpl(Selector sel); public: @@ -730,11 +730,11 @@ public: } unsigned getNumArgs() const; - + /// Retrieve the identifier at a given position in the selector. /// /// Note that the identifier pointer returned may be NULL. Clients that only - /// care about the text of the identifier string, and not the specific, + /// care about the text of the identifier string, and not the specific, /// uniqued identifier pointer, should use \c getNameForSlot(), which returns /// an empty string when the identifier pointer would be NULL. /// @@ -745,7 +745,7 @@ public: /// \returns the uniqued identifier for this slot, or NULL if this slot has /// no corresponding identifier. IdentifierInfo *getIdentifierInfoForSlot(unsigned argIndex) const; - + /// Retrieve the name at a given position in the selector. /// /// \param argIndex The index for which we want to retrieve the name. @@ -755,7 +755,7 @@ public: /// \returns the name for this slot, which may be the empty string if no /// name was supplied. StringRef getNameForSlot(unsigned argIndex) const; - + /// Derive the full selector name (e.g. "foo:bar:") and return /// it as an std::string. std::string getAsString() const; @@ -769,11 +769,11 @@ public: ObjCMethodFamily getMethodFamily() const { return getMethodFamilyImpl(*this); } - + ObjCStringFormatFamily getStringFormatFamily() const { return getStringFormatFamilyImpl(*this); } - + static Selector getEmptyMarker() { return Selector(uintptr_t(-1)); } @@ -781,7 +781,7 @@ public: static Selector getTombstoneMarker() { return Selector(uintptr_t(-2)); } - + static ObjCInstanceTypeFamily getInstTypeMethodFamily(Selector sel); }; @@ -901,7 +901,7 @@ struct PointerLikeTypeTraits<clang::Selector> { return clang::Selector(reinterpret_cast<uintptr_t>(P)); } - enum { NumLowBitsAvailable = 0 }; + enum { NumLowBitsAvailable = 0 }; }; // Provide PointerLikeTypeTraits for IdentifierInfo pointers, which diff --git a/include/clang/Basic/LLVM.h b/include/clang/Basic/LLVM.h index 8a432db911da..3f833c62c0a8 100644 --- a/include/clang/Basic/LLVM.h +++ b/include/clang/Basic/LLVM.h @@ -59,7 +59,7 @@ namespace clang { using llvm::dyn_cast; using llvm::dyn_cast_or_null; using llvm::cast_or_null; - + // ADT's. using llvm::ArrayRef; using llvm::MutableArrayRef; diff --git a/include/clang/Basic/LangOptions.h b/include/clang/Basic/LangOptions.h index f3a6292e5ade..a1396f84352f 100644 --- a/include/clang/Basic/LangOptions.h +++ b/include/clang/Basic/LangOptions.h @@ -50,10 +50,10 @@ protected: class LangOptions : public LangOptionsBase { public: using Visibility = clang::Visibility; - + enum GCMode { NonGC, GCOnly, HybridGC }; enum StackProtectorMode { SSPOff, SSPOn, SSPStrong, SSPReq }; - + enum SignedOverflowBehaviorTy { // Default C standard behavior. SOB_Undefined, @@ -165,7 +165,7 @@ public: clang::ObjCRuntime ObjCRuntime; std::string ObjCConstantStringClass; - + /// The name of the handler function to be called when -ftrapv is /// specified. /// @@ -209,10 +209,10 @@ public: LangOptions(); // Define accessors/mutators for language options of enumeration type. -#define LANGOPT(Name, Bits, Default, Description) +#define LANGOPT(Name, Bits, Default, Description) #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \ Type get##Name() const { return static_cast<Type>(Name); } \ - void set##Name(Type Value) { Name = static_cast<unsigned>(Value); } + void set##Name(Type Value) { Name = static_cast<unsigned>(Value); } #include "clang/Basic/LangOptions.def" /// Are we compiling a module interface (.cppm or module map)? @@ -228,7 +228,7 @@ public: bool isSignedOverflowDefined() const { return getSignedOverflowBehavior() == SOB_Defined; } - + bool isSubscriptPointerArithmetic() const { return ObjCRuntime.isSubscriptPointerArithmetic() && !ObjCSubscriptingLegacyRuntime; @@ -309,7 +309,7 @@ enum TranslationUnitKind { /// The translation unit is a module. TU_Module }; - + } // namespace clang #endif // LLVM_CLANG_BASIC_LANGOPTIONS_H diff --git a/include/clang/Basic/Linkage.h b/include/clang/Basic/Linkage.h index 94dcfd445b0b..529cfa9f3f8d 100644 --- a/include/clang/Basic/Linkage.h +++ b/include/clang/Basic/Linkage.h @@ -19,7 +19,7 @@ namespace clang { -/// Describes the different kinds of linkage +/// Describes the different kinds of linkage /// (C++ [basic.link], C99 6.2.2) that an entity may have. enum Linkage : unsigned char { /// No linkage, which means that the entity is unique and @@ -31,7 +31,7 @@ enum Linkage : unsigned char { /// translation units). InternalLinkage, - /// External linkage within a unique namespace. + /// External linkage within a unique namespace. /// /// From the language perspective, these entities have external /// linkage. However, since they reside in an anonymous namespace, diff --git a/include/clang/Basic/Module.h b/include/clang/Basic/Module.h index 4aebda1887c4..02a4ef610b64 100644 --- a/include/clang/Basic/Module.h +++ b/include/clang/Basic/Module.h @@ -44,7 +44,7 @@ class raw_ostream; } // namespace llvm namespace clang { - + class LangOptions; class TargetInfo; @@ -66,7 +66,7 @@ class Module { public: /// The name of this module. std::string Name; - + /// The location of the module definition. SourceLocation DefinitionLoc; @@ -111,12 +111,12 @@ public: /// The module through which entities defined in this module will /// eventually be exposed, for use in "private" modules. std::string ExportAsModule; - + private: /// The submodules of this module, indexed by name. std::vector<Module *> SubModules; - - /// A mapping from the submodule name to the index into the + + /// A mapping from the submodule name to the index into the /// \c SubModules vector at which that submodule resides. llvm::StringMap<unsigned> SubModuleIndex; @@ -214,13 +214,13 @@ public: /// Whether this module was loaded from a module file. unsigned IsFromModuleFile : 1; - + /// Whether this is a framework module. unsigned IsFramework : 1; - + /// Whether this is an explicit submodule. unsigned IsExplicit : 1; - + /// Whether this is a "system" module (which assumes that all /// headers in it are system headers). unsigned IsSystem : 1; @@ -233,16 +233,16 @@ public: /// Whether this is an inferred submodule (module * { ... }). unsigned IsInferred : 1; - /// Whether we should infer submodules for this module based on + /// Whether we should infer submodules for this module based on /// the headers. /// /// Submodules can only be inferred for modules with an umbrella header. unsigned InferSubmodules : 1; - + /// Whether, when inferring submodules, the inferred submodules /// should be explicit. unsigned InferExplicitSubmodules : 1; - + /// Whether, when inferring submodules, the inferr submodules should /// export all modules they import (e.g., the equivalent of "export *"). unsigned InferExportWildcard : 1; @@ -280,31 +280,31 @@ public: /// The set of modules imported by this module, and on which this /// module depends. llvm::SmallSetVector<Module *, 2> Imports; - + /// Describes an exported module. /// /// The pointer is the module being re-exported, while the bit will be true /// to indicate that this is a wildcard export. using ExportDecl = llvm::PointerIntPair<Module *, 1, bool>; - + /// The set of export declarations. SmallVector<ExportDecl, 2> Exports; - + /// Describes an exported module that has not yet been resolved /// (perhaps because the module it refers to has not yet been loaded). struct UnresolvedExportDecl { /// The location of the 'export' keyword in the module map file. SourceLocation ExportLoc; - + /// The name of the module. ModuleId Id; - + /// Whether this export declaration ends in a wildcard, indicating /// that all of its submodules should be exported (rather than the named /// module itself). bool Wildcard; }; - + /// The set of export declarations that have yet to be resolved. SmallVector<UnresolvedExportDecl, 2> UnresolvedExports; @@ -320,7 +320,7 @@ public: LinkLibrary() = default; LinkLibrary(const std::string &Library, bool IsFramework) : Library(Library), IsFramework(IsFramework) {} - + /// The library to link against. /// /// This will typically be a library or framework name, but can also @@ -371,9 +371,9 @@ public: /// Construct a new module or submodule. Module(StringRef Name, SourceLocation DefinitionLoc, Module *Parent, bool IsFramework, bool IsExplicit, unsigned VisibilityID); - + ~Module(); - + /// Determine whether this module is available for use within the /// current translation unit. bool isAvailable() const { return IsAvailable; } @@ -395,7 +395,7 @@ public: /// /// \param ShadowingModule If this module is unavailable because it is /// shadowed, this parameter will be set to the shadowing module. - bool isAvailable(const LangOptions &LangOpts, + bool isAvailable(const LangOptions &LangOpts, const TargetInfo &Target, Requirement &Req, UnresolvedHeaderDirective &MissingHeader, @@ -403,19 +403,19 @@ public: /// Determine whether this module is a submodule. bool isSubModule() const { return Parent != nullptr; } - + /// Determine whether this module is a submodule of the given other /// module. bool isSubModuleOf(const Module *Other) const; - + /// Determine whether this module is a part of a framework, /// either because it is a framework module or because it is a submodule /// of a framework module. bool isPartOfFramework() const { - for (const Module *Mod = this; Mod; Mod = Mod->Parent) + for (const Module *Mod = this; Mod; Mod = Mod->Parent) if (Mod->IsFramework) return true; - + return false; } @@ -456,7 +456,7 @@ public: /// Retrieve the top-level module for this (sub)module, which may /// be this module. const Module *getTopLevelModule() const; - + /// Retrieve the name of the top-level module. StringRef getTopLevelModuleName() const { return getTopLevelModule()->Name; @@ -552,7 +552,7 @@ public: using submodule_iterator = std::vector<Module *>::iterator; using submodule_const_iterator = std::vector<Module *>::const_iterator; - + submodule_iterator submodule_begin() { return SubModules.begin(); } submodule_const_iterator submodule_begin() const {return SubModules.begin();} submodule_iterator submodule_end() { return SubModules.end(); } @@ -575,9 +575,9 @@ public: return "<module-includes>"; } - /// Print the module map for this module to the given stream. + /// Print the module map for this module to the given stream. void print(raw_ostream &OS, unsigned Indent = 0) const; - + /// Dump the contents of this module to the given output stream. void dump() const; diff --git a/include/clang/Basic/ObjCRuntime.h b/include/clang/Basic/ObjCRuntime.h index d5f4f50fe36f..c307c9643390 100644 --- a/include/clang/Basic/ObjCRuntime.h +++ b/include/clang/Basic/ObjCRuntime.h @@ -154,7 +154,7 @@ public: llvm_unreachable("bad kind"); } - /// Does this runtime natively provide the ARC entrypoints? + /// Does this runtime natively provide the ARC entrypoints? /// /// ARC cannot be directly supported on a platform that does not provide /// these entrypoints, although it may be supportable via a stub diff --git a/include/clang/Basic/OperatorKinds.h b/include/clang/Basic/OperatorKinds.h index b0064cfb4e5a..3096f835e66b 100644 --- a/include/clang/Basic/OperatorKinds.h +++ b/include/clang/Basic/OperatorKinds.h @@ -27,7 +27,7 @@ enum OverloadedOperatorKind : int { NUM_OVERLOADED_OPERATORS }; -/// Retrieve the spelling of the given overloaded operator, without +/// Retrieve the spelling of the given overloaded operator, without /// the preceding "operator" keyword. const char *getOperatorSpelling(OverloadedOperatorKind Operator); diff --git a/include/clang/Basic/Sanitizers.def b/include/clang/Basic/Sanitizers.def index 5a36822a6303..ae5c75fc5bbd 100644 --- a/include/clang/Basic/Sanitizers.def +++ b/include/clang/Basic/Sanitizers.def @@ -131,9 +131,14 @@ SANITIZER_GROUP("undefined", Undefined, // -fsanitize=undefined-trap is an alias for -fsanitize=undefined. SANITIZER_GROUP("undefined-trap", UndefinedTrap, Undefined) +// ImplicitConversionSanitizer +SANITIZER("implicit-integer-truncation", ImplicitIntegerTruncation) +SANITIZER_GROUP("implicit-conversion", ImplicitConversion, + ImplicitIntegerTruncation) + SANITIZER_GROUP("integer", Integer, - SignedIntegerOverflow | UnsignedIntegerOverflow | Shift | - IntegerDivideByZero) + ImplicitIntegerTruncation | IntegerDivideByZero | Shift | + SignedIntegerOverflow | UnsignedIntegerOverflow) SANITIZER("local-bounds", LocalBounds) SANITIZER_GROUP("bounds", Bounds, ArrayBounds | LocalBounds) diff --git a/include/clang/Basic/Sanitizers.h b/include/clang/Basic/Sanitizers.h index 469d9e2e9591..2ecbde821599 100644 --- a/include/clang/Basic/Sanitizers.h +++ b/include/clang/Basic/Sanitizers.h @@ -84,7 +84,8 @@ SanitizerMask expandSanitizerGroups(SanitizerMask Kinds); /// Return the sanitizers which do not affect preprocessing. inline SanitizerMask getPPTransparentSanitizers() { return SanitizerKind::CFI | SanitizerKind::Integer | - SanitizerKind::Nullability | SanitizerKind::Undefined; + SanitizerKind::ImplicitConversion | SanitizerKind::Nullability | + SanitizerKind::Undefined; } } // namespace clang diff --git a/include/clang/Basic/SourceLocation.h b/include/clang/Basic/SourceLocation.h index f174f83abf4a..488a604a452f 100644 --- a/include/clang/Basic/SourceLocation.h +++ b/include/clang/Basic/SourceLocation.h @@ -38,7 +38,7 @@ class SourceManager; /// source file (MemoryBuffer) along with its \#include path and \#line data. /// class FileID { - /// A mostly-opaque identifier, where 0 is "invalid", >0 is + /// A mostly-opaque identifier, where 0 is "invalid", >0 is /// this module, and <-1 is something loaded from another module. int ID = 0; @@ -60,7 +60,7 @@ private: friend class ASTWriter; friend class ASTReader; friend class SourceManager; - + static FileID get(int V) { FileID F; F.ID = V; @@ -221,7 +221,7 @@ public: return B != X.B || E != X.E; } }; - + /// Represents a character-granular source range. /// /// The underlying SourceRange can either specify the starting/ending character @@ -229,7 +229,7 @@ public: /// last token of the range (a "token range"). In the token range case, the /// size of the last token must be measured to determine the actual end of the /// range. -class CharSourceRange { +class CharSourceRange { SourceRange Range; bool IsTokenRange = false; @@ -244,7 +244,7 @@ public: static CharSourceRange getCharRange(SourceRange R) { return CharSourceRange(R, false); } - + static CharSourceRange getTokenRange(SourceLocation B, SourceLocation E) { return getTokenRange(SourceRange(B, E)); } @@ -252,21 +252,21 @@ public: static CharSourceRange getCharRange(SourceLocation B, SourceLocation E) { return getCharRange(SourceRange(B, E)); } - + /// Return true if the end of this range specifies the start of /// the last token. Return false if the end of this range specifies the last /// character in the range. bool isTokenRange() const { return IsTokenRange; } bool isCharRange() const { return !IsTokenRange; } - + SourceLocation getBegin() const { return Range.getBegin(); } SourceLocation getEnd() const { return Range.getEnd(); } SourceRange getAsRange() const { return Range; } - + void setBegin(SourceLocation b) { Range.setBegin(b); } void setEnd(SourceLocation e) { Range.setEnd(e); } void setTokenRange(bool TR) { IsTokenRange = TR; } - + bool isValid() const { return Range.isValid(); } bool isInvalid() const { return !isValid(); } }; @@ -453,7 +453,7 @@ namespace llvm { return LHS == RHS; } }; - + template <> struct isPodLike<clang::SourceLocation> { static const bool value = true; }; template <> diff --git a/include/clang/Basic/SourceManager.h b/include/clang/Basic/SourceManager.h index 99c36f4cdfcc..af7dbbc13ca7 100644 --- a/include/clang/Basic/SourceManager.h +++ b/include/clang/Basic/SourceManager.h @@ -155,7 +155,7 @@ namespace SrcMgr { ContentCache(const FileEntry *Ent, const FileEntry *contentEnt) : Buffer(nullptr, false), OrigEntry(Ent), ContentsEntry(contentEnt), BufferOverridden(false), IsSystemFile(false), IsTransient(false) {} - + /// The copy ctor does not allow copies where source object has either /// a non-NULL Buffer or SourceLineCache. Ownership of allocated memory /// is not transferred, so this is a logical error. @@ -1072,7 +1072,7 @@ public: unsigned FileOffset = Entry.getOffset(); return SourceLocation::getFileLoc(FileOffset); } - + /// Return the source location corresponding to the last byte of the /// specified file. SourceLocation getLocForEndOfFile(FileID FID) const { @@ -1080,7 +1080,7 @@ public: const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid); if (Invalid || !Entry.isFile()) return SourceLocation(); - + unsigned FileOffset = Entry.getOffset(); return SourceLocation::getFileLoc(FileOffset + getFileIDSize(FID)); } @@ -1403,7 +1403,7 @@ public: PresumedLoc getPresumedLoc(SourceLocation Loc, bool UseLineDirectives = true) const; - /// Returns whether the PresumedLoc for a given SourceLocation is + /// Returns whether the PresumedLoc for a given SourceLocation is /// in the main file. /// /// This computes the "presumed" location for a SourceLocation, then checks diff --git a/include/clang/Basic/SourceManagerInternals.h b/include/clang/Basic/SourceManagerInternals.h index 68873be594d4..ddc58ffb6969 100644 --- a/include/clang/Basic/SourceManagerInternals.h +++ b/include/clang/Basic/SourceManagerInternals.h @@ -79,7 +79,7 @@ inline bool operator<(unsigned Offset, const LineEntry &E) { /// Used to hold and unique data used to represent \#line information. class LineTableInfo { - /// Map used to assign unique IDs to filenames in \#line directives. + /// Map used to assign unique IDs to filenames in \#line directives. /// /// This allows us to unique the filenames that /// frequently reoccur and reference them with indices. FilenameIDs holds diff --git a/include/clang/Basic/Specifiers.h b/include/clang/Basic/Specifiers.h index 303b77e44805..cd8213f6cfd4 100644 --- a/include/clang/Basic/Specifiers.h +++ b/include/clang/Basic/Specifiers.h @@ -28,14 +28,14 @@ namespace clang { TSW_long, TSW_longlong }; - + /// Specifies the signedness of a type, e.g., signed or unsigned. enum TypeSpecifierSign { TSS_unspecified, TSS_signed, TSS_unsigned }; - + enum TypeSpecifiersPipe { TSP_unspecified, TSP_pipe @@ -134,7 +134,7 @@ namespace clang { /// An Objective-C property is a logical field of an Objective-C /// object which is read and written via Objective-C method calls. OK_ObjCProperty, - + /// An Objective-C array/dictionary subscripting which reads an /// object or writes at the subscripted array/dictionary element via /// Objective-C method calls. diff --git a/include/clang/Basic/StmtNodes.td b/include/clang/Basic/StmtNodes.td index 506da0720338..1517d741cb3c 100644 --- a/include/clang/Basic/StmtNodes.td +++ b/include/clang/Basic/StmtNodes.td @@ -187,7 +187,7 @@ def TypoExpr : DStmt<Expr>; // Microsoft Extensions. def MSPropertyRefExpr : DStmt<Expr>; def MSPropertySubscriptExpr : DStmt<Expr>; -def CXXUuidofExpr : DStmt<Expr>; +def CXXUuidofExpr : DStmt<Expr>; def SEHTryStmt : Stmt; def SEHExceptStmt : Stmt; def SEHFinallyStmt : Stmt; diff --git a/include/clang/Basic/TargetInfo.h b/include/clang/Basic/TargetInfo.h index ec5c59b23906..958b9106bc99 100644 --- a/include/clang/Basic/TargetInfo.h +++ b/include/clang/Basic/TargetInfo.h @@ -1139,7 +1139,8 @@ public: bool isSEHTrySupported() const { return getTriple().isOSWindows() && (getTriple().getArch() == llvm::Triple::x86 || - getTriple().getArch() == llvm::Triple::x86_64); + getTriple().getArch() == llvm::Triple::x86_64 || + getTriple().getArch() == llvm::Triple::aarch64); } /// Return true if {|} are normal characters in the asm string. diff --git a/include/clang/Basic/TemplateKinds.h b/include/clang/Basic/TemplateKinds.h index 3b68cba73655..a0bc362e7a44 100644 --- a/include/clang/Basic/TemplateKinds.h +++ b/include/clang/Basic/TemplateKinds.h @@ -31,7 +31,7 @@ enum TemplateNameKind { /// The name refers to a variable template whose specialization produces a /// variable. TNK_Var_template, - /// The name refers to a dependent template name: + /// The name refers to a dependent template name: /// \code /// template<typename MetaFun, typename T1, typename T2> struct apply2 { /// typedef typename MetaFun::template apply<T1, T2>::type type; @@ -39,7 +39,7 @@ enum TemplateNameKind { /// \endcode /// /// Here, "apply" is a dependent template name within the typename - /// specifier in the typedef. "apply" is a nested template, and + /// specifier in the typedef. "apply" is a nested template, and /// whether the template name is assumed to refer to a type template or a /// function template depends on the context in which the template /// name occurs. diff --git a/include/clang/Basic/arm_neon.td b/include/clang/Basic/arm_neon.td index d405aac10650..c35336166c39 100644 --- a/include/clang/Basic/arm_neon.td +++ b/include/clang/Basic/arm_neon.td @@ -772,9 +772,9 @@ def RSHRN_HIGH_N : IOpInst<"vrshrn_high_n", "hmdi", "HsHiHlHUsHUiHUl", OP_NARROW_HI>; def QRSHRUN_HIGH_N : SOpInst<"vqrshrun_high_n", "hmdi", "HsHiHl", OP_NARROW_HI>; -def QSHRN_HIGH_N : SOpInst<"vqshrn_high_n", "hmdi", +def QSHRN_HIGH_N : SOpInst<"vqshrn_high_n", "hmdi", "HsHiHlHUsHUiHUl", OP_NARROW_HI>; -def QRSHRN_HIGH_N : SOpInst<"vqrshrn_high_n", "hmdi", +def QRSHRN_HIGH_N : SOpInst<"vqrshrn_high_n", "hmdi", "HsHiHlHUsHUiHUl", OP_NARROW_HI>; } @@ -927,7 +927,7 @@ def VMINV : SInst<"vminv", "sd", "csifUcUsUiQcQsQiQUcQUsQUiQfQd">; def VADDV : SInst<"vaddv", "sd", "csifUcUsUiQcQsQiQUcQUsQUiQfQdQlQUl">; def FMAXNMV : SInst<"vmaxnmv", "sd", "fQfQd">; def FMINNMV : SInst<"vminnmv", "sd", "fQfQd">; - + //////////////////////////////////////////////////////////////////////////////// // Newly added Vector Extract for f64 def VEXT_A64 : WInst<"vext", "dddi", "dQdPlQPl">; diff --git a/include/clang/Basic/arm_neon_incl.td b/include/clang/Basic/arm_neon_incl.td index 46708a52aa3a..5f3aa6fc0221 100644 --- a/include/clang/Basic/arm_neon_incl.td +++ b/include/clang/Basic/arm_neon_incl.td @@ -9,7 +9,7 @@ // // This file defines data structures shared by arm_neon.td and arm_fp16.td. // It constains base operation classes, operations, instructions, instruction -// modifiers, etc. +// modifiers, etc. // //===----------------------------------------------------------------------===// // diff --git a/include/clang/Driver/CC1Options.td b/include/clang/Driver/CC1Options.td index 7cb9724a57e1..672231e70fad 100644 --- a/include/clang/Driver/CC1Options.td +++ b/include/clang/Driver/CC1Options.td @@ -87,16 +87,16 @@ def analyzer_viz_egraph_ubigraph : Flag<["-"], "analyzer-viz-egraph-ubigraph">, def analyzer_inline_max_stack_depth : Separate<["-"], "analyzer-inline-max-stack-depth">, HelpText<"Bound on stack depth while inlining (4 by default)">; -def analyzer_inline_max_stack_depth_EQ : Joined<["-"], "analyzer-inline-max-stack-depth=">, +def analyzer_inline_max_stack_depth_EQ : Joined<["-"], "analyzer-inline-max-stack-depth=">, Alias<analyzer_inline_max_stack_depth>; - + def analyzer_inlining_mode : Separate<["-"], "analyzer-inlining-mode">, HelpText<"Specify the function selection heuristic used during inlining">; def analyzer_inlining_mode_EQ : Joined<["-"], "analyzer-inlining-mode=">, Alias<analyzer_inlining_mode>; def analyzer_disable_retry_exhausted : Flag<["-"], "analyzer-disable-retry-exhausted">, HelpText<"Do not re-analyze paths leading to exhausted nodes with a different strategy (may decrease code coverage)">; - + def analyzer_max_loop : Separate<["-"], "analyzer-max-loop">, HelpText<"The maximum number of times the analyzer will go through a loop">; def analyzer_stats : Flag<["-"], "analyzer-stats">, @@ -815,7 +815,7 @@ def fopenmp_is_device : Flag<["-"], "fopenmp-is-device">, HelpText<"Generate code only for an OpenMP target device.">; def fopenmp_host_ir_file_path : Separate<["-"], "fopenmp-host-ir-file-path">, HelpText<"Path to the IR file produced by the frontend for the host.">; - + } // let Flags = [CC1Option] diff --git a/include/clang/Driver/Driver.h b/include/clang/Driver/Driver.h index 017248c3690f..b7b802221180 100644 --- a/include/clang/Driver/Driver.h +++ b/include/clang/Driver/Driver.h @@ -256,7 +256,7 @@ private: llvm::opt::DerivedArgList * TranslateInputArgs(const llvm::opt::InputArgList &Args) const; - // getFinalPhase - Determine which compilation mode we are in and record + // getFinalPhase - Determine which compilation mode we are in and record // which option we used to determine the final phase. phases::ID getFinalPhase(const llvm::opt::DerivedArgList &DAL, llvm::opt::Arg **FinalPhaseArg = nullptr) const; @@ -365,12 +365,12 @@ public: llvm::opt::InputArgList ParseArgStrings(ArrayRef<const char *> Args, bool &ContainsError); - /// BuildInputs - Construct the list of inputs and their types from + /// BuildInputs - Construct the list of inputs and their types from /// the given arguments. /// /// \param TC - The default host tool chain. /// \param Args - The input arguments. - /// \param Inputs - The list to store the resulting compilation + /// \param Inputs - The list to store the resulting compilation /// inputs onto. void BuildInputs(const ToolChain &TC, llvm::opt::DerivedArgList &Args, InputList &Inputs) const; @@ -493,7 +493,7 @@ public: /// \param JA - The action of interest. /// \param BaseInput - The original input file that this action was /// triggered by. - /// \param BoundArch - The bound architecture. + /// \param BoundArch - The bound architecture. /// \param AtTopLevel - Whether this is a "top-level" action. /// \param MultipleArchs - Whether multiple -arch options were supplied. /// \param NormalizedTriple - The normalized triple of the relevant target. @@ -502,7 +502,7 @@ public: bool AtTopLevel, bool MultipleArchs, StringRef NormalizedTriple) const; - /// GetTemporaryPath - Return the pathname of a temporary file to use + /// GetTemporaryPath - Return the pathname of a temporary file to use /// as part of compilation; the file will have the given prefix and suffix. /// /// GCC goes to extra lengths here to be a bit more robust. diff --git a/include/clang/Driver/ToolChain.h b/include/clang/Driver/ToolChain.h index addf7aa6a9c8..2f9c2c190e32 100644 --- a/include/clang/Driver/ToolChain.h +++ b/include/clang/Driver/ToolChain.h @@ -413,6 +413,11 @@ public: return llvm::DebuggerKind::GDB; } + /// Does this toolchain supports given debug info option or not. + virtual bool supportsDebugInfoOption(const llvm::opt::Arg *) const { + return true; + } + /// GetExceptionModel - Return the tool chain exception model. virtual llvm::ExceptionHandling GetExceptionModel(const llvm::opt::ArgList &Args) const; diff --git a/include/clang/Edit/Commit.h b/include/clang/Edit/Commit.h index a574b8ef4cd2..d6eb6cd84f93 100644 --- a/include/clang/Edit/Commit.h +++ b/include/clang/Edit/Commit.h @@ -57,7 +57,7 @@ private: bool IsCommitable = true; SmallVector<Edit, 8> CachedEdits; - + llvm::BumpPtrAllocator StrAlloc; public: diff --git a/include/clang/Edit/EditedSource.h b/include/clang/Edit/EditedSource.h index 3d33688f5f73..52873c3c3841 100644 --- a/include/clang/Edit/EditedSource.h +++ b/include/clang/Edit/EditedSource.h @@ -85,7 +85,7 @@ public: bool canInsertInOffset(SourceLocation OrigLoc, FileOffset Offs); bool commit(const Commit &commit); - + void applyRewrites(EditsReceiver &receiver, bool adjustRemovals = true); void clearRewrites(); diff --git a/include/clang/Edit/Rewriters.h b/include/clang/Edit/Rewriters.h index 980ed1d3363f..8338d71b3e52 100644 --- a/include/clang/Edit/Rewriters.h +++ b/include/clang/Edit/Rewriters.h @@ -29,7 +29,7 @@ bool rewriteObjCRedundantCallWithLiteral(const ObjCMessageExpr *Msg, bool rewriteToObjCLiteralSyntax(const ObjCMessageExpr *Msg, const NSAPI &NS, Commit &commit, const ParentMap *PMap); - + bool rewriteToObjCSubscriptSyntax(const ObjCMessageExpr *Msg, const NSAPI &NS, Commit &commit); diff --git a/include/clang/Frontend/ASTUnit.h b/include/clang/Frontend/ASTUnit.h index 9f529ba0e0e8..ba145965462f 100644 --- a/include/clang/Frontend/ASTUnit.h +++ b/include/clang/Frontend/ASTUnit.h @@ -159,7 +159,7 @@ private: /// Whether the ASTUnit should delete the remapped buffers. bool OwnsRemappedFileBuffers = true; - + /// Track the top-level decls which appeared in an ASTUnit which was loaded /// from a source file. // @@ -176,7 +176,7 @@ private: /// Map from FileID to the file-level declarations that it contains. /// The files and decls are only local (and non-preamble) ones. FileDeclsTy FileDecls; - + /// The name of the original source file used to generate this ASTUnit. std::string OriginalSourceFile; @@ -197,7 +197,7 @@ private: /// Diagnostics that come from the driver are retained from one parse to /// the next. unsigned NumStoredDiagnosticsFromDriver = 0; - + /// Counter that determines when we want to try building a /// precompiled preamble. /// @@ -236,7 +236,7 @@ private: /// A list of the serialization ID numbers for each of the top-level /// declarations parsed within the precompiled preamble. std::vector<serialization::DeclID> TopLevelDeclsInPreamble; - + /// Whether we should be caching code-completion results. bool ShouldCacheCodeCompletionResults : 1; @@ -247,7 +247,7 @@ private: /// True if non-system source files should be treated as volatile /// (likely to change while trying to use them). bool UserFilesAreVolatile : 1; - + static void ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> Diags, ASTUnit &AST, bool CaptureDiagnostics); @@ -265,7 +265,7 @@ public: /// The code-completion string corresponding to this completion /// result. CodeCompletionString *Completion; - + /// A bitmask that indicates which code-completion contexts should /// contain this completion result. /// @@ -274,20 +274,20 @@ public: /// bit, shift 1 by that number of bits. Many completions can occur in /// several different contexts. uint64_t ShowInContexts; - + /// The priority given to this code-completion result. unsigned Priority; - - /// The libclang cursor kind corresponding to this code-completion + + /// The libclang cursor kind corresponding to this code-completion /// result. CXCursorKind Kind; - + /// The availability of this code-completion result. CXAvailabilityKind Availability; - + /// The simplified type class for a non-macro completion result. SimplifiedTypeClass TypeClass; - + /// The type of a non-macro completion result, stored as a unique /// integer used by the string map of cached completion types. /// @@ -296,13 +296,13 @@ public: /// for more information. unsigned Type; }; - + /// Retrieve the mapping from formatted type names to unique type /// identifiers. llvm::StringMap<unsigned> &getCachedCompletionTypes() { - return CachedCompletionTypes; + return CachedCompletionTypes; } - + /// Retrieve the allocator used to cache global code completions. std::shared_ptr<GlobalCodeCompletionAllocator> getCachedCompletionAllocator() { @@ -324,29 +324,29 @@ private: /// The set of cached code-completion results. std::vector<CachedCodeCompletionResult> CachedCompletionResults; - + /// A mapping from the formatted type name to a unique number for that /// type, which is used for type equality comparisons. llvm::StringMap<unsigned> CachedCompletionTypes; - - /// A string hash of the top-level declaration and macro definition + + /// A string hash of the top-level declaration and macro definition /// names processed the last time that we reparsed the file. /// - /// This hash value is used to determine when we need to refresh the + /// This hash value is used to determine when we need to refresh the /// global code-completion cache. unsigned CompletionCacheTopLevelHashValue = 0; - /// A string hash of the top-level declaration and macro definition + /// A string hash of the top-level declaration and macro definition /// names processed the last time that we reparsed the precompiled preamble. /// - /// This hash value is used to determine when we need to refresh the + /// This hash value is used to determine when we need to refresh the /// global code-completion cache after a rebuild of the precompiled preamble. unsigned PreambleTopLevelHashValue = 0; /// The current hash value for the top-level declaration and macro /// definition names unsigned CurrentTopLevelHashValue = 0; - + /// Bit used by CIndex to mark when a translation unit may be in an /// inconsistent state, and is not safe to free. unsigned UnsafeToFree : 1; @@ -357,10 +357,10 @@ private: /// Cache any "global" code-completion results, so that we can avoid /// recomputing them with each completion. void CacheCodeCompletionResults(); - - /// Clear out and deallocate + + /// Clear out and deallocate void ClearCachedCompletionResults(); - + explicit ASTUnit(bool MainFileIsAST); bool Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps, @@ -402,9 +402,9 @@ public: class ConcurrencyCheck { ASTUnit &Self; - + public: - explicit ConcurrencyCheck(ASTUnit &Self) : Self(Self) { + explicit ConcurrencyCheck(ASTUnit &Self) : Self(Self) { Self.ConcurrencyCheckValue.start(); } @@ -424,7 +424,7 @@ public: const DiagnosticsEngine &getDiagnostics() const { return *Diagnostics; } DiagnosticsEngine &getDiagnostics() { return *Diagnostics; } - + const SourceManager &getSourceManager() const { return *SourceMgr; } SourceManager &getSourceManager() { return *SourceMgr; } @@ -449,7 +449,7 @@ public: bool hasSema() const { return (bool)TheSema; } - Sema &getSema() const { + Sema &getSema() const { assert(TheSema && "ASTUnit does not have a Sema object!"); return *TheSema; } @@ -463,12 +463,12 @@ public: assert(HSOpts && "ASTUnit does not have header search options"); return *HSOpts; } - + const PreprocessorOptions &getPreprocessorOpts() const { assert(PPOpts && "ASTUnit does not have preprocessor options"); return *PPOpts; } - + const FileManager &getFileManager() const { return *FileMgr; } FileManager &getFileManager() { return *FileMgr; } @@ -529,7 +529,7 @@ public: /// Get the decls that are contained in a file in the Offset/Length /// range. \p Length can be 0 to indicate a point at \p Offset instead of - /// a range. + /// a range. void findFileRegionDecls(FileID File, unsigned Offset, unsigned Length, SmallVectorImpl<Decl *> &Decls); @@ -575,25 +575,25 @@ public: return SourceRange(mapLocationToPreamble(R.getBegin()), mapLocationToPreamble(R.getEnd())); } - + // Retrieve the diagnostics associated with this AST using stored_diag_iterator = StoredDiagnostic *; using stored_diag_const_iterator = const StoredDiagnostic *; - stored_diag_const_iterator stored_diag_begin() const { - return StoredDiagnostics.begin(); + stored_diag_const_iterator stored_diag_begin() const { + return StoredDiagnostics.begin(); } - stored_diag_iterator stored_diag_begin() { - return StoredDiagnostics.begin(); + stored_diag_iterator stored_diag_begin() { + return StoredDiagnostics.begin(); } - stored_diag_const_iterator stored_diag_end() const { - return StoredDiagnostics.end(); + stored_diag_const_iterator stored_diag_end() const { + return StoredDiagnostics.end(); } - stored_diag_iterator stored_diag_end() { - return StoredDiagnostics.end(); + stored_diag_iterator stored_diag_end() { + return StoredDiagnostics.end(); } unsigned stored_diag_size() const { return StoredDiagnostics.size(); } @@ -601,12 +601,12 @@ public: stored_diag_iterator stored_diag_afterDriver_begin() { if (NumStoredDiagnosticsFromDriver > StoredDiagnostics.size()) NumStoredDiagnosticsFromDriver = 0; - return StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver; + return StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver; } using cached_completion_iterator = std::vector<CachedCodeCompletionResult>::iterator; - + cached_completion_iterator cached_completion_begin() { return CachedCompletionResults.begin(); } @@ -615,8 +615,8 @@ public: return CachedCompletionResults.end(); } - unsigned cached_completion_size() const { - return CachedCompletionResults.size(); + unsigned cached_completion_size() const { + return CachedCompletionResults.size(); } /// Returns an iterator range for the local preprocessing entities @@ -712,7 +712,7 @@ private: public: /// Create an ASTUnit from a source file, via a CompilerInvocation - /// object, by invoking the optionally provided ASTFrontendAction. + /// object, by invoking the optionally provided ASTFrontendAction. /// /// \param CI - The compiler invocation to use; it must have exactly one input /// source file. The ASTUnit takes ownership of the CompilerInvocation object. @@ -854,10 +854,10 @@ public: /// /// \param Column The column at which code completion will occur. /// - /// \param IncludeMacros Whether to include macros in the code-completion + /// \param IncludeMacros Whether to include macros in the code-completion /// results. /// - /// \param IncludeCodePatterns Whether to include code patterns (such as a + /// \param IncludeCodePatterns Whether to include code patterns (such as a /// for loop) in the code-completion results. /// /// \param IncludeBriefComments Whether to include brief documentation within diff --git a/include/clang/Frontend/CompilerInstance.h b/include/clang/Frontend/CompilerInstance.h index 977d1b2ed65f..818c733982d9 100644 --- a/include/clang/Frontend/CompilerInstance.h +++ b/include/clang/Frontend/CompilerInstance.h @@ -144,9 +144,9 @@ class CompilerInstance : public ModuleLoader { bool DeleteBuiltModules = true; /// The location of the module-import keyword for the last module - /// import. + /// import. SourceLocation LastModuleImportLoc; - + /// The result of the last module import. /// ModuleLoadResult LastModuleImportResult; @@ -246,7 +246,7 @@ public: /// Indicates whether we should (re)build the global module index. bool shouldBuildGlobalModuleIndex() const; - + /// Set the flag indicating whether we should (re)build the global /// module index. void setBuildGlobalModuleIndex(bool Build) { @@ -350,7 +350,7 @@ public: void setDiagnostics(DiagnosticsEngine *Value); DiagnosticConsumer &getDiagnosticClient() const { - assert(Diagnostics && Diagnostics->getClient() && + assert(Diagnostics && Diagnostics->getClient() && "Compiler instance has no diagnostic client!"); return *Diagnostics->getClient(); } @@ -409,7 +409,7 @@ public: assert(FileMgr && "Compiler instance has no file manager!"); return *FileMgr; } - + void resetAndLeakFileManager() { BuryPointer(FileMgr.get()); FileMgr.resetWithoutRelease(); @@ -429,7 +429,7 @@ public: assert(SourceMgr && "Compiler instance has no source manager!"); return *SourceMgr; } - + void resetAndLeakSourceManager() { BuryPointer(SourceMgr.get()); SourceMgr.resetWithoutRelease(); @@ -469,7 +469,7 @@ public: assert(Context && "Compiler instance has no AST context!"); return *Context; } - + void resetAndLeakASTContext() { BuryPointer(Context.get()); Context.resetWithoutRelease(); @@ -481,7 +481,7 @@ public: /// Replace the current Sema; the compiler instance takes ownership /// of S. void setSema(Sema *S); - + /// } /// @name ASTConsumer /// { @@ -506,7 +506,7 @@ public: /// { bool hasSema() const { return (bool)TheSema; } - Sema &getSema() const { + Sema &getSema() const { assert(TheSema && "Compiler instance has no Sema object!"); return *TheSema; } @@ -613,7 +613,7 @@ public: /// attached to (and, then, owned by) the DiagnosticsEngine inside this AST /// unit. /// - /// \param ShouldOwnClient If Client is non-NULL, specifies whether + /// \param ShouldOwnClient If Client is non-NULL, specifies whether /// the diagnostic object should take ownership of the client. void createDiagnostics(DiagnosticConsumer *Client = nullptr, bool ShouldOwnClient = true); @@ -693,7 +693,7 @@ public: /// Create the Sema object to be used for parsing. void createSema(TranslationUnitKind TUKind, CodeCompleteConsumer *CompletionConsumer); - + /// Create the frontend timer and replace any existing one with it. void createFrontendTimer(); diff --git a/include/clang/Frontend/CompilerInvocation.h b/include/clang/Frontend/CompilerInvocation.h index 3d302051d298..1d421f09fdcc 100644 --- a/include/clang/Frontend/CompilerInvocation.h +++ b/include/clang/Frontend/CompilerInvocation.h @@ -106,7 +106,7 @@ public: return *PreprocessorOpts; } }; - + /// Helper class for holding the data necessary to invoke the compiler. /// /// This class is designed to represent an abstract "invocation" of the @@ -117,7 +117,7 @@ class CompilerInvocation : public CompilerInvocationBase { AnalyzerOptionsRef AnalyzerOpts; MigratorOptions MigratorOpts; - + /// Options controlling IRgen and the backend. CodeGenOptions CodeGenOpts; @@ -172,11 +172,11 @@ public: static void setLangDefaults(LangOptions &Opts, InputKind IK, const llvm::Triple &T, PreprocessorOptions &PPOpts, LangStandard::Kind LangStd = LangStandard::lang_unspecified); - - /// Retrieve a module hash string that is suitable for uniquely + + /// Retrieve a module hash string that is suitable for uniquely /// identifying the conditions under which the module was built. std::string getModuleHash() const; - + /// @} /// @name Option Subgroups /// @{ @@ -185,7 +185,7 @@ public: MigratorOptions &getMigratorOpts() { return MigratorOpts; } const MigratorOptions &getMigratorOpts() const { return MigratorOpts; } - + CodeGenOptions &getCodeGenOpts() { return CodeGenOpts; } const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; } diff --git a/include/clang/Frontend/DiagnosticRenderer.h b/include/clang/Frontend/DiagnosticRenderer.h index 191d32accf2f..3bbf37946d0b 100644 --- a/include/clang/Frontend/DiagnosticRenderer.h +++ b/include/clang/Frontend/DiagnosticRenderer.h @@ -32,7 +32,7 @@ class SourceManager; using DiagOrStoredDiag = llvm::PointerUnion<const Diagnostic *, const StoredDiagnostic *>; - + /// Class to encapsulate the logic for formatting a diagnostic message. /// /// Actual "printing" logic is implemented by subclasses. @@ -49,20 +49,20 @@ class DiagnosticRenderer { protected: const LangOptions &LangOpts; IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts; - + /// The location of the previous diagnostic if known. /// /// This will be invalid in cases where there is no (known) previous /// diagnostic location, or that location itself is invalid or comes from /// a different source manager than SM. SourceLocation LastLoc; - + /// The location of the last include whose stack was printed if known. /// /// Same restriction as LastLoc essentially, but tracking include stack /// root locations rather than diagnostic locations. SourceLocation LastIncludeLoc; - + /// The level of the last diagnostic emitted. /// /// The level of the last diagnostic emitted. Used to detect level changes @@ -71,7 +71,7 @@ protected: DiagnosticRenderer(const LangOptions &LangOpts, DiagnosticOptions *DiagOpts); - + virtual ~DiagnosticRenderer(); virtual void emitDiagnosticMessage(FullSourceLoc Loc, PresumedLoc PLoc, @@ -137,7 +137,7 @@ public: void emitStoredDiagnostic(StoredDiagnostic &Diag); }; - + /// Subclass of DiagnosticRender that turns all subdiagostics into explicit /// notes. It is up to subclasses to further define the behavior. class DiagnosticNoteRenderer : public DiagnosticRenderer { diff --git a/include/clang/Frontend/FrontendActions.h b/include/clang/Frontend/FrontendActions.h index 20f1b3e11bdb..54539a5b3cee 100644 --- a/include/clang/Frontend/FrontendActions.h +++ b/include/clang/Frontend/FrontendActions.h @@ -18,7 +18,7 @@ namespace clang { class Module; class FileEntry; - + //===----------------------------------------------------------------------===// // Custom Consumer Actions //===----------------------------------------------------------------------===// @@ -198,7 +198,7 @@ protected: class ASTMergeAction : public FrontendAction { /// The action that the merge action adapts. std::unique_ptr<FrontendAction> AdaptedAction; - + /// The set of AST files to merge. std::vector<std::string> ASTFiles; @@ -233,7 +233,7 @@ protected: bool usesPreprocessorOnly() const override { return true; } }; - + //===----------------------------------------------------------------------===// // Preprocessor Actions //===----------------------------------------------------------------------===// @@ -264,7 +264,7 @@ protected: bool hasPCHSupport() const override { return true; } }; - + } // end namespace clang #endif diff --git a/include/clang/Frontend/LayoutOverrideSource.h b/include/clang/Frontend/LayoutOverrideSource.h index 0b7f7dc7a7d6..28e3cf005b30 100644 --- a/include/clang/Frontend/LayoutOverrideSource.h +++ b/include/clang/Frontend/LayoutOverrideSource.h @@ -27,24 +27,24 @@ namespace clang { struct Layout { /// The size of the record. uint64_t Size; - + /// The alignment of the record. uint64_t Align; - + /// The offsets of the fields, in source order. SmallVector<uint64_t, 8> FieldOffsets; }; - + /// The set of layouts that will be overridden. llvm::StringMap<Layout> Layouts; - + public: /// Create a new AST source that overrides the layout of some /// set of record types. /// /// The file is the result of passing -fdump-record-layouts to a file. explicit LayoutOverrideSource(StringRef Filename); - + /// If this particular record type has an overridden layout, /// return that layout. bool @@ -54,7 +54,7 @@ namespace clang { llvm::DenseMap<const CXXRecordDecl *, CharUnits> &BaseOffsets, llvm::DenseMap<const CXXRecordDecl *, CharUnits> &VirtualBaseOffsets) override; - + /// Dump the overridden layouts. void dump(); }; diff --git a/include/clang/Frontend/LogDiagnosticPrinter.h b/include/clang/Frontend/LogDiagnosticPrinter.h index 98adf655fcf1..3286ecf2cdd3 100644 --- a/include/clang/Frontend/LogDiagnosticPrinter.h +++ b/include/clang/Frontend/LogDiagnosticPrinter.h @@ -23,22 +23,22 @@ class LogDiagnosticPrinter : public DiagnosticConsumer { struct DiagEntry { /// The primary message line of the diagnostic. std::string Message; - + /// The source file name, if available. std::string Filename; - + /// The source file line number, if available. unsigned Line; - + /// The source file column number, if available. unsigned Column; - + /// The ID of the diagnostic. unsigned DiagnosticID; /// The Option Flag for the diagnostic std::string WarningOption; - + /// The level of the diagnostic. DiagnosticsEngine::Level DiagnosticLevel; }; diff --git a/include/clang/Frontend/PCHContainerOperations.h b/include/clang/Frontend/PCHContainerOperations.h index f9a73508d700..7a12ebc862e7 100644 --- a/include/clang/Frontend/PCHContainerOperations.h +++ b/include/clang/Frontend/PCHContainerOperations.h @@ -34,12 +34,12 @@ struct PCHBuffer { llvm::SmallVector<char, 0> Data; bool IsComplete; }; - + /// This abstract interface provides operations for creating /// containers for serialized ASTs (precompiled headers and clang /// modules). class PCHContainerWriter { -public: +public: virtual ~PCHContainerWriter() = 0; virtual StringRef getFormat() const = 0; @@ -58,7 +58,7 @@ public: /// containers for serialized ASTs (precompiled headers and clang /// modules). class PCHContainerReader { -public: +public: virtual ~PCHContainerReader() = 0; /// Equivalent to the format passed to -fmodule-format= virtual StringRef getFormat() const = 0; @@ -102,7 +102,7 @@ public: } void registerReader(std::unique_ptr<PCHContainerReader> Reader) { Readers[Reader->getFormat()] = std::move(Reader); - } + } const PCHContainerWriter *getWriterOrNull(StringRef Format) { return Writers[Format].get(); } diff --git a/include/clang/Frontend/VerifyDiagnosticConsumer.h b/include/clang/Frontend/VerifyDiagnosticConsumer.h index 9d985bc4955f..f36970f1eb39 100644 --- a/include/clang/Frontend/VerifyDiagnosticConsumer.h +++ b/include/clang/Frontend/VerifyDiagnosticConsumer.h @@ -252,7 +252,7 @@ private: public: /// Create a new verifying diagnostic client, which will issue errors to - /// the currently-attached diagnostic client when a diagnostic does not match + /// the currently-attached diagnostic client when a diagnostic does not match /// what is expected (as indicated in the source file). VerifyDiagnosticConsumer(DiagnosticsEngine &Diags); ~VerifyDiagnosticConsumer() override; diff --git a/include/clang/Lex/CodeCompletionHandler.h b/include/clang/Lex/CodeCompletionHandler.h index be153cc1ad50..87089fd7d50b 100644 --- a/include/clang/Lex/CodeCompletionHandler.h +++ b/include/clang/Lex/CodeCompletionHandler.h @@ -18,13 +18,13 @@ namespace clang { class IdentifierInfo; class MacroInfo; - -/// Callback handler that receives notifications when performing code + +/// Callback handler that receives notifications when performing code /// completion within the preprocessor. class CodeCompletionHandler { public: virtual ~CodeCompletionHandler(); - + /// Callback invoked when performing code completion for a preprocessor /// directive. /// @@ -34,23 +34,23 @@ public: /// \param InConditional Whether we're inside a preprocessor conditional /// already. virtual void CodeCompleteDirective(bool InConditional) { } - + /// Callback invoked when performing code completion within a block of /// code that was excluded due to preprocessor conditionals. virtual void CodeCompleteInConditionalExclusion() { } - + /// Callback invoked when performing code completion in a context /// where the name of a macro is expected. /// /// \param IsDefinition Whether this is the definition of a macro, e.g., /// in a \#define. virtual void CodeCompleteMacroName(bool IsDefinition) { } - + /// Callback invoked when performing code completion in a preprocessor /// expression, such as the condition of an \#if or \#elif directive. virtual void CodeCompletePreprocessorExpression() { } - - /// Callback invoked when performing code completion inside a + + /// Callback invoked when performing code completion inside a /// function-like macro argument. /// /// There will be another callback invocation after the macro arguments are @@ -61,11 +61,11 @@ public: unsigned ArgumentIndex) { } /// Callback invoked when performing code completion in a part of the - /// file where we expect natural language, e.g., a comment, string, or + /// file where we expect natural language, e.g., a comment, string, or /// \#error directive. virtual void CodeCompleteNaturalLanguage() { } }; - + } #endif // LLVM_CLANG_LEX_CODECOMPLETIONHANDLER_H diff --git a/include/clang/Lex/DirectoryLookup.h b/include/clang/Lex/DirectoryLookup.h index 222ebf025ac0..55065b7d8547 100644 --- a/include/clang/Lex/DirectoryLookup.h +++ b/include/clang/Lex/DirectoryLookup.h @@ -24,7 +24,7 @@ class DirectoryEntry; class FileEntry; class HeaderSearch; class Module; - + /// DirectoryLookup - This class represents one entry in the search list that /// specifies the search order for directories in \#include directives. It /// represents either a directory, a framework, or a headermap. @@ -54,14 +54,14 @@ private: /// LookupType - This indicates whether this DirectoryLookup object is a /// normal directory, a framework, or a headermap. unsigned LookupType : 2; - + /// Whether this is a header map used when building a framework. unsigned IsIndexHeaderMap : 1; /// Whether we've performed an exhaustive search for module maps /// within the subdirectories of this directory. unsigned SearchedAllModuleMaps : 1; - + public: /// DirectoryLookup ctor - Note that this ctor *does not take ownership* of /// 'dir'. @@ -140,10 +140,10 @@ public: } /// Whether this header map is building a framework or not. - bool isIndexHeaderMap() const { - return isHeaderMap() && IsIndexHeaderMap; + bool isIndexHeaderMap() const { + return isHeaderMap() && IsIndexHeaderMap; } - + /// LookupFile - Lookup the specified file in this search path, returning it /// if it exists or returning null if not. /// diff --git a/include/clang/Lex/ExternalPreprocessorSource.h b/include/clang/Lex/ExternalPreprocessorSource.h index f34be682617c..d849bbd76188 100644 --- a/include/clang/Lex/ExternalPreprocessorSource.h +++ b/include/clang/Lex/ExternalPreprocessorSource.h @@ -19,18 +19,18 @@ namespace clang { class IdentifierInfo; class Module; -/// Abstract interface for external sources of preprocessor +/// Abstract interface for external sources of preprocessor /// information. /// -/// This abstract class allows an external sources (such as the \c ASTReader) +/// This abstract class allows an external sources (such as the \c ASTReader) /// to provide additional preprocessing information. class ExternalPreprocessorSource { public: virtual ~ExternalPreprocessorSource(); - + /// Read the set of macros defined by this external macro source. virtual void ReadDefinedMacros() = 0; - + /// Update an out-of-date identifier. virtual void updateOutOfDateIdentifier(IdentifierInfo &II) = 0; @@ -42,7 +42,7 @@ public: /// Map a module ID to a module. virtual Module *getModule(unsigned ModuleID) = 0; }; - + } #endif diff --git a/include/clang/Lex/HeaderSearch.h b/include/clang/Lex/HeaderSearch.h index b7147c54faac..6bb0f58f2db9 100644 --- a/include/clang/Lex/HeaderSearch.h +++ b/include/clang/Lex/HeaderSearch.h @@ -74,9 +74,9 @@ struct HeaderFileInfo { /// Whether this structure is considered to already have been /// "resolved", meaning that it was loaded from the external source. unsigned Resolved : 1; - + /// Whether this is a header inside a framework that is currently - /// being built. + /// being built. /// /// When a framework is being built, the headers have not yet been placed /// into the appropriate framework subdirectories, and therefore are @@ -86,7 +86,7 @@ struct HeaderFileInfo { /// Whether this file has been looked up as a header. unsigned IsValid : 1; - + /// The number of times the file has been included already. unsigned short NumIncludes = 0; @@ -110,9 +110,9 @@ struct HeaderFileInfo { /// If this header came from a framework include, this is the name /// of the framework. StringRef Framework; - + HeaderFileInfo() - : isImport(false), isPragmaOnce(false), DirInfo(SrcMgr::C_User), + : isImport(false), isPragmaOnce(false), DirInfo(SrcMgr::C_User), External(false), isModuleHeader(false), isCompilingModuleHeader(false), Resolved(false), IndexHeaderMapHeader(false), IsValid(false) {} @@ -124,7 +124,7 @@ struct HeaderFileInfo { /// Determine whether this is a non-default header file info, e.g., /// it corresponds to an actual header we've included or tried to include. bool isNonDefault() const { - return isImport || isPragmaOnce || NumIncludes || ControllingMacro || + return isImport || isPragmaOnce || NumIncludes || ControllingMacro || ControllingMacroID; } }; @@ -134,15 +134,15 @@ struct HeaderFileInfo { class ExternalHeaderFileInfoSource { public: virtual ~ExternalHeaderFileInfoSource(); - + /// Retrieve the header file information for the given file entry. /// /// \returns Header file information for the given file entry, with the - /// \c External bit set. If the file entry is not known, return a + /// \c External bit set. If the file entry is not known, return a /// default-constructed \c HeaderFileInfo. virtual HeaderFileInfo GetHeaderFileInfo(const FileEntry *FE) = 0; }; - + /// Encapsulates the information needed to find the file referenced /// by a \#include or \#include_next, (sub-)framework lookup, etc. class HeaderSearch { @@ -186,7 +186,7 @@ class HeaderSearch { /// The path to the module cache. std::string ModuleCachePath; - + /// All of the preprocessor-specific data about files that are /// included, indexed by the FileEntry's UID. mutable std::vector<HeaderFileInfo> FileInfo; @@ -232,7 +232,7 @@ class HeaderSearch { /// The mapping between modules and headers. mutable ModuleMap ModMap; - + /// Describes whether a given directory has a module map in it. llvm::DenseMap<const DirectoryEntry *, bool> DirectoryHasModuleMap; @@ -240,10 +240,10 @@ class HeaderSearch { /// whether they were valid or not. llvm::DenseMap<const FileEntry *, bool> LoadedModuleMaps; - /// Uniqued set of framework names, which is used to track which + /// Uniqued set of framework names, which is used to track which /// headers were included as framework headers. llvm::StringSet<llvm::BumpPtrAllocator> FrameworkNames; - + /// Entity used to resolve the identifier IDs of controlling /// macros into IdentifierInfo pointers, and keep the identifire up to date, /// as needed. @@ -251,7 +251,7 @@ class HeaderSearch { /// Entity used to look up stored header file information. ExternalHeaderFileInfoSource *ExternalSource = nullptr; - + // Various statistics we track for performance analysis. unsigned NumIncluded = 0; unsigned NumMultiIncludeFileOptzn = 0; @@ -269,7 +269,7 @@ public: /// Retrieve the header-search options with which this header search /// was initialized. HeaderSearchOptions &getHeaderSearchOpts() const { return *HSOpts; } - + FileManager &getFileMgr() const { return FileMgr; } DiagnosticsEngine &getDiags() const { return Diags; } @@ -306,7 +306,7 @@ public: /// Map the source include name to the dest include name. /// - /// The Source should include the angle brackets or quotes, the dest + /// The Source should include the angle brackets or quotes, the dest /// should not. This allows for distinction between <> and "" headers. void AddIncludeAlias(StringRef Source, StringRef Dest) { if (!IncludeAliases) @@ -332,7 +332,7 @@ public: void setModuleCachePath(StringRef CachePath) { ModuleCachePath = CachePath; } - + /// Retrieve the path to the module cache. StringRef getModuleCachePath() const { return ModuleCachePath; } @@ -340,7 +340,7 @@ public: void setDirectoryHasModuleMap(const DirectoryEntry* Dir) { DirectoryHasModuleMap[Dir] = true; } - + /// Forget everything we know about headers so far. void ClearFileInfo() { FileInfo.clear(); @@ -353,16 +353,16 @@ public: ExternalPreprocessorSource *getExternalLookup() const { return ExternalLookup; } - + /// Set the external source of header information. void SetExternalSource(ExternalHeaderFileInfoSource *ES) { ExternalSource = ES; } - + /// Set the target information for the header search, if not /// already known. void setTarget(const TargetInfo &Target); - + /// Given a "foo" or \<foo> reference, look up the indicated file, /// return null on failure. /// @@ -540,7 +540,7 @@ public: /// \c nullptr if none is found. const FileEntry *lookupModuleMapFile(const DirectoryEntry *Dir, bool IsFramework); - + void IncrementFrameworkLookupCount() { ++NumFrameworkLookups; } /// Determine whether there is a module map that may map the header @@ -556,7 +556,7 @@ public: /// header directories. bool hasModuleMap(StringRef Filename, const DirectoryEntry *Root, bool IsSystem); - + /// Retrieve the module that corresponds to the given file, if any. /// /// \param File The header that we wish to map to a module. @@ -617,7 +617,7 @@ private: /// frameworks. /// /// \returns The module, if found; otherwise, null. - Module *loadFrameworkModule(StringRef Name, + Module *loadFrameworkModule(StringRef Name, const DirectoryEntry *Dir, bool IsSystem); @@ -655,10 +655,10 @@ private: public: /// Retrieve the module map. ModuleMap &getModuleMap() { return ModMap; } - + /// Retrieve the module map. const ModuleMap &getModuleMap() const { return ModMap; } - + unsigned header_file_size() const { return FileInfo.size(); } /// Return the HeaderFileInfo structure for the specified FileEntry, @@ -722,7 +722,7 @@ public: bool *IsSystem = nullptr); void PrintStats(); - + size_t getTotalMemory() const; private: diff --git a/include/clang/Lex/HeaderSearchOptions.h b/include/clang/Lex/HeaderSearchOptions.h index 298179e91a6f..e5b52b30323f 100644 --- a/include/clang/Lex/HeaderSearchOptions.h +++ b/include/clang/Lex/HeaderSearchOptions.h @@ -14,7 +14,7 @@ #include "llvm/ADT/CachedHashString.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/StringRef.h" -#include <cstdint> +#include <cstdint> #include <string> #include <vector> #include <map> @@ -36,7 +36,7 @@ enum IncludeDirGroup { Angled, /// Like Angled, but marks header maps used when building frameworks. - IndexHeaderMap, + IndexHeaderMap, /// Like Angled, but marks system directories. System, @@ -70,7 +70,7 @@ public: std::string Path; frontend::IncludeDirGroup Group; unsigned IsFramework : 1; - + /// IgnoreSysRoot - This is false if an absolute path should be treated /// relative to the sysroot, or true if it should always be the absolute /// path. diff --git a/include/clang/Lex/LiteralSupport.h b/include/clang/Lex/LiteralSupport.h index 1b6bf6bcffb0..3843a5afd2b0 100644 --- a/include/clang/Lex/LiteralSupport.h +++ b/include/clang/Lex/LiteralSupport.h @@ -208,7 +208,7 @@ class StringLiteralParser { const LangOptions &Features; const TargetInfo &Target; DiagnosticsEngine *Diags; - + unsigned MaxTokenLength; unsigned SizeBound; unsigned CharByteWidth; @@ -230,7 +230,7 @@ public: ResultPtr(ResultBuf.data()), hadError(false), Pascal(false) { init(StringToks); } - + bool hadError; bool Pascal; diff --git a/include/clang/Lex/MacroArgs.h b/include/clang/Lex/MacroArgs.h index a202550da3b3..853eee2fd779 100644 --- a/include/clang/Lex/MacroArgs.h +++ b/include/clang/Lex/MacroArgs.h @@ -27,7 +27,7 @@ namespace clang { /// MacroArgs - An instance of this class captures information about /// the formal arguments specified to a function-like macro invocation. -class MacroArgs final +class MacroArgs final : private llvm::TrailingObjects<MacroArgs, Token> { friend TrailingObjects; @@ -43,7 +43,7 @@ class MacroArgs final /// if in strict mode and the C99 varargs macro had only a ... argument, this /// is false. bool VarargsElided; - + /// PreExpArgTokens - Pre-expanded tokens for arguments that need them. Empty /// if not yet computed. This includes the EOF marker at the end of the /// stream. @@ -115,7 +115,7 @@ public: /// Returns true if the macro was defined with a variadic (ellipsis) parameter /// AND was invoked with at least one token supplied as a variadic argument. /// - /// \code + /// \code /// #define F(a) a /// #define V(a, ...) __VA_OPT__(a) /// F() <-- returns false on this invocation. @@ -123,7 +123,7 @@ public: /// V(,) <-- returns false on this invocation. /// \endcode /// - + bool invokedWithVariadicArgument(const MacroInfo *const MI) const; /// StringifyArgument - Implement C99 6.10.3.2p2, converting a sequence of @@ -135,8 +135,8 @@ public: Preprocessor &PP, bool Charify, SourceLocation ExpansionLocStart, SourceLocation ExpansionLocEnd); - - + + /// deallocate - This should only be called by the Preprocessor when managing /// its freelist. MacroArgs *deallocate(); diff --git a/include/clang/Lex/MacroInfo.h b/include/clang/Lex/MacroInfo.h index 13e5313a9c30..0cc1cb92e67e 100644 --- a/include/clang/Lex/MacroInfo.h +++ b/include/clang/Lex/MacroInfo.h @@ -174,7 +174,7 @@ public: std::copy(List.begin(), List.end(), ParameterList); } - /// Parameters - The list of parameters for a function-like macro. This can + /// Parameters - The list of parameters for a function-like macro. This can /// be empty, for, e.g. "#define X()". using param_iterator = IdentifierInfo *const *; bool param_empty() const { return NumParameters == 0; } diff --git a/include/clang/Lex/ModuleLoader.h b/include/clang/Lex/ModuleLoader.h index a2766fa35984..05396dd20597 100644 --- a/include/clang/Lex/ModuleLoader.h +++ b/include/clang/Lex/ModuleLoader.h @@ -7,7 +7,7 @@ // //===----------------------------------------------------------------------===// // -// This file defines the ModuleLoader interface, which is responsible for +// This file defines the ModuleLoader interface, which is responsible for // loading named modules. // //===----------------------------------------------------------------------===// @@ -80,7 +80,7 @@ public: : BuildingModule(BuildingModule) {} virtual ~ModuleLoader(); - + /// Returns true if this instance is building a module. bool buildingModule() const { return BuildingModule; @@ -90,17 +90,17 @@ public: void setBuildingModule(bool BuildingModuleFlag) { BuildingModule = BuildingModuleFlag; } - + /// Attempt to load the given module. /// - /// This routine attempts to load the module described by the given + /// This routine attempts to load the module described by the given /// parameters. /// /// \param ImportLoc The location of the 'import' keyword. /// /// \param Path The identifiers (and their locations) of the module /// "path", e.g., "std.vector" would be split into "std" and "vector". - /// + /// /// \param Visibility The visibility provided for the names in the loaded /// module. /// @@ -108,7 +108,7 @@ public: /// implicitly, due to the presence of an inclusion directive. Otherwise, /// it is being loaded due to an import declaration. /// - /// \returns If successful, returns the loaded module. Otherwise, returns + /// \returns If successful, returns the loaded module. Otherwise, returns /// NULL to indicate that the module could not be loaded. virtual ModuleLoadResult loadModule(SourceLocation ImportLoc, ModuleIdPath Path, @@ -177,7 +177,7 @@ public: return false; } }; - + } // namespace clang #endif // LLVM_CLANG_LEX_MODULELOADER_H diff --git a/include/clang/Lex/ModuleMap.h b/include/clang/Lex/ModuleMap.h index 577f4008978e..aa519891c1ce 100644 --- a/include/clang/Lex/ModuleMap.h +++ b/include/clang/Lex/ModuleMap.h @@ -69,7 +69,7 @@ public: virtual void moduleMapAddUmbrellaHeader(FileManager *FileMgr, const FileEntry *Header) {} }; - + class ModuleMap { SourceManager &SourceMgr; DiagnosticsEngine &Diags; @@ -78,11 +78,11 @@ class ModuleMap { HeaderSearch &HeaderInfo; llvm::SmallVector<std::unique_ptr<ModuleMapCallbacks>, 1> Callbacks; - + /// The directory used for Clang-supplied, builtin include headers, /// such as "stdint.h". const DirectoryEntry *BuiltinIncludeDir = nullptr; - + /// Language options used to parse the module map itself. /// /// These are always simple C language options. @@ -285,7 +285,7 @@ private: /// /// \returns The resolved export declaration, which will have a NULL pointer /// if the export could not be resolved. - Module::ExportDecl + Module::ExportDecl resolveExport(Module *Mod, const Module::UnresolvedExportDecl &Unresolved, bool Complain) const; @@ -494,13 +494,13 @@ public: /// using direct (qualified) name lookup. /// /// \param Name The name of the module to look up. - /// + /// /// \param Context The module for which we will look for a submodule. If /// null, we will look for a top-level module. /// /// \returns The named submodule, if known; otherwose, returns null. Module *lookupModuleQualified(StringRef Name, Module *Context) const; - + /// Find a new module or submodule, or create it if it does not already /// exist. /// @@ -645,7 +645,7 @@ public: /// Marks this header as being excluded from the given module. void excludeHeader(Module *Mod, Module::Header Header); - /// Parse the given module map file, and record any modules we + /// Parse the given module map file, and record any modules we /// encounter. /// /// \param File The file to be parsed. @@ -672,13 +672,13 @@ public: /// Dump the contents of the module map, for debugging purposes. void dump(); - + using module_iterator = llvm::StringMap<Module *>::const_iterator; module_iterator module_begin() const { return Modules.begin(); } module_iterator module_end() const { return Modules.end(); } }; - + } // namespace clang #endif // LLVM_CLANG_LEX_MODULEMAP_H diff --git a/include/clang/Lex/PPCallbacks.h b/include/clang/Lex/PPCallbacks.h index eb85bda840af..45c2d18da6e2 100644 --- a/include/clang/Lex/PPCallbacks.h +++ b/include/clang/Lex/PPCallbacks.h @@ -66,10 +66,10 @@ public: /// Callback invoked whenever an inclusion directive results in a /// file-not-found error. /// - /// \param FileName The name of the file being included, as written in the + /// \param FileName The name of the file being included, as written in the /// source code. /// - /// \param RecoveryPath If this client indicates that it can recover from + /// \param RecoveryPath If this client indicates that it can recover from /// this missing file, the client should set this as an additional header /// search patch. /// @@ -84,13 +84,13 @@ public: /// any kind (\c \#include, \c \#import, etc.) has been processed, regardless /// of whether the inclusion will actually result in an inclusion. /// - /// \param HashLoc The location of the '#' that starts the inclusion + /// \param HashLoc The location of the '#' that starts the inclusion /// directive. /// - /// \param IncludeTok The token that indicates the kind of inclusion + /// \param IncludeTok The token that indicates the kind of inclusion /// directive, e.g., 'include' or 'import'. /// - /// \param FileName The name of the file being included, as written in the + /// \param FileName The name of the file being included, as written in the /// source code. /// /// \param IsAngled Whether the file name was enclosed in angle brackets; @@ -99,7 +99,7 @@ public: /// \param FilenameRange The character range of the quotes or angle brackets /// for the written file name. /// - /// \param File The actual file that may be included by this inclusion + /// \param File The actual file that may be included by this inclusion /// directive. /// /// \param SearchPath Contains the search path which was used to find the file @@ -222,7 +222,7 @@ public: /// Called when an OpenCL extension is either disabled or /// enabled with a pragma. - virtual void PragmaOpenCLExtension(SourceLocation NameLoc, + virtual void PragmaOpenCLExtension(SourceLocation NameLoc, const IdentifierInfo *Name, SourceLocation StateLoc, unsigned State) { } @@ -269,13 +269,13 @@ public: const MacroDefinition &MD, const MacroDirective *Undef) { } - + /// Hook called whenever the 'defined' operator is seen. /// \param MD The MacroDirective if the name was a macro, null otherwise. virtual void Defined(const Token &MacroNameTok, const MacroDefinition &MD, SourceRange Range) { } - + /// Hook called when a source range is skipped. /// \param Range The SourceRange that was skipped. The range begins at the /// \#if/\#else directive and ends after the \#endif/\#else directive. diff --git a/include/clang/Lex/PPConditionalDirectiveRecord.h b/include/clang/Lex/PPConditionalDirectiveRecord.h index a653b8339948..a2ccf1407f79 100644 --- a/include/clang/Lex/PPConditionalDirectiveRecord.h +++ b/include/clang/Lex/PPConditionalDirectiveRecord.h @@ -20,12 +20,12 @@ #include <vector> namespace clang { - + /// Records preprocessor conditional directive regions and allows /// querying in which region source locations belong to. class PPConditionalDirectiveRecord : public PPCallbacks { SourceManager &SourceMgr; - + SmallVector<SourceLocation, 6> CondDirectiveStack; class CondDirectiveLoc { diff --git a/include/clang/Lex/PTHLexer.h b/include/clang/Lex/PTHLexer.h index f122a008e4aa..0b84df1434ae 100644 --- a/include/clang/Lex/PTHLexer.h +++ b/include/clang/Lex/PTHLexer.h @@ -49,7 +49,7 @@ class PTHLexer : public PreprocessorLexer { /// ReadToken - Used by PTHLexer to read tokens TokBuf. void ReadToken(Token &T); - + bool LexEndOfFile(Token &Result); /// PTHMgr - The PTHManager object that created this PTHLexer. diff --git a/include/clang/Lex/Pragma.h b/include/clang/Lex/Pragma.h index 9348388bc28c..4d74face5275 100644 --- a/include/clang/Lex/Pragma.h +++ b/include/clang/Lex/Pragma.h @@ -34,19 +34,19 @@ class Token; * The pragma was introduced via \#pragma. */ PIK_HashPragma, - + /** * The pragma was introduced via the C99 _Pragma(string-literal). */ PIK__Pragma, - + /** - * The pragma was introduced via the Microsoft + * The pragma was introduced via the Microsoft * __pragma(token-string). */ PIK___pragma }; - + /// PragmaHandler - Instances of this interface defined to handle the various /// pragmas that the language front-end uses. Each handler optionally has a /// name (e.g. "pack") and the HandlePragma method is invoked when a pragma with diff --git a/include/clang/Lex/PreprocessingRecord.h b/include/clang/Lex/PreprocessingRecord.h index 54e28a52f5b3..44d79d9b6229 100644 --- a/include/clang/Lex/PreprocessingRecord.h +++ b/include/clang/Lex/PreprocessingRecord.h @@ -66,13 +66,13 @@ class Token; /// A macro expansion. MacroExpansionKind, - + /// \defgroup Preprocessing directives /// @{ - + /// A macro definition. MacroDefinitionKind, - + /// An inclusion directive, such as \c \#include, \c /// \#import, or \c \#include_next. InclusionDirectiveKind, @@ -86,10 +86,10 @@ class Token; private: /// The kind of preprocessed entity that this object describes. EntityKind Kind; - + /// The source range that covers this preprocessed entity. SourceRange Range; - + protected: friend class PreprocessingRecord; @@ -99,8 +99,8 @@ class Token; public: /// Retrieve the kind of preprocessed entity stored in this object. EntityKind getKind() const { return Kind; } - - /// Retrieve the source range that covers this entire preprocessed + + /// Retrieve the source range that covers this entire preprocessed /// entity. SourceRange getSourceRange() const LLVM_READONLY { return Range; } @@ -108,7 +108,7 @@ class Token; /// entity. bool isInvalid() const { return Kind == InvalidKind; } - // Only allow allocation of preprocessed entities using the allocator + // Only allow allocation of preprocessed entities using the allocator // in PreprocessingRecord or by doing a placement new. void *operator new(size_t bytes, PreprocessingRecord &PR, unsigned alignment = 8) noexcept { @@ -130,15 +130,15 @@ class Token; void *operator new(size_t bytes) noexcept; void operator delete(void *data) noexcept; }; - + /// Records the presence of a preprocessor directive. class PreprocessingDirective : public PreprocessedEntity { public: - PreprocessingDirective(EntityKind Kind, SourceRange Range) + PreprocessingDirective(EntityKind Kind, SourceRange Range) : PreprocessedEntity(Kind, Range) {} - + // Implement isa/cast/dyncast/etc. - static bool classof(const PreprocessedEntity *PD) { + static bool classof(const PreprocessedEntity *PD) { return PD->getKind() >= FirstPreprocessingDirective && PD->getKind() <= LastPreprocessingDirective; } @@ -159,13 +159,13 @@ class Token; /// Retrieve the location of the macro name in the definition. SourceLocation getLocation() const { return getSourceRange().getBegin(); } - + // Implement isa/cast/dyncast/etc. static bool classof(const PreprocessedEntity *PE) { return PE->getKind() == MacroDefinitionKind; } }; - + /// Records the location of a macro expansion. class MacroExpansion : public PreprocessedEntity { /// The definition of this macro or the name of the macro if it is @@ -246,16 +246,16 @@ class Token; public: InclusionDirective(PreprocessingRecord &PPRec, - InclusionKind Kind, StringRef FileName, + InclusionKind Kind, StringRef FileName, bool InQuotes, bool ImportedModule, const FileEntry *File, SourceRange Range); - + /// Determine what kind of inclusion directive this is. InclusionKind getKind() const { return static_cast<InclusionKind>(Kind); } - + /// Retrieve the included file name as it was written in the source. StringRef getFileName() const { return FileName; } - + /// Determine whether the included file name was written in quotes; /// otherwise, it was written in angle brackets. bool wasInQuotes() const { return InQuotes; } @@ -263,23 +263,23 @@ class Token; /// Determine whether the inclusion directive was automatically /// turned into a module import. bool importedModule() const { return ImportedModule; } - + /// Retrieve the file entry for the actual file that was included /// by this directive. const FileEntry *getFile() const { return File; } - + // Implement isa/cast/dyncast/etc. static bool classof(const PreprocessedEntity *PE) { return PE->getKind() == InclusionDirectiveKind; } }; - + /// An abstract class that should be subclassed by any external source /// of preprocessing record entries. class ExternalPreprocessingRecordSource { public: virtual ~ExternalPreprocessingRecordSource(); - + /// Read a preallocated preprocessed entity from the external source. /// /// \returns null if an error occurred that prevented the preprocessed @@ -301,20 +301,20 @@ class Token; /// Read a preallocated skipped range from the external source. virtual SourceRange ReadSkippedRange(unsigned Index) = 0; }; - + /// A record of the steps taken while preprocessing a source file, - /// including the various preprocessing directives processed, macros + /// including the various preprocessing directives processed, macros /// expanded, etc. class PreprocessingRecord : public PPCallbacks { SourceManager &SourceMgr; - + /// Allocator used to store preprocessing objects. llvm::BumpPtrAllocator BumpAlloc; /// The set of preprocessed entities in this record, in order they /// were seen. std::vector<PreprocessedEntity *> PreprocessedEntities; - + /// The set of preprocessed entities in this record that have been /// loaded from external sources. /// @@ -362,7 +362,7 @@ class Token; /// Retrieve the loaded preprocessed entity at the given index. PreprocessedEntity *getLoadedPreprocessedEntity(unsigned Index); - + /// Determine the number of preprocessed entities that were /// loaded (or can be loaded) from an external source. unsigned getNumLoadedPreprocessedEntities() const { @@ -403,7 +403,7 @@ class Token; void *Allocate(unsigned Size, unsigned Align = 8) { return BumpAlloc.Allocate(Size, Align); } - + /// Deallocate memory in the preprocessing record. void Deallocate(void *Ptr) {} @@ -518,7 +518,7 @@ class Token; ensureSkippedRangesLoaded(); return SkippedRanges; } - + private: friend class ASTReader; friend class ASTWriter; diff --git a/include/clang/Lex/Preprocessor.h b/include/clang/Lex/Preprocessor.h index 4ec29fe8f331..e718f5b6bbd0 100644 --- a/include/clang/Lex/Preprocessor.h +++ b/include/clang/Lex/Preprocessor.h @@ -255,7 +255,7 @@ class Preprocessor { /// with this preprocessor. std::vector<CommentHandler *> CommentHandlers; - /// True if we want to ignore EOF token and continue later on (thus + /// True if we want to ignore EOF token and continue later on (thus /// avoid tearing the Lexer and etc. down). bool IncrementalProcessing = false; @@ -281,7 +281,7 @@ class Preprocessor { /// for preprocessing. SourceLocation CodeCompletionFileLoc; - /// The source location of the \c import contextual keyword we just + /// The source location of the \c import contextual keyword we just /// lexed, if any. SourceLocation ModuleImportLoc; @@ -294,7 +294,7 @@ class Preprocessor { /// Whether the module import expects an identifier next. Otherwise, /// it expects a '.' or ';'. bool ModuleImportExpectsIdentifier = false; - + /// The source location of the currently-active /// \#pragma clang arc_cf_code_audited begin. SourceLocation PragmaARCCFCodeAuditedLoc; @@ -814,7 +814,7 @@ public: /// Retrieve the preprocessor options used to initialize this /// preprocessor. PreprocessorOptions &getPreprocessorOpts() const { return *PPOpts; } - + DiagnosticsEngine &getDiagnostics() const { return *Diags; } void setDiagnostics(DiagnosticsEngine &D) { Diags = &D; } @@ -852,7 +852,7 @@ public: } /// True if we are currently preprocessing a #if or #elif directive - bool isParsingIfOrElifDirective() const { + bool isParsingIfOrElifDirective() const { return ParsingIfOrElifDirective; } @@ -1439,7 +1439,7 @@ public: void enableIncrementalProcessing(bool value = true) { IncrementalProcessing = value; } - + /// Specify the point at which code-completion will be performed. /// /// \param File the file in which code completion should occur. If @@ -1630,7 +1630,7 @@ public: } /// Plop the specified string into a scratch buffer and set the - /// specified token's location and length to it. + /// specified token's location and length to it. /// /// If specified, the source location provides a location of the expansion /// point of the token. @@ -1769,7 +1769,7 @@ public: void PoisonSEHIdentifiers(bool Poison = true); // Borland /// Callback invoked when the lexer reads an identifier and has - /// filled in the tokens IdentifierInfo member. + /// filled in the tokens IdentifierInfo member. /// /// This callback potentially macro expands it or turns it into a named /// token (like 'for'). @@ -1817,12 +1817,12 @@ public: /// Retrieves the module that we're currently building, if any. Module *getCurrentModule(); - + /// Allocate a new MacroInfo object with the provided SourceLocation. MacroInfo *AllocateMacroInfo(SourceLocation L); /// Turn the specified lexer token into a fully checked and spelled - /// filename, e.g. as an operand of \#include. + /// filename, e.g. as an operand of \#include. /// /// The caller is expected to provide a buffer that is large enough to hold /// the spelling of the filename, but is also expected to handle the case @@ -1846,7 +1846,7 @@ public: bool *IsMapped, bool SkipCache = false); /// Get the DirectoryLookup structure used to find the current - /// FileEntry, if CurLexer is non-null and if applicable. + /// FileEntry, if CurLexer is non-null and if applicable. /// /// This allows us to implement \#include_next and find directory-specific /// properties. @@ -1856,7 +1856,7 @@ public: bool isInPrimaryFile() const; /// Handle cases where the \#include name is expanded - /// from a macro as multiple tokens, which need to be glued together. + /// from a macro as multiple tokens, which need to be glued together. /// /// This occurs for code like: /// \code @@ -1939,7 +1939,7 @@ private: /// - # (stringization) is followed by a macro parameter /// \param MacroNameTok - Token that represents the macro name /// \param ImmediatelyAfterHeaderGuard - Macro follows an #ifdef header guard - /// + /// /// Either returns a pointer to a MacroInfo object OR emits a diagnostic and /// returns a nullptr if an invalid sequence of tokens is encountered. MacroInfo *ReadOptionalMacroParameterListAndBody( diff --git a/include/clang/Lex/PreprocessorLexer.h b/include/clang/Lex/PreprocessorLexer.h index bb02725b116f..b619f192f530 100644 --- a/include/clang/Lex/PreprocessorLexer.h +++ b/include/clang/Lex/PreprocessorLexer.h @@ -169,12 +169,12 @@ public: using conditional_iterator = SmallVectorImpl<PPConditionalInfo>::const_iterator; - conditional_iterator conditional_begin() const { - return ConditionalStack.begin(); + conditional_iterator conditional_begin() const { + return ConditionalStack.begin(); } - conditional_iterator conditional_end() const { - return ConditionalStack.end(); + conditional_iterator conditional_end() const { + return ConditionalStack.end(); } void setConditionalLevels(ArrayRef<PPConditionalInfo> CL) { diff --git a/include/clang/Lex/PreprocessorOptions.h b/include/clang/Lex/PreprocessorOptions.h index 3d7e5ab4a8dc..5134aeaa6a29 100644 --- a/include/clang/Lex/PreprocessorOptions.h +++ b/include/clang/Lex/PreprocessorOptions.h @@ -13,7 +13,7 @@ #include "clang/Basic/LLVM.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/StringSet.h" -#include <memory> +#include <memory> #include <set> #include <string> #include <utility> @@ -27,7 +27,7 @@ class MemoryBuffer; namespace clang { -/// Enumerate the kinds of standard library that +/// Enumerate the kinds of standard library that enum ObjCXXARCStandardLibraryKind { ARCXX_nolib, @@ -37,7 +37,7 @@ enum ObjCXXARCStandardLibraryKind { /// libstdc++ ARCXX_libstdcxx }; - + /// PreprocessorOptions - This class is used for passing the various options /// used in preprocessor initialization to InitializePreprocessor(). class PreprocessorOptions { @@ -136,15 +136,15 @@ public: /// the buffers associated with remapped files. /// /// This flag defaults to false; it can be set true only through direct - /// manipulation of the compiler invocation object, in cases where the + /// manipulation of the compiler invocation object, in cases where the /// compiler invocation and its buffers will be reused. bool RetainRemappedFileBuffers = false; - + /// The Objective-C++ ARC standard library that we should support, /// by providing appropriate definitions to retrofit the standard library /// with support for lifetime-qualified pointers. ObjCXXARCStandardLibraryKind ObjCXXARCStandardLibrary = ARCXX_nolib; - + /// Records the set of modules class FailedModulesSet { llvm::StringSet<> Failed; @@ -158,7 +158,7 @@ public: Failed.insert(module); } }; - + /// The set of modules that failed to build. /// /// This pointer will be shared among all of the compiler instances created @@ -185,7 +185,7 @@ public: RemappedFiles.clear(); RemappedFileBuffers.clear(); } - + /// Reset any options that are not considered when building a /// module. void resetNonModularOptions() { diff --git a/include/clang/Lex/Token.h b/include/clang/Lex/Token.h index 633e1d15697b..85bef728197d 100644 --- a/include/clang/Lex/Token.h +++ b/include/clang/Lex/Token.h @@ -73,7 +73,7 @@ public: enum TokenFlags { StartOfLine = 0x01, // At start of line or only after whitespace // (considering the line after macro expansion). - LeadingSpace = 0x02, // Whitespace exists before this token (considering + LeadingSpace = 0x02, // Whitespace exists before this token (considering // whitespace after macro expansion). DisableExpand = 0x04, // This identifier may never be macro expanded. NeedsCleaning = 0x08, // Contained an escaped newline or trigraph. diff --git a/include/clang/Lex/TokenConcatenation.h b/include/clang/Lex/TokenConcatenation.h index a2d98b0d473a..60c182b509a4 100644 --- a/include/clang/Lex/TokenConcatenation.h +++ b/include/clang/Lex/TokenConcatenation.h @@ -58,8 +58,8 @@ namespace clang { public: TokenConcatenation(Preprocessor &PP); - bool AvoidConcat(const Token &PrevPrevTok, - const Token &PrevTok, + bool AvoidConcat(const Token &PrevPrevTok, + const Token &PrevTok, const Token &Tok) const; private: diff --git a/include/clang/Lex/TokenLexer.h b/include/clang/Lex/TokenLexer.h index e616d497eec6..98935ad9c4fa 100644 --- a/include/clang/Lex/TokenLexer.h +++ b/include/clang/Lex/TokenLexer.h @@ -65,7 +65,7 @@ class TokenLexer { /// Source location pointing at the source location entry chunk that /// was reserved for the current macro expansion. SourceLocation MacroExpansionStart; - + /// The offset of the macro expansion in the /// "source location address space". unsigned MacroStartSLocOffset; diff --git a/include/clang/Lex/VariadicMacroSupport.h b/include/clang/Lex/VariadicMacroSupport.h index 55202ffc34d7..3a7a955953f4 100644 --- a/include/clang/Lex/VariadicMacroSupport.h +++ b/include/clang/Lex/VariadicMacroSupport.h @@ -71,10 +71,10 @@ namespace clang { class VAOptDefinitionContext { /// Contains all the locations of so far unmatched lparens. SmallVector<SourceLocation, 8> UnmatchedOpeningParens; - + const IdentifierInfo *const Ident__VA_OPT__; - - + + public: VAOptDefinitionContext(Preprocessor &PP) : Ident__VA_OPT__(PP.Ident__VA_OPT__) {} @@ -86,12 +86,12 @@ namespace clang { /// Returns true if we have seen the __VA_OPT__ and '(' but before having /// seen the matching ')'. bool isInVAOpt() const { return UnmatchedOpeningParens.size(); } - + /// Call this function as soon as you see __VA_OPT__ and '('. void sawVAOptFollowedByOpeningParens(const SourceLocation LParenLoc) { assert(!isInVAOpt() && "Must NOT be within VAOPT context to call this"); UnmatchedOpeningParens.push_back(LParenLoc); - + } SourceLocation getUnmatchedOpeningParenLoc() const { @@ -107,13 +107,13 @@ namespace clang { UnmatchedOpeningParens.pop_back(); return !UnmatchedOpeningParens.size(); } - + /// Call this function each time an lparen is seen. void sawOpeningParen(SourceLocation LParenLoc) { assert(isInVAOpt() && "Must be within VAOPT context to call this"); UnmatchedOpeningParens.push_back(LParenLoc); } - + }; /// A class for tracking whether we're inside a VA_OPT during a @@ -133,11 +133,11 @@ namespace clang { int NumOfTokensPriorToVAOpt = -1; unsigned LeadingSpaceForStringifiedToken : 1; - + unsigned StringifyBefore : 1; unsigned CharifyBefore : 1; - - + + bool hasStringifyBefore() const { assert(!isReset() && "Must only be called if the state has not been reset"); @@ -169,14 +169,14 @@ namespace clang { void sawHashOrHashAtBefore(const bool HasLeadingSpace, const bool IsHashAt) { - + StringifyBefore = !IsHashAt; CharifyBefore = IsHashAt; LeadingSpaceForStringifiedToken = HasLeadingSpace; } - - + + bool hasCharifyBefore() const { assert(!isReset() && "Must only be called if the state has not been reset"); @@ -185,13 +185,13 @@ namespace clang { bool hasStringifyOrCharifyBefore() const { return hasStringifyBefore() || hasCharifyBefore(); } - + unsigned int getNumberOfTokensPriorToVAOpt() const { assert(!isReset() && "Must only be called if the state has not been reset"); return NumOfTokensPriorToVAOpt; } - + bool getLeadingSpaceForStringifiedToken() const { assert(hasStringifyBefore() && "Must only be called if this has been marked for stringification"); @@ -219,7 +219,7 @@ namespace clang { using VAOptDefinitionContext::isInVAOpt; using VAOptDefinitionContext::sawClosingParen; using VAOptDefinitionContext::sawOpeningParen; - + }; } // end namespace clang diff --git a/include/clang/Parse/ParseAST.h b/include/clang/Parse/ParseAST.h index 34b04060346f..f6e78ac2ca56 100644 --- a/include/clang/Parse/ParseAST.h +++ b/include/clang/Parse/ParseAST.h @@ -42,7 +42,7 @@ namespace clang { CodeCompleteConsumer *CompletionConsumer = nullptr, bool SkipFunctionBodies = false); - /// Parse the main file known to the preprocessor, producing an + /// Parse the main file known to the preprocessor, producing an /// abstract syntax tree. void ParseAST(Sema &S, bool PrintStats = false, bool SkipFunctionBodies = false); diff --git a/include/clang/Parse/Parser.h b/include/clang/Parse/Parser.h index d7b83803af20..69bf88a371db 100644 --- a/include/clang/Parse/Parser.h +++ b/include/clang/Parse/Parser.h @@ -132,7 +132,7 @@ class Parser : public CodeCompletionHandler { /// Identifier for "unavailable". IdentifierInfo *Ident_unavailable; - + /// Identifier for "message". IdentifierInfo *Ident_message; @@ -1196,7 +1196,7 @@ private: /// method will be stored so that they can be reintroduced into /// scope at the appropriate times. SmallVector<LateParsedDefaultArgument, 8> DefaultArgs; - + /// The set of tokens that make up an exception-specification that /// has not yet been parsed. CachedTokens *ExceptionSpecTokens; @@ -1225,7 +1225,7 @@ private: /// C++ class, its method declarations that contain parts that won't be /// parsed until after the definition is completed (C++ [class.mem]p2), /// the method declarations and possibly attached inline definitions - /// will be stored here with the tokens that will be parsed to create those + /// will be stored here with the tokens that will be parsed to create those /// entities. typedef SmallVector<LateParsedDeclaration*,2> LateParsedDeclarationsContainer; @@ -1653,6 +1653,7 @@ private: /// ParenParseOption - Control what ParseParenExpression will parse. enum ParenParseOption { SimpleExpr, // Only parse '(' expression ')' + FoldExpr, // Also allow fold-expression <anything> CompoundStmt, // Also allow '(' compound-statement ')' CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}' CastExpr // Also allow '(' type-name ')' <anything> @@ -1673,7 +1674,7 @@ private: ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral = false); ExprResult ParseGenericSelectionExpression(); - + ExprResult ParseObjCBoolLiteral(); ExprResult ParseFoldExpression(ExprResult LHS, BalancedDelimiterTracker &T); @@ -1835,7 +1836,7 @@ private: SourceLocation LBracloc, SourceLocation SuperLoc, ParsedType ReceiverType, Expr *ReceiverExpr); bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr); - + //===--------------------------------------------------------------------===// // C99 6.8: Statements and Blocks. @@ -2064,7 +2065,7 @@ private: bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS, const ParsedTemplateInfo &TemplateInfo, - AccessSpecifier AS, DeclSpecContext DSC, + AccessSpecifier AS, DeclSpecContext DSC, ParsedAttributesWithRange &Attrs); DeclSpecContext getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context); @@ -2192,7 +2193,7 @@ private: /// isCXXFunctionDeclarator - Disambiguates between a function declarator or /// a constructor-style initializer, when parsing declaration statements. /// Returns true for function declarator and false for constructor-style - /// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration + /// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration /// might be a constructor-style initializer. /// If during the disambiguation process a parsing error is encountered, /// the function returns true to let the declaration parsing code handle it. @@ -2319,7 +2320,7 @@ private: void stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs, DeclSpec &DS, Sema::TagUseKind TUK); - + // FixItLoc = possible correct location for the attributes void ProhibitAttributes(ParsedAttributesWithRange &Attrs, SourceLocation FixItLoc = SourceLocation()) { @@ -2689,7 +2690,7 @@ private: void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc, DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS, bool EnteringContext, - DeclSpecContext DSC, + DeclSpecContext DSC, ParsedAttributesWithRange &Attributes); void SkipCXXMemberSpecification(SourceLocation StartLoc, SourceLocation AttrFixitLoc, @@ -2943,7 +2944,7 @@ private: //===--------------------------------------------------------------------===// // C++11/G++: Type Traits [Type-Traits.html in the GCC manual] ExprResult ParseTypeTrait(); - + //===--------------------------------------------------------------------===// // Embarcadero: Arary and Expression Traits ExprResult ParseArrayTypeTrait(); diff --git a/include/clang/Parse/RAIIObjectsForParser.h b/include/clang/Parse/RAIIObjectsForParser.h index f45d6434833e..ba5e5fe3c8fb 100644 --- a/include/clang/Parse/RAIIObjectsForParser.h +++ b/include/clang/Parse/RAIIObjectsForParser.h @@ -49,7 +49,7 @@ namespace clang { bool Active; public: - /// Begin suppressing access-like checks + /// Begin suppressing access-like checks SuppressAccessChecks(Parser &P, bool activate = true) : S(P.getActions()), DiagnosticPool(nullptr) { if (activate) { @@ -264,7 +264,7 @@ namespace clang { Diags.DecrementAllExtensionsSilenced(); } }; - + /// ColonProtectionRAIIObject - This sets the Parser::ColonIsSacred bool and /// restores it when destroyed. This says that "foo:" should not be /// considered a possible typo for "foo::" for error recovery purposes. @@ -276,18 +276,18 @@ namespace clang { : P(p), OldVal(P.ColonIsSacred) { P.ColonIsSacred = Value; } - + /// restore - This can be used to restore the state early, before the dtor /// is run. void restore() { P.ColonIsSacred = OldVal; } - + ~ColonProtectionRAIIObject() { restore(); } }; - + /// RAII object that makes '>' behave either as an operator /// or as the closing angle bracket for a template argument list. class GreaterThanIsOperatorScope { @@ -298,28 +298,28 @@ namespace clang { : GreaterThanIsOperator(GTIO), OldGreaterThanIsOperator(GTIO) { GreaterThanIsOperator = Val; } - + ~GreaterThanIsOperatorScope() { GreaterThanIsOperator = OldGreaterThanIsOperator; } }; - + class InMessageExpressionRAIIObject { bool &InMessageExpression; bool OldValue; - + public: InMessageExpressionRAIIObject(Parser &P, bool Value) - : InMessageExpression(P.InMessageExpression), + : InMessageExpression(P.InMessageExpression), OldValue(P.InMessageExpression) { InMessageExpression = Value; } - + ~InMessageExpressionRAIIObject() { InMessageExpression = OldValue; } }; - + /// RAII object that makes sure paren/bracket/brace count is correct /// after declaration/statement parsing, even when there's a parsing error. class ParenBraceBracketBalancer { @@ -329,7 +329,7 @@ namespace clang { ParenBraceBracketBalancer(Parser &p) : P(p), ParenCount(p.ParenCount), BracketCount(p.BracketCount), BraceCount(p.BraceCount) { } - + ~ParenBraceBracketBalancer() { P.AngleBrackets.clear(P); P.ParenCount = ParenCount; @@ -369,7 +369,7 @@ namespace clang { tok::TokenKind Kind, Close, FinalToken; SourceLocation (Parser::*Consumer)(); SourceLocation LOpen, LClose; - + unsigned short &getDepth() { switch (Kind) { case tok::l_brace: return P.BraceCount; @@ -378,10 +378,10 @@ namespace clang { default: llvm_unreachable("Wrong token kind"); } } - + bool diagnoseOverflow(); bool diagnoseMissingClose(); - + public: BalancedDelimiterTracker(Parser& p, tok::TokenKind k, tok::TokenKind FinalToken = tok::semi) @@ -391,34 +391,34 @@ namespace clang { switch (Kind) { default: llvm_unreachable("Unexpected balanced token"); case tok::l_brace: - Close = tok::r_brace; + Close = tok::r_brace; Consumer = &Parser::ConsumeBrace; break; case tok::l_paren: - Close = tok::r_paren; + Close = tok::r_paren; Consumer = &Parser::ConsumeParen; break; - + case tok::l_square: - Close = tok::r_square; + Close = tok::r_square; Consumer = &Parser::ConsumeBracket; break; - } + } } - + SourceLocation getOpenLocation() const { return LOpen; } SourceLocation getCloseLocation() const { return LClose; } SourceRange getRange() const { return SourceRange(LOpen, LClose); } - + bool consumeOpen() { if (!P.Tok.is(Kind)) return true; - + if (getDepth() < P.getLangOpts().BracketDepth) { LOpen = (P.*Consumer)(); return false; } - + return diagnoseOverflow(); } @@ -436,7 +436,7 @@ namespace clang { LClose = (P.*Consumer)(); return false; } - + return diagnoseMissingClose(); } void skipToEnd(); diff --git a/include/clang/Sema/DeclSpec.h b/include/clang/Sema/DeclSpec.h index 83d5ab2cff85..2e70203c6cc0 100644 --- a/include/clang/Sema/DeclSpec.h +++ b/include/clang/Sema/DeclSpec.h @@ -61,7 +61,7 @@ namespace clang { /// /// The actual scope is described by getScopeRep(). class CXXScopeSpec { - SourceRange Range; + SourceRange Range; NestedNameSpecifierLocBuilder Builder; public: @@ -73,8 +73,8 @@ public: SourceLocation getEndLoc() const { return Range.getEnd(); } /// Retrieve the representation of the nested-name-specifier. - NestedNameSpecifier *getScopeRep() const { - return Builder.getRepresentation(); + NestedNameSpecifier *getScopeRep() const { + return Builder.getRepresentation(); } /// Extend the current nested-name-specifier by another @@ -91,7 +91,7 @@ public: void Extend(ASTContext &Context, SourceLocation TemplateKWLoc, TypeLoc TL, SourceLocation ColonColonLoc); - /// Extend the current nested-name-specifier by another + /// Extend the current nested-name-specifier by another /// nested-name-specifier component of the form 'identifier::'. /// /// \param Context The AST context in which this nested-name-specifier @@ -105,7 +105,7 @@ public: void Extend(ASTContext &Context, IdentifierInfo *Identifier, SourceLocation IdentifierLoc, SourceLocation ColonColonLoc); - /// Extend the current nested-name-specifier by another + /// Extend the current nested-name-specifier by another /// nested-name-specifier component of the form 'namespace::'. /// /// \param Context The AST context in which this nested-name-specifier @@ -119,7 +119,7 @@ public: void Extend(ASTContext &Context, NamespaceDecl *Namespace, SourceLocation NamespaceLoc, SourceLocation ColonColonLoc); - /// Extend the current nested-name-specifier by another + /// Extend the current nested-name-specifier by another /// nested-name-specifier component of the form 'namespace-alias::'. /// /// \param Context The AST context in which this nested-name-specifier @@ -127,7 +127,7 @@ public: /// /// \param Alias The namespace alias. /// - /// \param AliasLoc The location of the namespace alias + /// \param AliasLoc The location of the namespace alias /// name. /// /// \param ColonColonLoc The location of the trailing '::'. @@ -137,7 +137,7 @@ public: /// Turn this (empty) nested-name-specifier into the global /// nested-name-specifier '::'. void MakeGlobal(ASTContext &Context, SourceLocation ColonColonLoc); - + /// Turns this (empty) nested-name-specifier into '__super' /// nested-name-specifier. /// @@ -160,13 +160,13 @@ public: /// FIXME: This routine should be used very, very rarely, in cases where we /// need to synthesize a nested-name-specifier. Most code should instead use /// \c Adopt() with a proper \c NestedNameSpecifierLoc. - void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, + void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R); - - /// Adopt an existing nested-name-specifier (with source-range + + /// Adopt an existing nested-name-specifier (with source-range /// information). void Adopt(NestedNameSpecifierLoc Other); - + /// Retrieve a nested-name-specifier with location information, copied /// into the given AST context. /// @@ -196,14 +196,14 @@ public: bool isValid() const { return isNotEmpty() && getScopeRep() != nullptr; } /// Indicate that this nested-name-specifier is invalid. - void SetInvalid(SourceRange R) { + void SetInvalid(SourceRange R) { assert(R.isValid() && "Must have a valid source range"); if (Range.getBegin().isInvalid()) Range.setBegin(R.getBegin()); Range.setEnd(R.getEnd()); Builder.Clear(); } - + /// Deprecated. Some call sites intend isNotEmpty() while others intend /// isValid(). bool isSet() const { return getScopeRep() != nullptr; } @@ -215,8 +215,8 @@ public: /// Retrieve the data associated with the source-location information. char *location_data() const { return Builder.getBuffer().first; } - - /// Retrieve the size of the data associated with source-location + + /// Retrieve the size of the data associated with source-location /// information. unsigned location_size() const { return Builder.getBuffer().second; } }; @@ -254,7 +254,7 @@ public: static const TSW TSW_short = clang::TSW_short; static const TSW TSW_long = clang::TSW_long; static const TSW TSW_longlong = clang::TSW_longlong; - + enum TSC { TSC_unspecified, TSC_imaginary, @@ -709,7 +709,7 @@ public: bool isModulePrivateSpecified() const { return ModulePrivateLoc.isValid(); } SourceLocation getModulePrivateSpecLoc() const { return ModulePrivateLoc; } - + bool isConstexprSpecified() const { return Constexpr_specified; } SourceLocation getConstexprSpecLoc() const { return ConstexprLoc; } @@ -916,7 +916,7 @@ enum class UnqualifiedIdKind { IK_DeductionGuideName }; -/// Represents a C++ unqualified-id that has been parsed. +/// Represents a C++ unqualified-id that has been parsed. class UnqualifiedId { private: UnqualifiedId(const UnqualifiedId &Other) = delete; @@ -931,8 +931,8 @@ public: OverloadedOperatorKind Operator; /// The source locations of the individual tokens that name - /// the operator, e.g., the "new", "[", and "]" tokens in - /// operator new []. + /// the operator, e.g., the "new", "[", and "]" tokens in + /// operator new []. /// /// Different operators have different numbers of tokens in their name, /// up to three. Any remaining source locations in this array will be @@ -946,44 +946,44 @@ public: /// When Kind == IK_Identifier, the parsed identifier, or when /// Kind == IK_UserLiteralId, the identifier suffix. IdentifierInfo *Identifier; - + /// When Kind == IK_OperatorFunctionId, the overloaded operator /// that we parsed. struct OFI OperatorFunctionId; - - /// When Kind == IK_ConversionFunctionId, the type that the + + /// When Kind == IK_ConversionFunctionId, the type that the /// conversion function names. UnionParsedType ConversionFunctionId; /// When Kind == IK_ConstructorName, the class-name of the type /// whose constructor is being referenced. UnionParsedType ConstructorName; - + /// When Kind == IK_DestructorName, the type referred to by the /// class-name. UnionParsedType DestructorName; /// When Kind == IK_DeductionGuideName, the parsed template-name. UnionParsedTemplateTy TemplateName; - + /// When Kind == IK_TemplateId or IK_ConstructorTemplateId, /// the template-id annotation that contains the template name and /// template arguments. TemplateIdAnnotation *TemplateId; }; - + /// The location of the first token that describes this unqualified-id, /// which will be the location of the identifier, "operator" keyword, /// tilde (for a destructor), or the template name of a template-id. SourceLocation StartLocation; - + /// The location of the last token that describes this unqualified-id. SourceLocation EndLocation; UnqualifiedId() : Kind(UnqualifiedIdKind::IK_Identifier), Identifier(nullptr) {} - /// Clear out this unqualified-id, setting it to default (invalid) + /// Clear out this unqualified-id, setting it to default (invalid) /// state. void clear() { Kind = UnqualifiedIdKind::IK_Identifier; @@ -991,17 +991,17 @@ public: StartLocation = SourceLocation(); EndLocation = SourceLocation(); } - + /// Determine whether this unqualified-id refers to a valid name. bool isValid() const { return StartLocation.isValid(); } /// Determine whether this unqualified-id refers to an invalid name. bool isInvalid() const { return !isValid(); } - + /// Determine what kind of name we have. UnqualifiedIdKind getKind() const { return Kind; } - void setKind(UnqualifiedIdKind kind) { Kind = kind; } - + void setKind(UnqualifiedIdKind kind) { Kind = kind; } + /// Specify that this unqualified-id was parsed as an identifier. /// /// \param Id the parsed identifier. @@ -1011,8 +1011,8 @@ public: Identifier = const_cast<IdentifierInfo *>(Id); StartLocation = EndLocation = IdLoc; } - - /// Specify that this unqualified-id was parsed as an + + /// Specify that this unqualified-id was parsed as an /// operator-function-id. /// /// \param OperatorLoc the location of the 'operator' keyword. @@ -1021,11 +1021,11 @@ public: /// /// \param SymbolLocations the locations of the individual operator symbols /// in the operator. - void setOperatorFunctionId(SourceLocation OperatorLoc, + void setOperatorFunctionId(SourceLocation OperatorLoc, OverloadedOperatorKind Op, SourceLocation SymbolLocations[3]); - - /// Specify that this unqualified-id was parsed as a + + /// Specify that this unqualified-id was parsed as a /// conversion-function-id. /// /// \param OperatorLoc the location of the 'operator' keyword. @@ -1033,7 +1033,7 @@ public: /// \param Ty the type to which this conversion function is converting. /// /// \param EndLoc the location of the last token that makes up the type name. - void setConversionFunctionId(SourceLocation OperatorLoc, + void setConversionFunctionId(SourceLocation OperatorLoc, ParsedType Ty, SourceLocation EndLoc) { Kind = UnqualifiedIdKind::IK_ConversionFunctionId; @@ -1057,7 +1057,7 @@ public: StartLocation = OpLoc; EndLocation = IdLoc; } - + /// Specify that this unqualified-id was parsed as a constructor name. /// /// \param ClassType the class type referred to by the constructor name. @@ -1065,7 +1065,7 @@ public: /// \param ClassNameLoc the location of the class name. /// /// \param EndLoc the location of the last token that makes up the type name. - void setConstructorName(ParsedType ClassType, + void setConstructorName(ParsedType ClassType, SourceLocation ClassNameLoc, SourceLocation EndLoc) { Kind = UnqualifiedIdKind::IK_ConstructorName; @@ -1096,7 +1096,7 @@ public: EndLocation = EndLoc; DestructorName = ClassType; } - + /// Specify that this unqualified-id was parsed as a template-id. /// /// \param TemplateId the template-id annotation that describes the parsed @@ -1115,10 +1115,10 @@ public: TemplateName = Template; StartLocation = EndLocation = TemplateLoc; } - + /// Return the source range that covers this unqualified-id. - SourceRange getSourceRange() const LLVM_READONLY { - return SourceRange(StartLocation, EndLocation); + SourceRange getSourceRange() const LLVM_READONLY { + return SourceRange(StartLocation, EndLocation); } SourceLocation getLocStart() const LLVM_READONLY { return StartLocation; } SourceLocation getLocEnd() const LLVM_READONLY { return EndLocation; } @@ -1326,7 +1326,7 @@ struct DeclaratorChunk { /// Pointer to the expression in the noexcept-specifier of this /// function, if it has one. Expr *NoexceptExpr; - + /// Pointer to the cached tokens for an exception-specification /// that has not yet been parsed. CachedTokens *ExceptionSpecTokens; @@ -1426,7 +1426,7 @@ struct DeclaratorChunk { return SourceLocation::getFromRawEncoding(MutableLoc); } - /// Determine whether this function declaration contains a + /// Determine whether this function declaration contains a /// ref-qualifier. bool hasRefQualifier() const { return getRefQualifierLoc().isValid(); } @@ -1746,7 +1746,7 @@ enum class DeclaratorContext { /// Instances of this class should be a transient object that lives on the /// stack, not objects that are allocated in large quantities on the heap. class Declarator { - + private: const DeclSpec &DS; CXXScopeSpec SS; @@ -1771,7 +1771,7 @@ private: /// GroupingParens - Set by Parser::ParseParenDeclarator(). unsigned GroupingParens : 1; - /// FunctionDefinition - Is this Declarator for a function or member + /// FunctionDefinition - Is this Declarator for a function or member /// definition and, if so, what kind? /// /// Actually a FunctionDefinitionKind. @@ -1785,7 +1785,7 @@ private: /// Indicates whether this is an Objective-C instance variable. unsigned ObjCIvar : 1; - + /// Indicates whether this is an Objective-C 'weak' property. unsigned ObjCWeakProperty : 1; @@ -1817,7 +1817,7 @@ private: /// If provided, the source location of the ellipsis used to describe /// this declarator as a parameter pack. SourceLocation EllipsisLoc; - + friend struct DeclaratorChunk; public: @@ -1858,7 +1858,7 @@ public: const DecompositionDeclarator &getDecompositionDeclarator() const { return BindingGroup; } - + DeclaratorContext getContext() const { return Context; } bool isPrototypeContext() const { @@ -2107,10 +2107,10 @@ public: return BindingGroup.isSet(); } - IdentifierInfo *getIdentifier() const { + IdentifierInfo *getIdentifier() const { if (Name.getKind() == UnqualifiedIdKind::IK_Identifier) return Name.Identifier; - + return nullptr; } SourceLocation getIdentifierLoc() const { return Name.StartLocation; } @@ -2261,9 +2261,9 @@ public: return const_cast<Declarator*>(this)->getFunctionTypeInfo(); } - /// Determine whether the declaration that will be produced from + /// Determine whether the declaration that will be produced from /// this declaration will be a function. - /// + /// /// A declaration can declare a function even if the declarator itself /// isn't a function declarator, if the type specifier refers to a function /// type. This routine checks for both cases. @@ -2318,8 +2318,8 @@ public: case DeclaratorContext::MemberContext: // FIXME: sizeof(...) permits an expression. - case DeclaratorContext::TypeNameContext: - + case DeclaratorContext::TypeNameContext: + case DeclaratorContext::FunctionalCastContext: case DeclaratorContext::AliasDeclContext: case DeclaratorContext::AliasTemplateContext: @@ -2349,7 +2349,7 @@ public: llvm_unreachable("unknown context kind!"); } - + /// Return true if a function declarator at this position would be a /// function declaration. bool isFunctionDeclaratorAFunctionDeclaration() const { @@ -2418,7 +2418,7 @@ public: void setObjCIvar(bool Val = true) { ObjCIvar = Val; } bool isObjCIvar() const { return ObjCIvar; } - + void setObjCWeakProperty(bool Val = true) { ObjCWeakProperty = Val; } bool isObjCWeakProperty() const { return ObjCWeakProperty; } @@ -2438,16 +2438,16 @@ public: SourceLocation getEllipsisLoc() const { return EllipsisLoc; } void setEllipsisLoc(SourceLocation EL) { EllipsisLoc = EL; } - void setFunctionDefinitionKind(FunctionDefinitionKind Val) { - FunctionDefinition = Val; + void setFunctionDefinitionKind(FunctionDefinitionKind Val) { + FunctionDefinition = Val; } - + bool isFunctionDefinition() const { return getFunctionDefinitionKind() != FDK_Declaration; } - - FunctionDefinitionKind getFunctionDefinitionKind() const { - return (FunctionDefinitionKind)FunctionDefinition; + + FunctionDefinitionKind getFunctionDefinitionKind() const { + return (FunctionDefinitionKind)FunctionDefinition; } /// Returns true if this declares a real member and not a friend. @@ -2511,7 +2511,7 @@ public: SourceLocation getFirstLocation() const { return FirstLocation; } SourceLocation getLastLocation() const { return LastLocation; } Specifier getLastSpecifier() const { return LastSpecifier; } - + private: unsigned Specifiers; Specifier LastSpecifier; @@ -2565,7 +2565,7 @@ struct LambdaIntroducer { IdentifierInfo* Id, SourceLocation EllipsisLoc, LambdaCaptureInitKind InitKind, - ExprResult Init, + ExprResult Init, ParsedType InitCaptureType, SourceRange ExplicitRange) { Captures.push_back(LambdaCapture(Kind, Loc, Id, EllipsisLoc, InitKind, Init, diff --git a/include/clang/Sema/DelayedDiagnostic.h b/include/clang/Sema/DelayedDiagnostic.h index 76aa4546d749..a26b6ff070f6 100644 --- a/include/clang/Sema/DelayedDiagnostic.h +++ b/include/clang/Sema/DelayedDiagnostic.h @@ -8,7 +8,7 @@ //===----------------------------------------------------------------------===// // /// \file -/// Defines the classes clang::DelayedDiagnostic and +/// Defines the classes clang::DelayedDiagnostic and /// clang::AccessedEntity. /// /// DelayedDiangostic is used to record diagnostics that are being diff --git a/include/clang/Sema/ExternalSemaSource.h b/include/clang/Sema/ExternalSemaSource.h index 42754b33e2df..00f80e27415d 100644 --- a/include/clang/Sema/ExternalSemaSource.h +++ b/include/clang/Sema/ExternalSemaSource.h @@ -46,7 +46,7 @@ struct ExternalVTableUse { SourceLocation Location; bool DefinitionRequired; }; - + /// An abstract interface that should be implemented by /// external AST sources that also provide information for semantic /// analysis. @@ -106,7 +106,7 @@ public: /// introduce the same declarations repeatedly. virtual void ReadTentativeDefinitions( SmallVectorImpl<VarDecl *> &TentativeDefs) {} - + /// Read the set of unused file-scope declarations known to the /// external Sema source. /// @@ -116,7 +116,7 @@ public: /// introduce the same declarations repeatedly. virtual void ReadUnusedFileScopedDecls( SmallVectorImpl<const DeclaratorDecl *> &Decls) {} - + /// Read the set of delegating constructors known to the /// external Sema source. /// @@ -148,9 +148,9 @@ public: /// Read the set of referenced selectors known to the /// external Sema source. /// - /// The external source should append its own referenced selectors to the - /// given vector of selectors. Note that this routine - /// may be invoked multiple times; the external source should take care not + /// The external source should append its own referenced selectors to the + /// given vector of selectors. Note that this routine + /// may be invoked multiple times; the external source should take care not /// to introduce the same selectors repeatedly. virtual void ReadReferencedSelectors( SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {} @@ -159,7 +159,7 @@ public: /// external Sema source. /// /// The external source should append its own weak, undeclared identifiers to - /// the given vector. Note that this routine may be invoked multiple times; + /// the given vector. Note that this routine may be invoked multiple times; /// the external source should take care not to introduce the same identifiers /// repeatedly. virtual void ReadWeakUndeclaredIdentifiers( @@ -180,7 +180,7 @@ public: /// external source should take care not to introduce the same instantiations /// repeatedly. virtual void ReadPendingInstantiations( - SmallVectorImpl<std::pair<ValueDecl *, + SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {} /// Read the set of late parsed template functions for this source. @@ -227,7 +227,7 @@ public: static bool classof(const ExternalASTSource *Source) { return Source->SemaSource; } -}; +}; } // end namespace clang diff --git a/include/clang/Sema/IdentifierResolver.h b/include/clang/Sema/IdentifierResolver.h index ea6c3df74af0..1c46e1d0e3d2 100644 --- a/include/clang/Sema/IdentifierResolver.h +++ b/include/clang/Sema/IdentifierResolver.h @@ -32,7 +32,7 @@ class LangOptions; class NamedDecl; class Preprocessor; class Scope; - + /// IdentifierResolver - Keeps track of shadowed decls on enclosing /// scopes. It manages the shadowing chains of declaration names and /// implements efficient decl lookup based on a declaration name. @@ -58,7 +58,7 @@ class IdentifierResolver { void InsertDecl(DeclsTy::iterator Pos, NamedDecl *D) { Decls.insert(Pos, D); } - + private: DeclsTy Decls; }; @@ -176,17 +176,17 @@ public: /// /// \returns true if the declaration was added, false otherwise. bool tryAddTopLevelDecl(NamedDecl *D, DeclarationName Name); - + private: const LangOptions &LangOpt; Preprocessor &PP; - + class IdDeclInfoMap; IdDeclInfoMap *IdDeclInfos; void updatingIdentifier(IdentifierInfo &II); void readingIdentifier(IdentifierInfo &II); - + /// FETokenInfo contains a Decl pointer if lower bit == 0. static inline bool isDeclPtr(void *Ptr) { return (reinterpret_cast<uintptr_t>(Ptr) & 0x1) == 0; diff --git a/include/clang/Sema/Initialization.h b/include/clang/Sema/Initialization.h index 7a510f391bda..8582e971d0b6 100644 --- a/include/clang/Sema/Initialization.h +++ b/include/clang/Sema/Initialization.h @@ -102,7 +102,7 @@ public: /// complex number. EK_ComplexElement, - /// The entity being initialized is the field that captures a + /// The entity being initialized is the field that captures a /// variable in a lambda. EK_LambdaCapture, @@ -178,7 +178,7 @@ private: union { /// When Kind == EK_Variable, EK_Member or EK_Binding, the variable. VD Variable; - + /// When Kind == EK_RelatedResult, the ObjectiveC method where /// result type was implicitly changed to accommodate ARC semantics. ObjCMethodDecl *MethodDecl; @@ -186,21 +186,21 @@ private: /// When Kind == EK_Parameter, the ParmVarDecl, with the /// low bit indicating whether the parameter is "consumed". uintptr_t Parameter; - + /// When Kind == EK_Temporary or EK_CompoundLiteralInit, the type /// source information for the temporary. TypeSourceInfo *TypeInfo; struct LN LocAndNRVO; - - /// When Kind == EK_Base, the base specifier that provides the + + /// When Kind == EK_Base, the base specifier that provides the /// base class. The lower bit specifies whether the base is an inherited /// virtual base. uintptr_t Base; /// When Kind == EK_ArrayElement, EK_VectorElement, or /// EK_ComplexElement, the index of the array or vector element being - /// initialized. + /// initialized. unsigned Index; struct C Capture; @@ -211,7 +211,7 @@ private: /// Create the initialization entity for a variable. InitializedEntity(VarDecl *Var, EntityKind EK = EK_Variable) : Kind(EK), Type(Var->getType()), Variable{Var, false, false} {} - + /// Create the initialization entity for the result of a /// function, throwing an object, performing an explicit cast, or /// initializing a parameter for which there is no declaration. @@ -221,15 +221,15 @@ private: LocAndNRVO.Location = Loc.getRawEncoding(); LocAndNRVO.NRVO = NRVO; } - + /// Create the initialization entity for a member subobject. InitializedEntity(FieldDecl *Member, const InitializedEntity *Parent, bool Implicit, bool DefaultMemberInit) : Kind(EK_Member), Parent(Parent), Type(Member->getType()), Variable{Member, Implicit, DefaultMemberInit} {} - + /// Create the initialization entity for an array element. - InitializedEntity(ASTContext &Context, unsigned Index, + InitializedEntity(ASTContext &Context, unsigned Index, const InitializedEntity &Parent); /// Create the initialization entity for a lambda capture. @@ -238,7 +238,7 @@ private: Capture.VarID = VarID; Capture.Location = Loc.getRawEncoding(); } - + public: /// Create the initialization entity for a variable. static InitializedEntity InitializeVariable(VarDecl *Var) { @@ -314,7 +314,7 @@ public: static InitializedEntity InitializeNew(SourceLocation NewLoc, QualType Type) { return InitializedEntity(EK_New, NewLoc, Type); } - + /// Create the initialization entity for a temporary. static InitializedEntity InitializeTemporary(QualType Type) { return InitializeTemporary(nullptr, Type); @@ -324,7 +324,7 @@ public: static InitializedEntity InitializeTemporary(TypeSourceInfo *TypeInfo) { return InitializeTemporary(TypeInfo, TypeInfo->getType()); } - + /// Create the initialization entity for a temporary. static InitializedEntity InitializeTemporary(TypeSourceInfo *TypeInfo, QualType Type) { @@ -332,7 +332,7 @@ public: Result.TypeInfo = TypeInfo; return Result; } - + /// Create the initialization entity for a related result. static InitializedEntity InitializeRelatedResult(ObjCMethodDecl *MD, QualType Type) { @@ -375,8 +375,8 @@ public: } /// Create the initialization entity for an array element. - static InitializedEntity InitializeElement(ASTContext &Context, - unsigned Index, + static InitializedEntity InitializeElement(ASTContext &Context, + unsigned Index, const InitializedEntity &Parent) { return InitializedEntity(Context, Index, Parent); } @@ -403,7 +403,7 @@ public: /// Determine the kind of initialization. EntityKind getKind() const { return Kind; } - + /// Retrieve the parent of the entity being initialized, when /// the initialization itself is occurring within the context of a /// larger initialization. @@ -411,27 +411,27 @@ public: /// Retrieve type being initialized. QualType getType() const { return Type; } - - /// Retrieve complete type-source information for the object being + + /// Retrieve complete type-source information for the object being /// constructed, if known. TypeSourceInfo *getTypeSourceInfo() const { if (Kind == EK_Temporary || Kind == EK_CompoundLiteralInit) return TypeInfo; - + return nullptr; } - + /// Retrieve the name of the entity being initialized. DeclarationName getName() const; /// Retrieve the variable, parameter, or field being /// initialized. ValueDecl *getDecl() const; - + /// Retrieve the ObjectiveC method being initialized. ObjCMethodDecl *getMethodDecl() const { return MethodDecl; } - /// Determine whether this initialization allows the named return + /// Determine whether this initialization allows the named return /// value optimization, which also applies to thrown objects. bool allowsNRVO() const; @@ -446,7 +446,7 @@ public: assert(isParameterKind() && "Not a parameter"); return (Parameter & 1); } - + /// Retrieve the base specifier. const CXXBaseSpecifier *getBaseSpecifier() const { assert(getKind() == EK_Base && "Not a base specifier"); @@ -519,7 +519,7 @@ public: assert(getKind() == EK_LambdaCapture && "Not a lambda capture!"); return SourceLocation::getFromRawEncoding(Capture.Location); } - + void setParameterCFAudited() { Kind = EK_Parameter_CF_Audited; } @@ -533,8 +533,8 @@ public: private: unsigned dumpImpl(raw_ostream &OS) const; }; - -/// Describes the kind of initialization being performed, along with + +/// Describes the kind of initialization being performed, along with /// location information for tokens related to the initialization (equal sign, /// parentheses). class InitializationKind { @@ -556,7 +556,7 @@ public: /// Value initialization IK_Value }; - + private: /// The context of the initialization. enum InitContext { @@ -578,24 +578,24 @@ private: /// Functional cast context IC_FunctionalCast }; - + /// The kind of initialization being performed. InitKind Kind : 8; /// The context of the initialization. InitContext Context : 8; - + /// The source locations involved in the initialization. SourceLocation Locations[3]; - - InitializationKind(InitKind Kind, InitContext Context, SourceLocation Loc1, + + InitializationKind(InitKind Kind, InitContext Context, SourceLocation Loc1, SourceLocation Loc2, SourceLocation Loc3) : Kind(Kind), Context(Context) { Locations[0] = Loc1; Locations[1] = Loc2; Locations[2] = Loc3; } - + public: /// Create a direct initialization. static InitializationKind CreateDirect(SourceLocation InitLoc, @@ -617,13 +617,13 @@ public: RBraceLoc); } - /// Create a direct initialization due to a cast that isn't a C-style + /// Create a direct initialization due to a cast that isn't a C-style /// or functional cast. static InitializationKind CreateCast(SourceRange TypeRange) { return InitializationKind(IK_Direct, IC_StaticCast, TypeRange.getBegin(), TypeRange.getBegin(), TypeRange.getEnd()); } - + /// Create a direct initialization for a C-style cast. static InitializationKind CreateCStyleCast(SourceLocation StartLoc, SourceRange TypeRange, @@ -647,16 +647,16 @@ public: static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs = false) { - return InitializationKind(IK_Copy, + return InitializationKind(IK_Copy, AllowExplicitConvs? IC_ExplicitConvs : IC_Normal, InitLoc, EqualLoc, EqualLoc); } - + /// Create a default initialization. static InitializationKind CreateDefault(SourceLocation InitLoc) { return InitializationKind(IK_Default, IC_Normal, InitLoc, InitLoc, InitLoc); } - + /// Create a value initialization. static InitializationKind CreateValue(SourceLocation InitLoc, SourceLocation LParenLoc, @@ -676,20 +676,20 @@ public: return CreateDirectList(Loc, Init->getLocStart(), Init->getLocEnd()); return CreateDirect(Loc, Init->getLocStart(), Init->getLocEnd()); } - + /// Determine the initialization kind. InitKind getKind() const { return Kind; } - + /// Determine whether this initialization is an explicit cast. bool isExplicitCast() const { return Context >= IC_StaticCast; } - + /// Determine whether this initialization is a C-style cast. - bool isCStyleOrFunctionalCast() const { - return Context >= IC_CStyleCast; + bool isCStyleOrFunctionalCast() const { + return Context >= IC_CStyleCast; } /// Determine whether this is a C-style cast. @@ -709,12 +709,12 @@ public: /// Retrieve the location at which initialization is occurring. SourceLocation getLocation() const { return Locations[0]; } - + /// Retrieve the source range that covers the initialization. - SourceRange getRange() const { + SourceRange getRange() const { return SourceRange(Locations[0], Locations[2]); } - + /// Retrieve the location of the equal sign for copy initialization /// (if present). SourceLocation getEqualLoc() const { @@ -741,7 +741,7 @@ public: bool hasParenOrBraceRange() const { return Kind == IK_Direct || Kind == IK_Value || Kind == IK_DirectList; } - + /// Retrieve the source range containing the locations of the open /// and closing parentheses or braces for value, direct, and direct list /// initializations. @@ -771,7 +771,7 @@ public: /// A normal sequence. NormalSequence }; - + /// Describes the kind of a particular step in an initialization /// sequence. enum StepKind { @@ -898,13 +898,13 @@ public: /// Passing zero to a function where OpenCL event_t is expected. SK_OCLZeroEvent }; - + /// A single step in the initialization sequence. class Step { public: /// The kind of conversion or initialization step we are taking. StepKind Kind; - + // The type that results from this initialization. QualType Type; @@ -916,7 +916,7 @@ public: union { /// When Kind == SK_ResolvedOverloadedFunction or Kind == - /// SK_UserConversion, the function that the expression should be + /// SK_UserConversion, the function that the expression should be /// resolved to or the conversion function to call, respectively. /// When Kind == SK_ConstructorInitialization or SK_ListConstruction, /// the constructor to be called. @@ -938,14 +938,14 @@ public: void Destroy(); }; - + private: /// The kind of initialization sequence computed. enum SequenceKind SequenceKind; - + /// Steps taken by this initialization. SmallVector<Step, 4> Steps; - + public: /// Describes why initialization failed. enum FailureKind { @@ -958,7 +958,7 @@ public: /// Array must be initialized with an initializer list. FK_ArrayNeedsInitList, - /// Array must be initialized with an initializer list or a + /// Array must be initialized with an initializer list or a /// string literal. FK_ArrayNeedsInitListOrStringLiteral, @@ -1067,14 +1067,14 @@ public: /// List-copy-initialization chose an explicit constructor. FK_ExplicitConstructor, }; - + private: /// The reason why initialization failed. FailureKind Failure; /// The failed result of overload resolution. OverloadingResult FailedOverloadResult; - + /// The candidate set created when initialization failed. OverloadCandidateSet FailedCandidateSet; @@ -1100,11 +1100,11 @@ private: void PrintInitLocationNote(Sema &S, const InitializedEntity &Entity); public: - /// Try to perform initialization of the given entity, creating a + /// Try to perform initialization of the given entity, creating a /// record of the steps required to perform the initialization. /// /// The generated initialization sequence will either contain enough - /// information to diagnose + /// information to diagnose /// /// \param S the semantic analysis object. /// @@ -1119,7 +1119,7 @@ public: /// narrowing conversions in C++11 onwards. /// \param TreatUnavailableAsInvalid true if we want to treat unavailable /// as invalid. - InitializationSequence(Sema &S, + InitializationSequence(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, @@ -1130,7 +1130,7 @@ public: bool TopLevelOfInitList, bool TreatUnavailableAsInvalid); ~InitializationSequence(); - + /// Perform the actual initialization of the given entity based on /// the computed initialization sequence. /// @@ -1157,22 +1157,22 @@ public: const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType = nullptr); - + /// Diagnose an potentially-invalid initialization sequence. /// - /// \returns true if the initialization sequence was ill-formed, + /// \returns true if the initialization sequence was ill-formed, /// false otherwise. - bool Diagnose(Sema &S, + bool Diagnose(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, ArrayRef<Expr *> Args); - + /// Determine the kind of initialization sequence computed. enum SequenceKind getKind() const { return SequenceKind; } - + /// Set the kind of sequence computed. void setSequenceKind(enum SequenceKind SK) { SequenceKind = SK; } - + /// Determine whether the initialization sequence is valid. explicit operator bool() const { return !Failed(); } @@ -1188,14 +1188,14 @@ public: step_range steps() const { return {step_begin(), step_end()}; } - /// Determine whether this initialization is a direct reference + /// Determine whether this initialization is a direct reference /// binding (C++ [dcl.init.ref]). bool isDirectReferenceBinding() const; - + /// Determine whether this initialization failed due to an ambiguity. bool isAmbiguous() const; - - /// Determine whether this initialization is direct call to a + + /// Determine whether this initialization is direct call to a /// constructor. bool isConstructorInitialization() const; @@ -1228,7 +1228,7 @@ public: /// rvalue, an xvalue, or an lvalue. void AddDerivedToBaseCastStep(QualType BaseType, ExprValueKind Category); - + /// Add a new step binding a reference to an object. /// /// \param BindingTemporary True if we are binding a reference to a temporary @@ -1351,11 +1351,11 @@ public: assert((Failure != FK_Incomplete || !FailedIncompleteType.isNull()) && "Incomplete type failure requires a type!"); } - + /// Note that this initialization sequence failed due to failed /// overload resolution. void SetOverloadFailure(FailureKind Failure, OverloadingResult Result); - + /// Retrieve a reference to the candidate set when overload /// resolution fails. OverloadCandidateSet &getFailedCandidateSet() { @@ -1381,15 +1381,15 @@ public: return Failure; } - /// Dump a representation of this initialization sequence to + /// Dump a representation of this initialization sequence to /// the given stream, for debugging purposes. void dump(raw_ostream &OS) const; - - /// Dump a representation of this initialization sequence to + + /// Dump a representation of this initialization sequence to /// standard error, for debugging purposes. void dump() const; }; - + } // namespace clang #endif // LLVM_CLANG_SEMA_INITIALIZATION_H diff --git a/include/clang/Sema/Lookup.h b/include/clang/Sema/Lookup.h index c06952064dd9..e28b847f4ae5 100644 --- a/include/clang/Sema/Lookup.h +++ b/include/clang/Sema/Lookup.h @@ -50,11 +50,11 @@ public: /// No entity found met the criteria. NotFound = 0, - /// No entity found met the criteria within the current - /// instantiation,, but there were dependent base classes of the + /// No entity found met the criteria within the current + /// instantiation,, but there were dependent base classes of the /// current instantiation that could not be searched. NotFoundInCurrentInstantiation, - + /// Name lookup found a single declaration that met the /// criteria. getFoundDecl() will return this declaration. Found, @@ -435,7 +435,7 @@ public: bool wasNotFoundInCurrentInstantiation() const { return ResultKind == NotFoundInCurrentInstantiation; } - + /// Note that while no result was found in the current instantiation, /// there were dependent base classes that could not be searched. void setNotFoundInCurrentInstantiation() { @@ -610,7 +610,7 @@ public: LookupResult::iterator I; bool Changed = false; bool CalledDone = false; - + Filter(LookupResult &Results) : Results(Results), I(Results.begin()) {} public: diff --git a/include/clang/Sema/MultiplexExternalSemaSource.h b/include/clang/Sema/MultiplexExternalSemaSource.h index 4c242c89f3f4..86bddebcef69 100644 --- a/include/clang/Sema/MultiplexExternalSemaSource.h +++ b/include/clang/Sema/MultiplexExternalSemaSource.h @@ -42,7 +42,7 @@ private: SmallVector<ExternalSemaSource *, 2> Sources; // doesn't own them. public: - + ///Constructs a new multiplexing external sema source and appends the /// given element to it. /// @@ -113,7 +113,7 @@ public: /// Get the decls that are contained in a file in the Offset/Length /// range. \p Length can be 0 to indicate a point at \p Offset instead of - /// a range. + /// a range. void FindFileRegionDecls(FileID File, unsigned Offset,unsigned Length, SmallVectorImpl<Decl *> &Decls) override; @@ -125,7 +125,7 @@ public: /// incomplete Objective-C class. /// /// This routine will only be invoked if the "externally completed" bit is - /// set on the ObjCInterfaceDecl via the function + /// set on the ObjCInterfaceDecl via the function /// \c ObjCInterfaceDecl::setExternallyCompleted(). void CompleteType(ObjCInterfaceDecl *Class) override; @@ -156,7 +156,7 @@ public: /// Perform layout on the given record. /// - /// This routine allows the external AST source to provide an specific + /// This routine allows the external AST source to provide an specific /// layout for a record, overriding the layout that would normally be /// constructed. It is intended for clients who receive specific layout /// details rather than source code (such as LLDB). The client is expected @@ -173,13 +173,13 @@ public: /// expressed in bits. All of the fields must be provided with offsets. /// /// \param BaseOffsets The offset of each of the direct, non-virtual base - /// classes. If any bases are not given offsets, the bases will be laid + /// classes. If any bases are not given offsets, the bases will be laid /// out according to the ABI. /// /// \param VirtualBaseOffsets The offset of each of the virtual base classes - /// (either direct or not). If any bases are not given offsets, the bases will + /// (either direct or not). If any bases are not given offsets, the bases will /// be laid out according to the ABI. - /// + /// /// \returns true if the record layout was provided, false otherwise. bool layoutRecordType(const RecordDecl *Record, @@ -287,9 +287,9 @@ public: /// Read the set of referenced selectors known to the /// external Sema source. /// - /// The external source should append its own referenced selectors to the - /// given vector of selectors. Note that this routine - /// may be invoked multiple times; the external source should take care not + /// The external source should append its own referenced selectors to the + /// given vector of selectors. Note that this routine + /// may be invoked multiple times; the external source should take care not /// to introduce the same selectors repeatedly. void ReadReferencedSelectors(SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) override; @@ -298,7 +298,7 @@ public: /// external Sema source. /// /// The external source should append its own weak, undeclared identifiers to - /// the given vector. Note that this routine may be invoked multiple times; + /// the given vector. Note that this routine may be invoked multiple times; /// the external source should take care not to introduce the same identifiers /// repeatedly. void ReadWeakUndeclaredIdentifiers( @@ -356,7 +356,7 @@ public: // isa/cast/dyn_cast support static bool classof(const MultiplexExternalSemaSource*) { return true; } //static bool classof(const ExternalSemaSource*) { return true; } -}; +}; } // end namespace clang diff --git a/include/clang/Sema/Overload.h b/include/clang/Sema/Overload.h index f75faf049625..6ded010ee8ed 100644 --- a/include/clang/Sema/Overload.h +++ b/include/clang/Sema/Overload.h @@ -62,7 +62,7 @@ class Sema; /// Succeeded, but refers to a deleted function. OR_Deleted }; - + enum OverloadCandidateDisplayKind { /// Requests that all candidates be shown. Viable candidates will /// be printed first. @@ -107,7 +107,7 @@ class Sema; /// Integral conversions (C++ [conv.integral]) ICK_Integral_Conversion, - /// Floating point conversions (C++ [conv.double] + /// Floating point conversions (C++ [conv.double] ICK_Floating_Conversion, /// Complex conversions (C99 6.3.1.6) @@ -252,7 +252,7 @@ class Sema; /// Whether the qualification conversion involves a change in the /// Objective-C lifetime (for automatic reference counting). unsigned QualificationIncludesObjCLifetime : 1; - + /// IncompatibleObjC - Whether this is an Objective-C conversion /// that we should warn about (if we actually use it). unsigned IncompatibleObjC : 1; @@ -268,21 +268,21 @@ class Sema; /// Whether this is an lvalue reference binding (otherwise, it's /// an rvalue reference binding). unsigned IsLvalueReference : 1; - + /// Whether we're binding to a function lvalue. unsigned BindsToFunctionLvalue : 1; - + /// Whether we're binding to an rvalue. unsigned BindsToRvalue : 1; - - /// Whether this binds an implicit object argument to a + + /// Whether this binds an implicit object argument to a /// non-static member function without a ref-qualifier. unsigned BindsImplicitObjectArgumentWithoutRefQualifier : 1; - + /// Whether this binds a reference to an object with a different /// Objective-C lifetime qualifier. unsigned ObjCLifetimeConversionBinding : 1; - + /// FromType - The type that this conversion is converting /// from. This is an opaque pointer that can be translated into a /// QualType. @@ -303,13 +303,13 @@ class Sema; void setFromType(QualType T) { FromTypePtr = T.getAsOpaquePtr(); } - void setToType(unsigned Idx, QualType T) { + void setToType(unsigned Idx, QualType T) { assert(Idx < 3 && "To type index is out of range"); - ToTypePtrs[Idx] = T.getAsOpaquePtr(); + ToTypePtrs[Idx] = T.getAsOpaquePtr(); } void setAllToTypes(QualType T) { - ToTypePtrs[0] = T.getAsOpaquePtr(); + ToTypePtrs[0] = T.getAsOpaquePtr(); ToTypePtrs[1] = ToTypePtrs[0]; ToTypePtrs[2] = ToTypePtrs[0]; } @@ -324,11 +324,11 @@ class Sema; } void setAsIdentityConversion(); - + bool isIdentityConversion() const { return Second == ICK_Identity && Third == ICK_Identity; } - + ImplicitConversionRank getRank() const; NarrowingKind getNarrowingKind(ASTContext &Context, const Expr *Converted, @@ -562,7 +562,7 @@ class Sema; new (this) ImplicitConversionSequence(Other); return *this; } - + ~ImplicitConversionSequence() { destruct(); } @@ -571,7 +571,7 @@ class Sema; assert(isInitialized() && "querying uninitialized conversion"); return Kind(ConversionKind); } - + /// Return a ranking of the implicit conversion sequence /// kind, where smaller ranks represent better conversion /// sequences. @@ -581,11 +581,11 @@ class Sema; /// per C++ [over.best.ics]p10. unsigned getKindRank() const { switch (getKind()) { - case StandardConversion: + case StandardConversion: return 0; case UserDefinedConversion: - case AmbiguousConversion: + case AmbiguousConversion: return 1; case EllipsisConversion: @@ -781,7 +781,7 @@ class Sema; union { DeductionFailureInfo DeductionFailure; - + /// FinalConversion - For a conversion function (where Function is /// a CXXConversionDecl), the standard conversion that occurs /// after the call to the overload candidate to convert the result diff --git a/include/clang/Sema/ParsedAttr.h b/include/clang/Sema/ParsedAttr.h index 3f293247787c..cfb91af78370 100644 --- a/include/clang/Sema/ParsedAttr.h +++ b/include/clang/Sema/ParsedAttr.h @@ -179,7 +179,7 @@ private: /// The location of the 'unavailable' keyword in an /// availability attribute. SourceLocation UnavailableLoc; - + const Expr *MessageExpr; /// Arguments, if any, are stored immediately following the object. @@ -265,7 +265,7 @@ private: Args[2] = Parm3; AttrKind = getKind(getName(), getScopeName(), syntaxUsed); } - + /// Constructor for type_tag_for_datatype attribute. ParsedAttr(IdentifierInfo *attrName, SourceRange attrRange, IdentifierInfo *scopeName, SourceLocation scopeLoc, @@ -352,7 +352,7 @@ public: void operator delete(void *) = delete; - enum Kind { + enum Kind { #define PARSED_ATTR(NAME) AT_##NAME, #include "clang/Sema/AttrParsedAttrList.inc" #undef PARSED_ATTR @@ -363,11 +363,11 @@ public: IdentifierInfo *getName() const { return AttrName; } SourceLocation getLoc() const { return AttrRange.getBegin(); } SourceRange getRange() const { return AttrRange; } - + bool hasScope() const { return ScopeName; } IdentifierInfo *getScopeName() const { return ScopeName; } SourceLocation getScopeLoc() const { return ScopeLoc; } - + bool hasParsedType() const { return HasParsedType; } /// Is this the Microsoft __declspec(property) attribute? @@ -473,7 +473,7 @@ public: assert(getKind() == AT_Availability && "Not an availability attribute"); return UnavailableLoc; } - + const Expr * getMessageExpr() const { assert(getKind() == AT_Availability && "Not an availability attribute"); return MessageExpr; diff --git a/include/clang/Sema/ParsedTemplate.h b/include/clang/Sema/ParsedTemplate.h index f79157ba813e..258b2291d260 100644 --- a/include/clang/Sema/ParsedTemplate.h +++ b/include/clang/Sema/ParsedTemplate.h @@ -25,7 +25,7 @@ #include <cstdlib> #include <new> -namespace clang { +namespace clang { /// Represents the parsed form of a C++ template argument. class ParsedTemplateArgument { public: @@ -39,87 +39,87 @@ namespace clang { Template }; - /// Build an empty template argument. + /// Build an empty template argument. /// /// This template argument is invalid. ParsedTemplateArgument() : Kind(Type), Arg(nullptr) { } - + /// Create a template type argument or non-type template argument. /// /// \param Arg the template type argument or non-type template argument. /// \param Loc the location of the type. ParsedTemplateArgument(KindType Kind, void *Arg, SourceLocation Loc) : Kind(Kind), Arg(Arg), Loc(Loc) { } - + /// Create a template template argument. /// /// \param SS the C++ scope specifier that precedes the template name, if /// any. /// - /// \param Template the template to which this template template + /// \param Template the template to which this template template /// argument refers. /// /// \param TemplateLoc the location of the template name. ParsedTemplateArgument(const CXXScopeSpec &SS, - ParsedTemplateTy Template, - SourceLocation TemplateLoc) + ParsedTemplateTy Template, + SourceLocation TemplateLoc) : Kind(ParsedTemplateArgument::Template), - Arg(Template.getAsOpaquePtr()), + Arg(Template.getAsOpaquePtr()), SS(SS), Loc(TemplateLoc), EllipsisLoc() { } - + /// Determine whether the given template argument is invalid. bool isInvalid() const { return Arg == nullptr; } - + /// Determine what kind of template argument we have. KindType getKind() const { return Kind; } - + /// Retrieve the template type argument's type. ParsedType getAsType() const { assert(Kind == Type && "Not a template type argument"); return ParsedType::getFromOpaquePtr(Arg); } - + /// Retrieve the non-type template argument's expression. Expr *getAsExpr() const { assert(Kind == NonType && "Not a non-type template argument"); return static_cast<Expr*>(Arg); } - + /// Retrieve the template template argument's template name. ParsedTemplateTy getAsTemplate() const { assert(Kind == Template && "Not a template template argument"); return ParsedTemplateTy::getFromOpaquePtr(Arg); } - + /// Retrieve the location of the template argument. SourceLocation getLocation() const { return Loc; } - + /// Retrieve the nested-name-specifier that precedes the template /// name in a template template argument. const CXXScopeSpec &getScopeSpec() const { - assert(Kind == Template && + assert(Kind == Template && "Only template template arguments can have a scope specifier"); return SS; } - + /// Retrieve the location of the ellipsis that makes a template /// template argument into a pack expansion. SourceLocation getEllipsisLoc() const { - assert(Kind == Template && + assert(Kind == Template && "Only template template arguments can have an ellipsis"); return EllipsisLoc; } - + /// Retrieve a pack expansion of the given template template /// argument. /// /// \param EllipsisLoc The location of the ellipsis. ParsedTemplateArgument getTemplatePackExpansion( SourceLocation EllipsisLoc) const; - + private: KindType Kind; - + /// The actual template argument representation, which may be /// an \c Sema::TypeTy* (for a type), an Expr* (for an /// expression), or an Sema::TemplateTy (for a template). @@ -136,14 +136,14 @@ namespace clang { /// argument (turning it into a template template argument expansion). SourceLocation EllipsisLoc; }; - + /// Information about a template-id annotation /// token. /// - /// A template-id annotation token contains the template declaration, - /// template arguments, whether those template arguments were types, - /// expressions, or template names, and the source locations for important - /// tokens. All of the information about template arguments is allocated + /// A template-id annotation token contains the template declaration, + /// template arguments, whether those template arguments were types, + /// expressions, or template names, and the source locations for important + /// tokens. All of the information about template arguments is allocated /// directly after this structure. struct TemplateIdAnnotation final : private llvm::TrailingObjects<TemplateIdAnnotation, @@ -159,34 +159,34 @@ namespace clang { /// TemplateNameLoc - The location of the template name within the /// source. SourceLocation TemplateNameLoc; - + /// FIXME: Temporarily stores the name of a specialization IdentifierInfo *Name; - + /// FIXME: Temporarily stores the overloaded operator kind. OverloadedOperatorKind Operator; - + /// The declaration of the template corresponding to the /// template-name. ParsedTemplateTy Template; - + /// The kind of template that Template refers to. TemplateNameKind Kind; - + /// The location of the '<' before the template argument /// list. SourceLocation LAngleLoc; - + /// The location of the '>' after the template argument /// list. SourceLocation RAngleLoc; - + /// NumArgs - The number of template arguments. unsigned NumArgs; - + /// Retrieves a pointer to the template arguments - ParsedTemplateArgument *getTemplateArgs() { - return getTrailingObjects<ParsedTemplateArgument>(); + ParsedTemplateArgument *getTemplateArgs() { + return getTrailingObjects<ParsedTemplateArgument>(); } /// Creates a new TemplateIdAnnotation with NumArgs arguments and @@ -213,7 +213,7 @@ namespace clang { getTemplateArgs(), getTemplateArgs() + NumArgs, [](ParsedTemplateArgument &A) { A.~ParsedTemplateArgument(); }); this->~TemplateIdAnnotation(); - free(this); + free(this); } private: TemplateIdAnnotation(const TemplateIdAnnotation &) = delete; @@ -239,7 +239,7 @@ namespace clang { /// Retrieves the range of the given template parameter lists. SourceRange getTemplateParamsRange(TemplateParameterList const *const *Params, - unsigned NumParams); + unsigned NumParams); } // end namespace clang #endif // LLVM_CLANG_SEMA_PARSEDTEMPLATE_H diff --git a/include/clang/Sema/Scope.h b/include/clang/Sema/Scope.h index a3379ff34f12..11fa0362124b 100644 --- a/include/clang/Sema/Scope.h +++ b/include/clang/Sema/Scope.h @@ -89,7 +89,7 @@ public: /// This is a scope that corresponds to the Objective-C /// \@catch statement. AtCatchScope = 0x400, - + /// This scope corresponds to an Objective-C method body. /// It always has FnScope and DeclScope set as well. ObjCMethodScope = 0x800, @@ -347,7 +347,7 @@ public: } return false; } - + /// isInObjcMethodScope - Return true if this scope is, or is contained in, an /// Objective-C method body. Note that this method is not constant time. bool isInObjcMethodScope() const { diff --git a/include/clang/Sema/ScopeInfo.h b/include/clang/Sema/ScopeInfo.h index 5eac2845fd33..5925fd6ccead 100644 --- a/include/clang/Sema/ScopeInfo.h +++ b/include/clang/Sema/ScopeInfo.h @@ -85,12 +85,12 @@ public: PartialDiagnostic PD; SourceLocation Loc; const Stmt *stmt; - + PossiblyUnreachableDiag(const PartialDiagnostic &PD, SourceLocation Loc, const Stmt *stmt) : PD(PD), Loc(Loc), stmt(stmt) {} }; - + /// Retains information about a function, method, or block that is /// currently being parsed. class FunctionScopeInfo { @@ -101,7 +101,7 @@ protected: SK_Lambda, SK_CapturedRegion }; - + public: /// What kind of scope we are describing. ScopeKind Kind : 3; @@ -206,7 +206,7 @@ public: /// current function scope. These diagnostics are vetted for reachability /// prior to being emitted. SmallVector<PossiblyUnreachableDiag, 4> PossiblyUnreachableDiags; - + /// A list of parameters which have the nonnull attribute and are /// modified in the function. llvm::SmallPtrSet<const ParmVarDecl *, 8> ModifiedNonNullParams; @@ -633,9 +633,9 @@ public: QualType ReturnType; void addCapture(VarDecl *Var, bool isBlock, bool isByref, bool isNested, - SourceLocation Loc, SourceLocation EllipsisLoc, + SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, Expr *Cpy) { - Captures.push_back(Capture(Var, isBlock, isByref, isNested, Loc, + Captures.push_back(Capture(Var, isBlock, isByref, isNested, Loc, EllipsisLoc, CaptureType, Cpy)); CaptureMap[Var] = Captures.size(); } @@ -655,13 +655,13 @@ public: /// Determine whether the C++ 'this' is captured. bool isCXXThisCaptured() const { return CXXThisCaptureIndex != 0; } - + /// Retrieve the capture of C++ 'this', if it has been captured. Capture &getCXXThisCapture() { assert(isCXXThisCaptured() && "this has not been captured"); return Captures[CXXThisCaptureIndex - 1]; } - + /// Determine whether the given variable has been captured. bool isCaptured(VarDecl *Var) const { return CaptureMap.count(Var); @@ -684,7 +684,7 @@ public: return Captures[Known->second - 1]; } - static bool classof(const FunctionScopeInfo *FSI) { + static bool classof(const FunctionScopeInfo *FSI) { return FSI->Kind == SK_Block || FSI->Kind == SK_Lambda || FSI->Kind == SK_CapturedRegion; } @@ -694,7 +694,7 @@ public: class BlockScopeInfo final : public CapturingScopeInfo { public: BlockDecl *TheDecl; - + /// TheScope - This is the scope for the block itself, which contains /// arguments etc. Scope *TheScope; @@ -711,8 +711,8 @@ public: ~BlockScopeInfo() override; - static bool classof(const FunctionScopeInfo *FSI) { - return FSI->Kind == SK_Block; + static bool classof(const FunctionScopeInfo *FSI) { + return FSI->Kind == SK_Block; } }; @@ -796,12 +796,12 @@ public: /// Whether the lambda contains an unexpanded parameter pack. bool ContainsUnexpandedParameterPack = false; - /// If this is a generic lambda, use this as the depth of + /// If this is a generic lambda, use this as the depth of /// each 'auto' parameter, during initial AST construction. unsigned AutoTemplateParameterDepth = 0; /// Store the list of the auto parameters for a generic lambda. - /// If this is a generic lambda, store the list of the auto + /// If this is a generic lambda, store the list of the auto /// parameters converted into TemplateTypeParmDecls into a vector /// that can be used to construct the generic lambda's template /// parameter list, during initial AST construction. @@ -811,19 +811,19 @@ public: /// list has been created (from the AutoTemplateParams) then /// store a reference to it (cache it to avoid reconstructing it). TemplateParameterList *GLTemplateParameterList = nullptr; - + /// Contains all variable-referring-expressions (i.e. DeclRefExprs /// or MemberExprs) that refer to local variables in a generic lambda /// or a lambda in a potentially-evaluated-if-used context. - /// - /// Potentially capturable variables of a nested lambda that might need - /// to be captured by the lambda are housed here. + /// + /// Potentially capturable variables of a nested lambda that might need + /// to be captured by the lambda are housed here. /// This is specifically useful for generic lambdas or /// lambdas within a potentially evaluated-if-used context. /// If an enclosing variable is named in an expression of a lambda nested - /// within a generic lambda, we don't always know know whether the variable + /// within a generic lambda, we don't always know know whether the variable /// will truly be odr-used (i.e. need to be captured) by that nested lambda, - /// until its instantiation. But we still need to capture it in the + /// until its instantiation. But we still need to capture it in the /// enclosing lambda if all intervening lambdas can capture the variable. llvm::SmallVector<Expr*, 4> PotentiallyCapturingExprs; @@ -867,10 +867,10 @@ public: return !AutoTemplateParams.empty() || GLTemplateParameterList; } - /// Add a variable that might potentially be captured by the - /// lambda and therefore the enclosing lambdas. - /// - /// This is also used by enclosing lambda's to speculatively capture + /// Add a variable that might potentially be captured by the + /// lambda and therefore the enclosing lambdas. + /// + /// This is also used by enclosing lambda's to speculatively capture /// variables that nested lambda's - depending on their enclosing /// specialization - might need to capture. /// Consider: @@ -879,7 +879,7 @@ public: /// void foo() { /// const int x = 10; /// auto L = [=](auto a) { // capture 'x' - /// return [=](auto b) { + /// return [=](auto b) { /// f(x, a); // we may or may not need to capture 'x' /// }; /// }; @@ -888,46 +888,46 @@ public: assert(isa<DeclRefExpr>(VarExpr) || isa<MemberExpr>(VarExpr)); PotentiallyCapturingExprs.push_back(VarExpr); } - + void addPotentialThisCapture(SourceLocation Loc) { PotentialThisCaptureLocation = Loc; } - bool hasPotentialThisCapture() const { - return PotentialThisCaptureLocation.isValid(); + bool hasPotentialThisCapture() const { + return PotentialThisCaptureLocation.isValid(); } /// Mark a variable's reference in a lambda as non-odr using. /// - /// For generic lambdas, if a variable is named in a potentially evaluated - /// expression, where the enclosing full expression is dependent then we + /// For generic lambdas, if a variable is named in a potentially evaluated + /// expression, where the enclosing full expression is dependent then we /// must capture the variable (given a default capture). - /// This is accomplished by recording all references to variables - /// (DeclRefExprs or MemberExprs) within said nested lambda in its array of + /// This is accomplished by recording all references to variables + /// (DeclRefExprs or MemberExprs) within said nested lambda in its array of /// PotentialCaptures. All such variables have to be captured by that lambda, /// except for as described below. - /// If that variable is usable as a constant expression and is named in a - /// manner that does not involve its odr-use (e.g. undergoes + /// If that variable is usable as a constant expression and is named in a + /// manner that does not involve its odr-use (e.g. undergoes /// lvalue-to-rvalue conversion, or discarded) record that it is so. Upon the /// act of analyzing the enclosing full expression (ActOnFinishFullExpr) /// if we can determine that the full expression is not instantiation- - /// dependent, then we can entirely avoid its capture. + /// dependent, then we can entirely avoid its capture. /// /// const int n = 0; /// [&] (auto x) { /// (void)+n + x; /// }; - /// Interestingly, this strategy would involve a capture of n, even though - /// it's obviously not odr-used here, because the full-expression is + /// Interestingly, this strategy would involve a capture of n, even though + /// it's obviously not odr-used here, because the full-expression is /// instantiation-dependent. It could be useful to avoid capturing such /// variables, even when they are referred to in an instantiation-dependent /// expression, if we can unambiguously determine that they shall never be /// odr-used. This would involve removal of the variable-referring-expression - /// from the array of PotentialCaptures during the lvalue-to-rvalue + /// from the array of PotentialCaptures during the lvalue-to-rvalue /// conversions. But per the working draft N3797, (post-chicago 2013) we must - /// capture such variables. + /// capture such variables. /// Before anyone is tempted to implement a strategy for not-capturing 'n', - /// consider the insightful warning in: + /// consider the insightful warning in: /// /cfe-commits/Week-of-Mon-20131104/092596.html /// "The problem is that the set of captures for a lambda is part of the ABI /// (since lambda layout can be made visible through inline functions and the @@ -937,32 +937,32 @@ public: /// building such a node. So we need a rule that anyone can implement and get /// exactly the same result". void markVariableExprAsNonODRUsed(Expr *CapturingVarExpr) { - assert(isa<DeclRefExpr>(CapturingVarExpr) + assert(isa<DeclRefExpr>(CapturingVarExpr) || isa<MemberExpr>(CapturingVarExpr)); NonODRUsedCapturingExprs.insert(CapturingVarExpr); } bool isVariableExprMarkedAsNonODRUsed(Expr *CapturingVarExpr) const { - assert(isa<DeclRefExpr>(CapturingVarExpr) + assert(isa<DeclRefExpr>(CapturingVarExpr) || isa<MemberExpr>(CapturingVarExpr)); return NonODRUsedCapturingExprs.count(CapturingVarExpr); } void removePotentialCapture(Expr *E) { PotentiallyCapturingExprs.erase( - std::remove(PotentiallyCapturingExprs.begin(), - PotentiallyCapturingExprs.end(), E), + std::remove(PotentiallyCapturingExprs.begin(), + PotentiallyCapturingExprs.end(), E), PotentiallyCapturingExprs.end()); } void clearPotentialCaptures() { PotentiallyCapturingExprs.clear(); PotentialThisCaptureLocation = SourceLocation(); } - unsigned getNumPotentialVariableCaptures() const { - return PotentiallyCapturingExprs.size(); + unsigned getNumPotentialVariableCaptures() const { + return PotentiallyCapturingExprs.size(); } - bool hasPotentialCaptures() const { - return getNumPotentialVariableCaptures() || - PotentialThisCaptureLocation.isValid(); + bool hasPotentialCaptures() const { + return getNumPotentialVariableCaptures() || + PotentialThisCaptureLocation.isValid(); } // When passed the index, returns the VarDecl and Expr associated diff --git a/include/clang/Sema/SemaInternal.h b/include/clang/Sema/SemaInternal.h index 86ab703a5b3a..c55e16a27cd3 100644 --- a/include/clang/Sema/SemaInternal.h +++ b/include/clang/Sema/SemaInternal.h @@ -45,7 +45,7 @@ inline bool IsVariableAConstantExpression(VarDecl *Var, ASTContext &Context) { const VarDecl *DefVD = nullptr; return !isa<ParmVarDecl>(Var) && Var->isUsableInConstantExpressions(Context) && - Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE(); + Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE(); } // Helper function to check whether D's attributes match current CUDA mode. @@ -60,13 +60,13 @@ inline bool DeclAttrsMatchCUDAMode(const LangOptions &LangOpts, Decl *D) { return isDeviceSideDecl == LangOpts.CUDAIsDevice; } -// Directly mark a variable odr-used. Given a choice, prefer to use -// MarkVariableReferenced since it does additional checks and then +// Directly mark a variable odr-used. Given a choice, prefer to use +// MarkVariableReferenced since it does additional checks and then // calls MarkVarDeclODRUsed. // If the variable must be captured: // - if FunctionScopeIndexToStopAt is null, capture it in the CurContext -// - else capture it in the DeclContext that maps to the -// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. +// - else capture it in the DeclContext that maps to the +// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. inline void MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, const unsigned *const FunctionScopeIndexToStopAt) { @@ -81,10 +81,10 @@ inline void MarkVarDeclODRUsed(VarDecl *Var, old = Loc; } QualType CaptureType, DeclRefType; - SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, + SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, /*EllipsisLoc*/ SourceLocation(), - /*BuildAndDiagnose*/ true, - CaptureType, DeclRefType, + /*BuildAndDiagnose*/ true, + CaptureType, DeclRefType, FunctionScopeIndexToStopAt); Var->markUsed(SemaRef.Context); diff --git a/include/clang/Sema/SemaLambda.h b/include/clang/Sema/SemaLambda.h index dfdc4ebc3643..8edb9b5c613d 100644 --- a/include/clang/Sema/SemaLambda.h +++ b/include/clang/Sema/SemaLambda.h @@ -25,11 +25,11 @@ class FunctionScopeInfo; class Sema; /// Examines the FunctionScopeInfo stack to determine the nearest -/// enclosing lambda (to the current lambda) that is 'capture-capable' for +/// enclosing lambda (to the current lambda) that is 'capture-capable' for /// the variable referenced in the current lambda (i.e. \p VarToCapture). /// If successful, returns the index into Sema's FunctionScopeInfo stack -/// of the capture-capable lambda's LambdaScopeInfo. -/// See Implementation for more detailed comments. +/// of the capture-capable lambda's LambdaScopeInfo. +/// See Implementation for more detailed comments. Optional<unsigned> getStackIndexOfNearestEnclosingCaptureCapableLambda( ArrayRef<const sema::FunctionScopeInfo *> FunctionScopes, diff --git a/include/clang/Sema/Template.h b/include/clang/Sema/Template.h index c0dee3e82d58..39b08e934be4 100644 --- a/include/clang/Sema/Template.h +++ b/include/clang/Sema/Template.h @@ -46,7 +46,7 @@ class VarDecl; /// Data structure that captures multiple levels of template argument /// lists for use in template instantiation. /// - /// Multiple levels of template arguments occur when instantiating the + /// Multiple levels of template arguments occur when instantiating the /// definitions of member templates. For example: /// /// \code @@ -63,7 +63,7 @@ class VarDecl; /// list will contain a template argument list (int) at depth 0 and a /// template argument list (17) at depth 1. class MultiLevelTemplateArgumentList { - /// The template argument list at a certain template depth + /// The template argument list at a certain template depth using ArgList = ArrayRef<TemplateArgument>; /// The template argument lists, stored from the innermost template @@ -73,17 +73,17 @@ class VarDecl; /// The number of outer levels of template arguments that are not /// being substituted. unsigned NumRetainedOuterLevels = 0; - + public: /// Construct an empty set of template argument lists. MultiLevelTemplateArgumentList() = default; - + /// Construct a single-level template argument list. - explicit + explicit MultiLevelTemplateArgumentList(const TemplateArgumentList &TemplateArgs) { addOuterTemplateArguments(&TemplateArgs); } - + /// Determine the number of levels in this template argument /// list. unsigned getNumLevels() const { @@ -102,7 +102,7 @@ class VarDecl; assert(Index < TemplateArgumentLists[getNumLevels() - Depth - 1].size()); return TemplateArgumentLists[getNumLevels() - Depth - 1][Index]; } - + /// Determine whether there is a non-NULL template argument at the /// given depth and index. /// @@ -112,13 +112,13 @@ class VarDecl; if (Depth < NumRetainedOuterLevels) return false; - + if (Index >= TemplateArgumentLists[getNumLevels() - Depth - 1].size()) return false; - + return !(*this)(Depth, Index).isNull(); } - + /// Clear out a specific template argument. void setArgument(unsigned Depth, unsigned Index, TemplateArgument Arg) { @@ -128,8 +128,8 @@ class VarDecl; TemplateArgumentLists[getNumLevels() - Depth - 1][Index]) = Arg; } - - /// Add a new outermost level to the multi-level template argument + + /// Add a new outermost level to the multi-level template argument /// list. void addOuterTemplateArguments(const TemplateArgumentList *TemplateArgs) { addOuterTemplateArguments(ArgList(TemplateArgs->data(), @@ -153,21 +153,21 @@ class VarDecl; /// Retrieve the innermost template argument list. const ArgList &getInnermost() const { - return TemplateArgumentLists.front(); + return TemplateArgumentLists.front(); } }; - + /// The context in which partial ordering of function templates occurs. enum TPOC { /// Partial ordering of function templates for a function call. TPOC_Call, - /// Partial ordering of function templates for a call to a + /// Partial ordering of function templates for a call to a /// conversion function. TPOC_Conversion, /// Partial ordering of function templates in other contexts, e.g., - /// taking the address of a function template or matching a function + /// taking the address of a function template or matching a function /// template specialization to a function template. TPOC_Other }; @@ -261,7 +261,7 @@ class VarDecl; /// The set of argument packs we've allocated. SmallVector<DeclArgumentPack *, 1> ArgumentPacks; - + /// The outer scope, which contains local variable /// definitions from some other instantiation (that may not be /// relevant to this particular scope). @@ -273,17 +273,17 @@ class VarDecl; /// Whether to combine this scope with the outer scope, such that /// lookup will search our outer scope. bool CombineWithOuterScope; - + /// If non-NULL, the template parameter pack that has been /// partially substituted per C++0x [temp.arg.explicit]p9. NamedDecl *PartiallySubstitutedPack = nullptr; - + /// If \c PartiallySubstitutedPack is non-null, the set of /// explicitly-specified template arguments in that pack. - const TemplateArgument *ArgsInPartiallySubstitutedPack; - - /// If \c PartiallySubstitutedPack, the number of - /// explicitly-specified template arguments in + const TemplateArgument *ArgsInPartiallySubstitutedPack; + + /// If \c PartiallySubstitutedPack, the number of + /// explicitly-specified template arguments in /// ArgsInPartiallySubstitutedPack. unsigned NumArgsInPartiallySubstitutedPack; @@ -301,17 +301,17 @@ class VarDecl; ~LocalInstantiationScope() { Exit(); } - + const Sema &getSema() const { return SemaRef; } /// Exit this local instantiation scope early. void Exit() { if (Exited) return; - + for (unsigned I = 0, N = ArgumentPacks.size(); I != N; ++I) delete ArgumentPacks[I]; - + SemaRef.CurrentInstantiationScope = Outer; Exited = true; } @@ -381,9 +381,9 @@ class VarDecl; void InstantiatedLocal(const Decl *D, Decl *Inst); void InstantiatedLocalPackArg(const Decl *D, ParmVarDecl *Inst); void MakeInstantiatedLocalArgPack(const Decl *D); - + /// Note that the given parameter pack has been partially substituted - /// via explicit specification of template arguments + /// via explicit specification of template arguments /// (C++0x [temp.arg.explicit]p9). /// /// \param Pack The parameter pack, which will always be a template @@ -394,7 +394,7 @@ class VarDecl; /// /// \param NumExplicitArgs The number of explicitly-specified template /// arguments provided for this parameter pack. - void SetPartiallySubstitutedPack(NamedDecl *Pack, + void SetPartiallySubstitutedPack(NamedDecl *Pack, const TemplateArgument *ExplicitArgs, unsigned NumExplicitArgs); @@ -416,7 +416,7 @@ class VarDecl; }; class TemplateDeclInstantiator - : public DeclVisitor<TemplateDeclInstantiator, Decl *> + : public DeclVisitor<TemplateDeclInstantiator, Decl *> { Sema &SemaRef; Sema::ArgumentPackSubstitutionIndexRAII SubstIndex; @@ -562,7 +562,7 @@ class VarDecl; template<typename T> Decl *instantiateUnresolvedUsingDecl(T *D, bool InstantiatingPackElement = false); - }; + }; } // namespace clang diff --git a/include/clang/Serialization/ASTBitCodes.h b/include/clang/Serialization/ASTBitCodes.h index 76bc818557a9..430fc48379fe 100644 --- a/include/clang/Serialization/ASTBitCodes.h +++ b/include/clang/Serialization/ASTBitCodes.h @@ -55,16 +55,16 @@ namespace serialization { const unsigned VERSION_MINOR = 0; /// An ID number that refers to an identifier in an AST file. - /// + /// /// The ID numbers of identifiers are consecutive (in order of discovery) /// and start at 1. 0 is reserved for NULL. using IdentifierID = uint32_t; - + /// An ID number that refers to a declaration in an AST file. /// /// The ID numbers of declarations are consecutive (in order of - /// discovery), with values below NUM_PREDEF_DECL_IDS being reserved. - /// At the start of a chain of precompiled headers, declaration ID 1 is + /// discovery), with values below NUM_PREDEF_DECL_IDS being reserved. + /// At the start of a chain of precompiled headers, declaration ID 1 is /// used for the translation unit declaration. using DeclID = uint32_t; @@ -98,14 +98,14 @@ namespace serialization { TypeID asTypeID(unsigned FastQuals) const { if (Idx == uint32_t(-1)) return TypeID(-1); - + return (Idx << Qualifiers::FastWidth) | FastQuals; } static TypeIdx fromTypeID(TypeID ID) { if (ID == TypeID(-1)) return TypeIdx(-1); - + return TypeIdx(ID >> Qualifiers::FastWidth); } }; @@ -124,7 +124,7 @@ namespace serialization { } static unsigned getHashValue(QualType T) { - assert(!T.getLocalFastQualifiers() && + assert(!T.getLocalFastQualifiers() && "hash invalid for types with fast quals"); uintptr_t v = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr()); return (unsigned(v) >> 4) ^ (unsigned(v) >> 9); @@ -155,8 +155,8 @@ namespace serialization { /// The number of predefined selector IDs. const unsigned int NUM_PREDEF_SELECTOR_IDS = 1; - - /// An ID number that refers to a set of CXXBaseSpecifiers in an + + /// An ID number that refers to a set of CXXBaseSpecifiers in an /// AST file. using CXXBaseSpecifiersID = uint32_t; @@ -170,7 +170,7 @@ namespace serialization { /// An ID number that refers to a submodule in a module file. using SubmoduleID = uint32_t; - + /// The number of predefined submodule IDs. const unsigned int NUM_PREDEF_SUBMODULE_IDS = 1; @@ -311,7 +311,7 @@ namespace serialization { /// generate the AST file, including both its file ID and its /// name. ORIGINAL_FILE, - + /// The directory that the PCH was originally created in. ORIGINAL_PCH_DIR, @@ -706,15 +706,15 @@ namespace serialization { enum PreprocessorDetailRecordTypes { /// Describes a macro expansion within the preprocessing record. PPD_MACRO_EXPANSION = 0, - + /// Describes a macro definition within the preprocessing record. PPD_MACRO_DEFINITION = 1, - + /// Describes an inclusion directive within the preprocessing /// record. PPD_INCLUSION_DIRECTIVE = 2 }; - + /// Record types used within a submodule description block. enum SubmoduleRecordTypes { /// Metadata for submodules as a whole. @@ -737,11 +737,11 @@ namespace serialization { /// Specifies an umbrella directory. SUBMODULE_UMBRELLA_DIR = 5, - /// Specifies the submodules that are imported by this + /// Specifies the submodules that are imported by this /// submodule. SUBMODULE_IMPORTS = 6, - /// Specifies the submodules that are re-exported from this + /// Specifies the submodules that are re-exported from this /// submodule. SUBMODULE_EXPORTS = 7, @@ -1203,7 +1203,7 @@ namespace serialization { /// C ucontext_t typedef type SPECIAL_TYPE_UCONTEXT_T = 7 }; - + /// The number of special type IDs. const unsigned NumSpecialTypeIDs = 8; @@ -1211,7 +1211,7 @@ namespace serialization { /// /// These declaration IDs correspond to predefined declarations in the AST /// context, such as the NULL declaration ID. Such declarations are never - /// actually serialized, since they will be built by the AST context when + /// actually serialized, since they will be built by the AST context when /// it is created. enum PredefinedDeclIDs { /// The NULL declaration. @@ -1279,7 +1279,7 @@ namespace serialization { /// Record code for a list of local redeclarations of a declaration. /// This can occur within DECLTYPES_BLOCK_ID. const unsigned int LOCAL_REDECLARATIONS = 50; - + /// Record codes for each kind of declaration. /// /// These constants describe the declaration records that can occur within @@ -1539,7 +1539,7 @@ namespace serialization { /// /// These constants describe the records that describe statements /// or expressions. These records occur within type and declarations - /// block, so they begin with record values of 128. Each constant + /// block, so they begin with record values of 128. Each constant /// describes a record for a specific statement or expression class in the /// AST. enum StmtCode { @@ -1741,7 +1741,7 @@ namespace serialization { EXPR_OBJC_BOXED_EXPRESSION, EXPR_OBJC_ARRAY_LITERAL, EXPR_OBJC_DICTIONARY_LITERAL, - + /// An ObjCEncodeExpr record. EXPR_OBJC_ENCODE, @@ -1800,7 +1800,7 @@ namespace serialization { EXPR_OBJC_AVAILABILITY_CHECK, // C++ - + /// A CXXCatchStmt record. STMT_CXX_CATCH, @@ -1862,9 +1862,9 @@ namespace serialization { EXPR_CXX_NEW, // CXXNewExpr EXPR_CXX_DELETE, // CXXDeleteExpr EXPR_CXX_PSEUDO_DESTRUCTOR, // CXXPseudoDestructorExpr - + EXPR_EXPR_WITH_CLEANUPS, // ExprWithCleanups - + EXPR_CXX_DEPENDENT_SCOPE_MEMBER, // CXXDependentScopeMemberExpr EXPR_CXX_DEPENDENT_SCOPE_DECL_REF, // DependentScopeDeclRefExpr EXPR_CXX_UNRESOLVED_CONSTRUCT, // CXXUnresolvedConstructExpr @@ -1878,7 +1878,7 @@ namespace serialization { EXPR_BINARY_CONDITIONAL_OPERATOR, // BinaryConditionalOperator EXPR_TYPE_TRAIT, // TypeTraitExpr EXPR_ARRAY_TYPE_TRAIT, // ArrayTypeTraitIntExpr - + EXPR_PACK_EXPANSION, // PackExpansionExpr EXPR_SIZEOF_PACK, // SizeOfPackExpr EXPR_SUBST_NON_TYPE_TEMPLATE_PARM, // SubstNonTypeTemplateParmExpr @@ -1888,7 +1888,7 @@ namespace serialization { EXPR_CXX_FOLD, // CXXFoldExpr // CUDA - EXPR_CUDA_KERNEL_CALL, // CUDAKernelCallExpr + EXPR_CUDA_KERNEL_CALL, // CUDAKernelCallExpr // OpenCL EXPR_ASTYPE, // AsTypeExpr @@ -1998,22 +1998,22 @@ namespace serialization { // Offset into the array of redeclaration chains. unsigned Offset; - + friend bool operator<(const LocalRedeclarationsInfo &X, const LocalRedeclarationsInfo &Y) { return X.FirstID < Y.FirstID; } - + friend bool operator>(const LocalRedeclarationsInfo &X, const LocalRedeclarationsInfo &Y) { return X.FirstID > Y.FirstID; } - + friend bool operator<=(const LocalRedeclarationsInfo &X, const LocalRedeclarationsInfo &Y) { return X.FirstID <= Y.FirstID; } - + friend bool operator>=(const LocalRedeclarationsInfo &X, const LocalRedeclarationsInfo &Y) { return X.FirstID >= Y.FirstID; @@ -2027,22 +2027,22 @@ namespace serialization { // Offset into the array of category lists. unsigned Offset; - + friend bool operator<(const ObjCCategoriesInfo &X, const ObjCCategoriesInfo &Y) { return X.DefinitionID < Y.DefinitionID; } - + friend bool operator>(const ObjCCategoriesInfo &X, const ObjCCategoriesInfo &Y) { return X.DefinitionID > Y.DefinitionID; } - + friend bool operator<=(const ObjCCategoriesInfo &X, const ObjCCategoriesInfo &Y) { return X.DefinitionID <= Y.DefinitionID; } - + friend bool operator>=(const ObjCCategoriesInfo &X, const ObjCCategoriesInfo &Y) { return X.DefinitionID >= Y.DefinitionID; diff --git a/include/clang/Serialization/ASTReader.h b/include/clang/Serialization/ASTReader.h index 82a74a64443d..0eecb6f5d65a 100644 --- a/include/clang/Serialization/ASTReader.h +++ b/include/clang/Serialization/ASTReader.h @@ -591,7 +591,7 @@ private: llvm::DenseMap<serialization::DeclID, DeclContextVisibleUpdates> PendingVisibleUpdates; - /// The set of C++ or Objective-C classes that have forward + /// The set of C++ or Objective-C classes that have forward /// declarations that have not yet been linked to their definitions. llvm::SmallPtrSet<Decl *, 4> PendingDefinitions; @@ -662,10 +662,10 @@ private: /// This vector is indexed by the Submodule ID (-1). NULL submodule entries /// indicate that the particular submodule ID has not yet been loaded. SmallVector<Module *, 2> SubmodulesLoaded; - + using GlobalSubmoduleMapType = ContinuousRangeMap<serialization::SubmoduleID, ModuleFile *, 4>; - + /// Mapping from global submodule IDs to the module file in which the /// submodule resides along with the offset that should be added to the /// global submodule ID to produce a local ID. @@ -678,12 +678,12 @@ private: /// A mapping from each of the hidden submodules to the deserialized /// declarations in that submodule that could be made visible. HiddenNamesMapType HiddenNamesMap; - + /// A module import, export, or conflict that hasn't yet been resolved. struct UnresolvedModuleRef { /// The file in which this module resides. ModuleFile *File; - + /// The module that is importing or exporting. Module *Mod; @@ -699,11 +699,11 @@ private: /// String data. StringRef String; }; - - /// The set of module imports and exports that still need to be + + /// The set of module imports and exports that still need to be /// resolved. SmallVector<UnresolvedModuleRef, 2> UnresolvedModuleRefs; - + /// A vector containing selectors that have already been loaded. /// /// This vector is indexed by the Selector ID (-1). NULL selector @@ -1056,7 +1056,7 @@ private: /// Objective-C protocols. std::deque<InterestingDecl> PotentiallyInterestingDecls; - /// The list of redeclaration chains that still need to be + /// The list of redeclaration chains that still need to be /// reconstructed, and the local offset to the corresponding list /// of redeclarations. SmallVector<std::pair<Decl *, uint64_t>, 16> PendingDeclChains; @@ -1117,14 +1117,14 @@ private: using KeyDeclsMap = llvm::DenseMap<Decl *, SmallVector<serialization::DeclID, 2>>; - + /// A mapping from canonical declarations to the set of global /// declaration IDs for key declaration that have been merged with that /// canonical declaration. A key declaration is a formerly-canonical /// declaration whose module did not import any other key declaration for that /// entity. These are the IDs that we use as keys when finding redecl chains. KeyDeclsMap KeyDecls; - + /// A mapping from DeclContexts to the semantic DeclContext that we /// are treating as the definition of the entity. This is used, for instance, /// when merging implicit instantiations of class templates across modules. @@ -1625,7 +1625,7 @@ public: /// Determine whether we tried to load the global index, but failed, /// e.g., because it is out-of-date or does not exist. bool isGlobalIndexUnavailable() const; - + /// Initializes the ASTContext void InitializeContext(); @@ -1654,7 +1654,7 @@ public: /// Retrieve the name of the original source file name for the primary /// module file. StringRef getOriginalSourceFile() { - return ModuleMgr.getPrimaryModule().OriginalSourceFileName; + return ModuleMgr.getPrimaryModule().OriginalSourceFileName; } /// Retrieve the name of the original source file name directly from @@ -1741,7 +1741,7 @@ public: unsigned getTotalNumSubmodules() const { return static_cast<unsigned>(SubmodulesLoaded.size()); } - + /// Returns the number of selectors found in the chain. unsigned getTotalNumSelectors() const { return static_cast<unsigned>(SelectorsLoaded.size()); @@ -1839,15 +1839,15 @@ public: return cast_or_null<T>(GetLocalDecl(F, LocalID)); } - /// Map a global declaration ID into the declaration ID used to + /// Map a global declaration ID into the declaration ID used to /// refer to this declaration within the given module fule. /// /// \returns the global ID of the given declaration as known in the given /// module file. - serialization::DeclID + serialization::DeclID mapGlobalIDToModuleFileGlobalID(ModuleFile &M, serialization::DeclID GlobalID); - + /// Reads a declaration ID from the given position in a record in the /// given module. /// @@ -2067,7 +2067,7 @@ public: /// Retrieve the global submodule ID given a module and its local ID /// number. - serialization::SubmoduleID + serialization::SubmoduleID getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID); /// Retrieve the submodule that corresponds to a global submodule ID. diff --git a/include/clang/Serialization/ASTWriter.h b/include/clang/Serialization/ASTWriter.h index a93579930ff5..7ff5d65bd7d0 100644 --- a/include/clang/Serialization/ASTWriter.h +++ b/include/clang/Serialization/ASTWriter.h @@ -416,7 +416,7 @@ private: /// The set of Objective-C class that have categories we /// should serialize. llvm::SetVector<ObjCInterfaceDecl *> ObjCClassesWithCategories; - + /// The set of declarations that may have redeclaration chains that /// need to be serialized. llvm::SmallVector<const Decl *, 16> Redeclarations; @@ -424,7 +424,7 @@ private: /// A cache of the first local declaration for "interesting" /// redeclaration chains. llvm::DenseMap<const Decl *, const Decl *> FirstLocalDeclCache; - + /// Mapping from SwitchCase statements to IDs. llvm::DenseMap<SwitchCase *, unsigned> SwitchCaseIDs; @@ -475,7 +475,7 @@ private: void WriteHeaderSearch(const HeaderSearch &HS); void WritePreprocessorDetail(PreprocessingRecord &PPRec); void WriteSubmodules(Module *WritingModule); - + void WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag, bool isModule); diff --git a/include/clang/Serialization/ContinuousRangeMap.h b/include/clang/Serialization/ContinuousRangeMap.h index 2f909965db7e..73bf2ed10f04 100644 --- a/include/clang/Serialization/ContinuousRangeMap.h +++ b/include/clang/Serialization/ContinuousRangeMap.h @@ -72,14 +72,14 @@ public: "Must insert keys in order."); Rep.push_back(Val); } - + void insertOrReplace(const value_type &Val) { iterator I = std::lower_bound(Rep.begin(), Rep.end(), Val, Compare()); if (I != Rep.end() && I->first == Val.first) { I->second = Val.second; return; } - + Rep.insert(I, Val); } @@ -106,7 +106,7 @@ public: reference back() { return Rep.back(); } const_reference back() const { return Rep.back(); } - + /// An object that helps properly build a continuous range map /// from a set of values. class Builder { @@ -116,7 +116,7 @@ public: explicit Builder(ContinuousRangeMap &Self) : Self(Self) {} Builder(const Builder&) = delete; Builder &operator=(const Builder&) = delete; - + ~Builder() { llvm::sort(Self.Rep.begin(), Self.Rep.end(), Compare()); std::unique(Self.Rep.begin(), Self.Rep.end(), @@ -128,7 +128,7 @@ public: return A == B; }); } - + void insert(const value_type &Val) { Self.Rep.push_back(Val); } diff --git a/include/clang/Serialization/GlobalModuleIndex.h b/include/clang/Serialization/GlobalModuleIndex.h index f48d0cf17c49..d47fe9517d76 100644 --- a/include/clang/Serialization/GlobalModuleIndex.h +++ b/include/clang/Serialization/GlobalModuleIndex.h @@ -115,7 +115,7 @@ class GlobalModuleIndex { /// The number of identifier lookup hits, where we recognize the /// identifier. unsigned NumIdentifierLookupHits; - + /// Internal constructor. Use \c readIndex() to read an index. explicit GlobalModuleIndex(std::unique_ptr<llvm::MemoryBuffer> Buffer, llvm::BitstreamCursor Cursor); @@ -167,7 +167,7 @@ public: /// A set of module files in which we found a result. typedef llvm::SmallPtrSet<ModuleFile *, 4> HitSet; - + /// Look for all of the module files with information about the given /// identifier, e.g., a global function, variable, or type with that name. /// diff --git a/include/clang/Serialization/Module.h b/include/clang/Serialization/Module.h index 653981b1427c..d6e78e693109 100644 --- a/include/clang/Serialization/Module.h +++ b/include/clang/Serialization/Module.h @@ -173,7 +173,7 @@ public: /// The generation of which this module file is a part. unsigned Generation; - + /// The memory buffer that stores the data associated with /// this AST file, owned by the PCMCache in the ModuleManager. llvm::MemoryBuffer *Buffer; @@ -358,17 +358,17 @@ public: /// the header files. void *HeaderFileInfoTable = nullptr; - // === Submodule information === + // === Submodule information === /// The number of submodules in this module. unsigned LocalNumSubmodules = 0; - + /// Base submodule ID for submodules local to this module. serialization::SubmoduleID BaseSubmoduleID = 0; - + /// Remapping table for submodule IDs in this module. ContinuousRangeMap<uint32_t, int, 2> SubmoduleRemap; - + // === Selectors === /// The number of selectors new to this file. @@ -431,13 +431,13 @@ public: const serialization::DeclID *FileSortedDecls = nullptr; unsigned NumFileSortedDecls = 0; - /// Array of category list location information within this + /// Array of category list location information within this /// module file, sorted by the definition ID. const serialization::ObjCCategoriesInfo *ObjCCategoriesMap = nullptr; - + /// The number of redeclaration info entries in ObjCCategoriesMap. unsigned LocalNumObjCCategoriesInMap = 0; - + /// The Objective-C category lists for categories known to this /// module. SmallVector<uint64_t, 1> ObjCCategories; diff --git a/include/clang/Serialization/ModuleFileExtension.h b/include/clang/Serialization/ModuleFileExtension.h index f7bdcec598f1..f70218e329af 100644 --- a/include/clang/Serialization/ModuleFileExtension.h +++ b/include/clang/Serialization/ModuleFileExtension.h @@ -26,7 +26,7 @@ namespace clang { class ASTReader; class ASTWriter; class Sema; - + namespace serialization { class ModuleFile; } // end namespace serialization @@ -128,7 +128,7 @@ public: /// Abstract base class that reads a module file extension block from /// a module file. /// -/// Subclasses +/// Subclasses class ModuleFileExtensionReader { ModuleFileExtension *Extension; diff --git a/include/clang/Serialization/ModuleManager.h b/include/clang/Serialization/ModuleManager.h index e101e60b21a3..cfc9a2ef112c 100644 --- a/include/clang/Serialization/ModuleManager.h +++ b/include/clang/Serialization/ModuleManager.h @@ -82,7 +82,7 @@ class ModuleManager { /// The visitation order. SmallVector<ModuleFile *, 4> VisitOrder; - + /// The list of module files that both we and the global module index /// know about. /// @@ -150,13 +150,13 @@ public: /// Forward iterator end-point to traverse all loaded modules ModuleIterator end() { return Chain.end(); } - + /// Const forward iterator to traverse all loaded modules. ModuleConstIterator begin() const { return Chain.begin(); } /// Const forward iterator end-point to traverse all loaded modules ModuleConstIterator end() const { return Chain.end(); } - + /// Reverse iterator to traverse all loaded modules. ModuleReverseIterator rbegin() { return Chain.rbegin(); } @@ -172,14 +172,14 @@ public: /// Returns the primary module associated with the manager, that is, /// the first module loaded ModuleFile &getPrimaryModule() { return *Chain[0]; } - + /// Returns the primary module associated with the manager, that is, /// the first module loaded. ModuleFile &getPrimaryModule() const { return *Chain[0]; } - + /// Returns the module associated with the given index ModuleFile &operator[](unsigned Index) const { return *Chain[Index]; } - + /// Returns the module associated with the given file name. ModuleFile *lookupByFileName(StringRef FileName) const; @@ -191,7 +191,7 @@ public: /// Returns the in-memory (virtual file) buffer with the given name std::unique_ptr<llvm::MemoryBuffer> lookupBuffer(StringRef Name); - + /// Number of modules loaded unsigned size() const { return Chain.size(); } diff --git a/include/clang/StaticAnalyzer/Checkers/Checkers.td b/include/clang/StaticAnalyzer/Checkers/Checkers.td index ab0e4af1361b..9e53460f6e93 100644 --- a/include/clang/StaticAnalyzer/Checkers/Checkers.td +++ b/include/clang/StaticAnalyzer/Checkers/Checkers.td @@ -276,6 +276,10 @@ def ReturnUndefChecker : Checker<"UndefReturn">, let ParentPackage = Cplusplus in { +def InnerPointerChecker : Checker<"InnerPointer">, + HelpText<"Check for inner pointers of C++ containers used after re/deallocation">, + DescFile<"InnerPointerChecker.cpp">; + def NewDeleteChecker : Checker<"NewDelete">, HelpText<"Check for double-free and use-after-free problems. Traces memory managed by new/delete.">, DescFile<"MallocChecker.cpp">; @@ -305,10 +309,6 @@ def DeleteWithNonVirtualDtorChecker : Checker<"DeleteWithNonVirtualDtor">, "destructor in their base class">, DescFile<"DeleteWithNonVirtualDtorChecker.cpp">; -def InnerPointerChecker : Checker<"InnerPointer">, - HelpText<"Check for inner pointers of C++ containers used after re/deallocation">, - DescFile<"InnerPointerChecker.cpp">; - def IteratorRangeChecker : Checker<"IteratorRange">, HelpText<"Check for iterators used outside their valid ranges">, DescFile<"IteratorChecker.cpp">; @@ -440,7 +440,7 @@ def MallocOverflowSecurityChecker : Checker<"MallocOverflow">, DescFile<"MallocOverflowSecurityChecker.cpp">; // Operating systems specific PROT_READ/PROT_WRITE values is not implemented, -// the defaults are correct for several common operating systems though, +// the defaults are correct for several common operating systems though, // but may need to be overridden via the related analyzer-config flags. def MmapWriteExecChecker : Checker<"MmapWriteExec">, HelpText<"Warn on mmap() calls that are both writable and executable">, diff --git a/include/clang/StaticAnalyzer/Checkers/ObjCRetainCount.h b/include/clang/StaticAnalyzer/Checkers/ObjCRetainCount.h index e5e857e97029..f5a06394b187 100644 --- a/include/clang/StaticAnalyzer/Checkers/ObjCRetainCount.h +++ b/include/clang/StaticAnalyzer/Checkers/ObjCRetainCount.h @@ -136,7 +136,7 @@ public: // by inlining the function NoRetHard }; - + /// Determines the object kind of a tracked object. enum ObjKind { /// Indicates that the tracked object is a CF object. This is @@ -153,30 +153,30 @@ public: private: Kind K; ObjKind O; - + RetEffect(Kind k, ObjKind o = AnyObj) : K(k), O(o) {} - + public: Kind getKind() const { return K; } - + ObjKind getObjKind() const { return O; } - + bool isOwned() const { return K == OwnedSymbol || K == OwnedWhenTrackedReceiver; } - + bool notOwned() const { return K == NotOwnedSymbol; } - + bool operator==(const RetEffect &Other) const { return K == Other.K && O == Other.O; } - + static RetEffect MakeOwnedWhenTrackedReceiver() { return RetEffect(OwnedWhenTrackedReceiver, ObjC); } - + static RetEffect MakeOwned(ObjKind o) { return RetEffect(OwnedSymbol, o); } diff --git a/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h b/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h index 9d292cfddb0c..7586f7e0835b 100644 --- a/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h +++ b/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h @@ -130,23 +130,23 @@ public: /// Pair of checker name and enable/disable. std::vector<std::pair<std::string, bool>> CheckersControlList; - + /// A key-value table of use-specified configuration values. ConfigTable Config; AnalysisStores AnalysisStoreOpt = RegionStoreModel; AnalysisConstraints AnalysisConstraintsOpt = RangeConstraintsModel; AnalysisDiagClients AnalysisDiagOpt = PD_HTML; AnalysisPurgeMode AnalysisPurgeOpt = PurgeStmt; - + std::string AnalyzeSpecificFunction; /// Store full compiler invocation for reproducible instructions in the /// generated report. std::string FullCompilerInvocation; - + /// The maximum number of times the analyzer visits a block. unsigned maxBlockVisitOnPath; - + /// Disable all analyzer checks. /// /// This flag allows one to disable analyzer checks on the code processed by @@ -170,21 +170,21 @@ public: /// precision until we have a better way to lazily evaluate such logic. The /// downside is that it eagerly bifurcates paths. unsigned eagerlyAssumeBinOpBifurcation : 1; - + unsigned TrimGraph : 1; unsigned visualizeExplodedGraphWithGraphViz : 1; unsigned visualizeExplodedGraphWithUbiGraph : 1; unsigned UnoptimizedCFG : 1; unsigned PrintStats : 1; - + /// Do not re-analyze paths leading to exhausted nodes with a different /// strategy. We get better code coverage when retry is enabled. unsigned NoRetryExhausted : 1; - + /// The inlining stack depth limit. // Cap the stack depth at 4 calls (5 stack frames, base + 4 calls). unsigned InlineMaxStackDepth = 5; - + /// The mode of function selection used during inlining. AnalysisInliningMode InliningMode = NoRedundancy; @@ -211,7 +211,7 @@ private: UMK_Deep = 2 }; - /// Controls the high-level analyzer mode, which influences the default + /// Controls the high-level analyzer mode, which influences the default /// settings for some of the lower-level config options (such as IPAMode). /// \sa getUserMode UserModeKind UserMode = UMK_NotSet; @@ -221,7 +221,7 @@ private: /// Controls which C++ member functions will be considered for inlining. CXXInlineableMemberKind CXXMemberInliningMode; - + /// \sa includeImplicitDtorsInCFG Optional<bool> IncludeImplicitDtorsInCFG; @@ -239,7 +239,7 @@ private: /// \sa mayInlineCXXStandardLibrary Optional<bool> InlineCXXStandardLibrary; - + /// \sa includeScopesInCFG Optional<bool> IncludeScopesInCFG; @@ -722,9 +722,9 @@ public: /// the option will be ignored. bool shouldElideConstructors(); }; - + using AnalyzerOptionsRef = IntrusiveRefCntPtr<AnalyzerOptions>; - + } // namespace clang #endif // LLVM_CLANG_STATICANALYZER_CORE_ANALYZEROPTIONS_H diff --git a/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h b/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h index 111e1d1e8e20..9041f4c1afbd 100644 --- a/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h +++ b/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h @@ -74,7 +74,7 @@ using DiagnosticForConsumerMapTy = /// This class provides an interface through which checkers can create /// individual bug reports. class BugReport : public llvm::ilist_node<BugReport> { -public: +public: class NodeResolver { virtual void anchor(); @@ -102,7 +102,7 @@ protected: PathDiagnosticLocation Location; PathDiagnosticLocation UniqueingLocation; const Decl *UniqueingDecl; - + const ExplodedNode *ErrorNode = nullptr; SmallVector<SourceRange, 4> Ranges; ExtraTextList ExtraText; @@ -220,12 +220,12 @@ public: /// Disable all path pruning when generating a PathDiagnostic. void disablePathPruning() { DoNotPrunePath = true; } - + void markInteresting(SymbolRef sym); void markInteresting(const MemRegion *R); void markInteresting(SVal V); void markInteresting(const LocationContext *LC); - + bool isInteresting(SymbolRef sym); bool isInteresting(const MemRegion *R); bool isInteresting(SVal V); @@ -251,11 +251,11 @@ public: void markInvalid(const void *Tag, const void *Data) { Invalidations.insert(std::make_pair(Tag, Data)); } - + /// Return the canonical declaration, be it a method or class, where /// this issue semantically occurred. const Decl *getDeclWithIssue() const; - + /// Specifically set the Decl where an issue occurred. This isn't necessary /// for BugReports that cover a path as it will be automatically inferred. void setDeclWithIssue(const Decl *declWithIssue) { @@ -290,7 +290,7 @@ public: /// This allows for addition of meta data to the diagnostic. /// - /// Currently, only the HTMLDiagnosticClient knows how to display it. + /// Currently, only the HTMLDiagnosticClient knows how to display it. void addExtraText(StringRef S) { ExtraText.push_back(S); } @@ -310,7 +310,7 @@ public: PathDiagnosticLocation getUniqueingLocation() const { return UniqueingLocation; } - + /// Get the declaration containing the uniqueing location. const Decl *getUniqueingDecl() const { return UniqueingDecl; diff --git a/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h b/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h index 92118b0fbee2..da019f83c214 100644 --- a/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h +++ b/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h @@ -246,7 +246,7 @@ public: BugReport &BR) override; }; -/// When a region containing undefined value or '0' value is passed +/// When a region containing undefined value or '0' value is passed /// as an argument in a call, marks the call as interesting. /// /// As a result, BugReporter will not prune the path through the function even diff --git a/include/clang/StaticAnalyzer/Core/BugReporter/BugType.h b/include/clang/StaticAnalyzer/Core/BugReporter/BugType.h index c723f31aec26..3c1f8f718a3b 100644 --- a/include/clang/StaticAnalyzer/Core/BugReporter/BugType.h +++ b/include/clang/StaticAnalyzer/Core/BugReporter/BugType.h @@ -52,7 +52,7 @@ public: // FIXME: This is a workaround to ensure that the correct check name is used // The check names are set after the constructors are run. // In case the BugType object is initialized in the checker's ctor - // the Check field will be empty. To circumvent this problem we use + // the Check field will be empty. To circumvent this problem we use // CheckerBase whenever it is possible. StringRef CheckName = Checker ? Checker->getCheckName().getName() : Check.getName(); diff --git a/include/clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h b/include/clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h index b18d3c9b3031..b0bb12feba20 100644 --- a/include/clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h +++ b/include/clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h @@ -71,17 +71,17 @@ public: PDFileEntry(llvm::FoldingSetNodeID &NodeID) : NodeID(NodeID) {} using ConsumerFiles = std::vector<std::pair<StringRef, StringRef>>; - + /// A vector of <consumer,file> pairs. ConsumerFiles files; - + /// A precomputed hash tag used for uniquing PDFileEntry objects. const llvm::FoldingSetNodeID NodeID; /// Used for profiling in the FoldingSet. void Profile(llvm::FoldingSetNodeID &ID) { ID = NodeID; } }; - + class FilesMade { llvm::BumpPtrAllocator Alloc; llvm::FoldingSet<PDFileEntry> Set; @@ -94,7 +94,7 @@ public: void addDiagnostic(const PathDiagnostic &PD, StringRef ConsumerName, StringRef fileName); - + PDFileEntry::ConsumerFiles *getFiles(const PathDiagnostic &PD); }; @@ -127,7 +127,7 @@ public: virtual PathGenerationScheme getGenerationScheme() const { return Minimal; } virtual bool supportsLogicalOpControlFlow() const { return false; } - + /// Return true if the PathDiagnosticConsumer supports individual /// PathDiagnostics that span multiple files. virtual bool supportsCrossFileDiagnostics() const { return false; } @@ -322,12 +322,12 @@ public: void flatten(); const SourceManager& getManager() const { assert(isValid()); return *SM; } - + void Profile(llvm::FoldingSetNodeID &ID) const; void dump() const; - /// Given an exploded node, retrieve the statement that should be used + /// Given an exploded node, retrieve the statement that should be used /// for the diagnostic location. static const Stmt *getStmt(const ExplodedNode *N); @@ -354,7 +354,7 @@ public: Start.flatten(); End.flatten(); } - + void Profile(llvm::FoldingSetNodeID &ID) const { Start.Profile(ID); End.Profile(ID); @@ -378,7 +378,7 @@ private: /// In the containing bug report, this piece is the last piece from /// the main source file. bool LastInMainSourceFile = false; - + /// A constant string that can be used to tag the PathDiagnosticPiece, /// typically with the identification of the creator. The actual pointer /// value is meant to be an identifier; the string itself is useful for @@ -401,14 +401,14 @@ public: /// Tag this PathDiagnosticPiece with the given C-string. void setTag(const char *tag) { Tag = tag; } - + /// Return the opaque tag (if any) on the PathDiagnosticPiece. const void *getTag() const { return Tag.data(); } - + /// Return the string representation of the tag. This is useful /// for debugging. StringRef getTagStr() const { return Tag; } - + /// getDisplayHint - Return a hint indicating where the diagnostic should /// be displayed by the PathDiagnosticConsumer. DisplayHint getDisplayHint() const { return Hint; } @@ -488,7 +488,7 @@ public: /// Interface for classes constructing Stack hints. /// -/// If a PathDiagnosticEvent occurs in a different frame than the final +/// If a PathDiagnosticEvent occurs in a different frame than the final /// diagnostic the hints can be used to summarize the effect of the call. class StackHintGenerator { public: @@ -563,12 +563,12 @@ public: bool hasCallStackHint() { return (bool)CallStackHint; } - /// Produce the hint for the given node. The node contains + /// Produce the hint for the given node. The node contains /// information about the call for which the diagnostic can be generated. std::string getCallStackMessage(const ExplodedNode *N) { if (CallStackHint) return CallStackHint->getMessage(N); - return {}; + return {}; } void dump() const override; @@ -605,16 +605,16 @@ class PathDiagnosticCallPiece : public PathDiagnosticPiece { public: PathDiagnosticLocation callEnter; PathDiagnosticLocation callEnterWithin; - PathDiagnosticLocation callReturn; + PathDiagnosticLocation callReturn; PathPieces path; ~PathDiagnosticCallPiece() override; const Decl *getCaller() const { return Caller; } - + const Decl *getCallee() const { return Callee; } void setCallee(const CallEnter &CE, const SourceManager &SM); - + bool hasCallStackMessage() { return !CallStackMessage.empty(); } void setCallStackMessage(StringRef st) { CallStackMessage = st; } @@ -725,7 +725,7 @@ public: ~PathDiagnosticMacroPiece() override; PathPieces subPieces; - + bool containsEvent() const; void flattenLocations() override { @@ -779,7 +779,7 @@ class PathDiagnostic : public llvm::FoldingSetNode { PathPieces pathImpl; SmallVector<PathPieces *, 3> pathStack; - + /// Important bug uniqueing location. /// The location info is useful to differentiate between bugs. PathDiagnosticLocation UniqueingLoc; @@ -796,22 +796,22 @@ public: const Decl *DeclToUnique, std::unique_ptr<FilesToLineNumsMap> ExecutedLines); ~PathDiagnostic(); - + const PathPieces &path; - /// Return the path currently used by builders for constructing the + /// Return the path currently used by builders for constructing the /// PathDiagnostic. PathPieces &getActivePath() { if (pathStack.empty()) return pathImpl; return *pathStack.back(); } - + /// Return a mutable version of 'path'. PathPieces &getMutablePieces() { return pathImpl; } - + /// Return the unrolled size of the path. unsigned full_size(); @@ -898,7 +898,7 @@ public: /// Two diagnostics with the same issue along different paths will generate /// different profiles. void FullProfile(llvm::FoldingSetNodeID &ID) const; -}; +}; } // namespace ento diff --git a/include/clang/StaticAnalyzer/Core/Checker.h b/include/clang/StaticAnalyzer/Core/Checker.h index 45b7a61139ea..8484cfe4c956 100644 --- a/include/clang/StaticAnalyzer/Core/Checker.h +++ b/include/clang/StaticAnalyzer/Core/Checker.h @@ -63,7 +63,7 @@ public: class EndOfTranslationUnit { template <typename CHECKER> static void _checkEndOfTranslationUnit(void *checker, - const TranslationUnitDecl *TU, + const TranslationUnitDecl *TU, AnalysisManager& mgr, BugReporter &BR) { ((const CHECKER *)checker)->checkEndOfTranslationUnit(TU, mgr, BR); @@ -331,7 +331,7 @@ public: class RegionChanges { template <typename CHECKER> - static ProgramStateRef + static ProgramStateRef _checkRegionChanges(void *checker, ProgramStateRef state, const InvalidatedSymbols *invalidated, @@ -370,7 +370,7 @@ class PointerEscape { Kind); InvalidatedSymbols RegularEscape; - for (InvalidatedSymbols::const_iterator I = Escaped.begin(), + for (InvalidatedSymbols::const_iterator I = Escaped.begin(), E = Escaped.end(); I != E; ++I) if (!ETraits->hasTrait(*I, RegionAndSymbolInvalidationTraits::TK_PreserveContents) && @@ -410,7 +410,7 @@ class ConstPointerEscape { return State; InvalidatedSymbols ConstEscape; - for (InvalidatedSymbols::const_iterator I = Escaped.begin(), + for (InvalidatedSymbols::const_iterator I = Escaped.begin(), E = Escaped.end(); I != E; ++I) if (ETraits->hasTrait(*I, RegionAndSymbolInvalidationTraits::TK_PreserveContents) && @@ -436,7 +436,7 @@ public: } }; - + template <typename EVENT> class Event { template <typename CHECKER> @@ -504,7 +504,7 @@ public: /// Dump checker name to stream. raw_ostream& operator<<(raw_ostream &Out, const CheckerBase &Checker); -/// Tag that can use a checker name as a message provider +/// Tag that can use a checker name as a message provider /// (see SimpleProgramPointTag). class CheckerProgramPointTag : public SimpleProgramPointTag { public: diff --git a/include/clang/StaticAnalyzer/Core/CheckerManager.h b/include/clang/StaticAnalyzer/Core/CheckerManager.h index 33a794061a38..7c353326be46 100644 --- a/include/clang/StaticAnalyzer/Core/CheckerManager.h +++ b/include/clang/StaticAnalyzer/Core/CheckerManager.h @@ -86,7 +86,7 @@ enum PointerEscapeKind { /// argument to a function. PSK_IndirectEscapeOnCall, - /// The reason for pointer escape is unknown. For example, + /// The reason for pointer escape is unknown. For example, /// a region containing this pointer is invalidated. PSK_EscapeOther }; @@ -353,18 +353,18 @@ public: /// /// This notifies the checkers about pointer escape, which occurs whenever /// the analyzer cannot track the symbol any more. For example, as a - /// result of assigning a pointer into a global or when it's passed to a + /// result of assigning a pointer into a global or when it's passed to a /// function call the analyzer cannot model. - /// + /// /// \param State The state at the point of escape. /// \param Escaped The list of escaped symbols. - /// \param Call The corresponding CallEvent, if the symbols escape as + /// \param Call The corresponding CallEvent, if the symbols escape as /// parameters to the given call. /// \param Kind The reason of pointer escape. - /// \param ITraits Information about invalidation for a particular + /// \param ITraits Information about invalidation for a particular /// region/symbol. /// \returns Checkers can modify the state by returning a new one. - ProgramStateRef + ProgramStateRef runCheckersForPointerEscape(ProgramStateRef State, const InvalidatedSymbols &Escaped, const CallEvent *Call, @@ -381,7 +381,7 @@ public: void runCheckersForEvalCall(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const CallEvent &CE, ExprEngine &Eng); - + /// Run checkers for the entire Translation Unit. void runCheckersOnEndOfTranslationUnit(const TranslationUnitDecl *TU, AnalysisManager &mgr, @@ -419,21 +419,21 @@ public: //===----------------------------------------------------------------------===// using CheckStmtFunc = CheckerFn<void (const Stmt *, CheckerContext &)>; - + using CheckObjCMessageFunc = CheckerFn<void (const ObjCMethodCall &, CheckerContext &)>; using CheckCallFunc = CheckerFn<void (const CallEvent &, CheckerContext &)>; - + using CheckLocationFunc = CheckerFn<void (const SVal &location, bool isLoad, const Stmt *S, CheckerContext &)>; - + using CheckBindFunc = CheckerFn<void (const SVal &location, const SVal &val, const Stmt *S, CheckerContext &)>; - + using CheckEndAnalysisFunc = CheckerFn<void (ExplodedGraph &, BugReporter &, ExprEngine &)>; @@ -441,18 +441,18 @@ public: using CheckEndFunctionFunc = CheckerFn<void (const ReturnStmt *, CheckerContext &)>; - + using CheckBranchConditionFunc = CheckerFn<void (const Stmt *, CheckerContext &)>; using CheckNewAllocatorFunc = CheckerFn<void (const CXXNewExpr *, SVal, CheckerContext &)>; - + using CheckDeadSymbolsFunc = CheckerFn<void (SymbolReaper &, CheckerContext &)>; - + using CheckLiveSymbolsFunc = CheckerFn<void (ProgramStateRef,SymbolReaper &)>; - + using CheckRegionChangesFunc = CheckerFn<ProgramStateRef (ProgramStateRef, const InvalidatedSymbols *symbols, @@ -460,17 +460,17 @@ public: ArrayRef<const MemRegion *> Regions, const LocationContext *LCtx, const CallEvent *Call)>; - + using CheckPointerEscapeFunc = CheckerFn<ProgramStateRef (ProgramStateRef, const InvalidatedSymbols &Escaped, const CallEvent *Call, PointerEscapeKind Kind, RegionAndSymbolInvalidationTraits *ITraits)>; - + using EvalAssumeFunc = CheckerFn<ProgramStateRef (ProgramStateRef, const SVal &cond, bool assumption)>; - + using EvalCallFunc = CheckerFn<bool (const CallExpr *, CheckerContext &)>; using CheckEndOfTranslationUnit = @@ -531,7 +531,7 @@ public: template <typename EVENT> void _registerListenerForEvent(CheckEventFunc checkfn) { EventInfo &info = Events[getTag<EVENT>()]; - info.Checkers.push_back(checkfn); + info.Checkers.push_back(checkfn); } template <typename EVENT> @@ -636,7 +636,7 @@ private: EventInfo() = default; }; - + using EventsTy = llvm::DenseMap<EventTag, EventInfo>; EventsTy Events; }; diff --git a/include/clang/StaticAnalyzer/Core/CheckerOptInfo.h b/include/clang/StaticAnalyzer/Core/CheckerOptInfo.h index e981871ae4e0..2d13bf34cd15 100644 --- a/include/clang/StaticAnalyzer/Core/CheckerOptInfo.h +++ b/include/clang/StaticAnalyzer/Core/CheckerOptInfo.h @@ -28,7 +28,7 @@ class CheckerOptInfo { public: CheckerOptInfo(StringRef name, bool enable) : Name(name), Enable(enable), Claimed(false) { } - + StringRef getName() const { return Name; } bool isEnabled() const { return Enable; } bool isDisabled() const { return !isEnabled(); } diff --git a/include/clang/StaticAnalyzer/Core/CheckerRegistry.h b/include/clang/StaticAnalyzer/Core/CheckerRegistry.h index 912a601b61c4..d580dda73488 100644 --- a/include/clang/StaticAnalyzer/Core/CheckerRegistry.h +++ b/include/clang/StaticAnalyzer/Core/CheckerRegistry.h @@ -47,7 +47,7 @@ // The clang_registerCheckers function may add any number of checkers to the // registry. If any checkers require additional initialization, use the three- // argument form of CheckerRegistry::addChecker. -// +// // To load a checker plugin, specify the full path to the dynamic library as // the argument to the -load option in the cc1 frontend. You can then enable // your custom checker using the -analyzer-checker: diff --git a/include/clang/StaticAnalyzer/Core/IssueHash.h b/include/clang/StaticAnalyzer/Core/IssueHash.h index 8cb6631fae74..03997aae79ae 100644 --- a/include/clang/StaticAnalyzer/Core/IssueHash.h +++ b/include/clang/StaticAnalyzer/Core/IssueHash.h @@ -29,7 +29,7 @@ class LangOptions; /// location. The bugtype and the name of the checker is also part of the hash. /// The last component is the string representation of the enclosing declaration /// of the associated location. -/// +/// /// In case a new hash is introduced, the old one should still be maintained for /// a while. One should not introduce a new hash for every change, it is /// possible to introduce experimental hashes that may change in the future. diff --git a/include/clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h b/include/clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h index 93edfcef2d5a..243795e720f6 100644 --- a/include/clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h +++ b/include/clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h @@ -88,7 +88,7 @@ public: /// for 'unsigned char' (u8). RangeTestResultKind testInRange(const llvm::APSInt &Val, bool AllowMixedSign) const LLVM_READONLY; - + bool operator==(const APSIntType &Other) const { return BitWidth == Other.BitWidth && IsUnsigned == Other.IsUnsigned; } @@ -102,7 +102,7 @@ public: std::tie(Other.BitWidth, Other.IsUnsigned); } }; - + } // end ento namespace } // end clang namespace diff --git a/include/clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h b/include/clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h index 02b335761e70..85369509efcd 100644 --- a/include/clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h +++ b/include/clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h @@ -45,12 +45,12 @@ class AnalysisManager : public BugReporterData { public: AnalyzerOptions &options; - + AnalysisManager(ASTContext &ctx,DiagnosticsEngine &diags, const LangOptions &lang, const PathDiagnosticConsumers &Consumers, StoreManagerCreator storemgr, - ConstraintManagerCreator constraintmgr, + ConstraintManagerCreator constraintmgr, CheckerManager *checkerMgr, AnalyzerOptions &Options, CodeInjector* injector = nullptr); @@ -60,7 +60,7 @@ public: void ClearContexts() { AnaCtxMgr.clear(); } - + AnalysisDeclContextManager& getAnalysisDeclContextManager() { return AnaCtxMgr; } diff --git a/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h b/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h index 0bbc6500d6ec..b72b158194c7 100644 --- a/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h +++ b/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h @@ -155,12 +155,12 @@ public: return getValue(TargetType.convert(From)); } - + const llvm::APSInt &Convert(QualType T, const llvm::APSInt &From) { APSIntType TargetType = getAPSIntType(T); if (TargetType == APSIntType(From)) return From; - + return getValue(TargetType.convert(From)); } diff --git a/include/clang/StaticAnalyzer/Core/PathSensitive/BlockCounter.h b/include/clang/StaticAnalyzer/Core/PathSensitive/BlockCounter.h index b94dadff2342..5e831095abc7 100644 --- a/include/clang/StaticAnalyzer/Core/PathSensitive/BlockCounter.h +++ b/include/clang/StaticAnalyzer/Core/PathSensitive/BlockCounter.h @@ -35,7 +35,7 @@ class BlockCounter { public: BlockCounter() : Data(nullptr) {} - unsigned getNumVisited(const StackFrameContext *CallSite, + unsigned getNumVisited(const StackFrameContext *CallSite, unsigned BlockID) const; class Factory { @@ -45,7 +45,7 @@ public: ~Factory(); BlockCounter GetEmptyCounter(); - BlockCounter IncrementCount(BlockCounter BC, + BlockCounter IncrementCount(BlockCounter BC, const StackFrameContext *CallSite, unsigned BlockID); }; diff --git a/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h b/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h index 9c667f912e9f..9078fb94d282 100644 --- a/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h +++ b/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h @@ -29,6 +29,7 @@ #include "clang/Basic/LLVM.h" #include "clang/Basic/SourceLocation.h" #include "clang/Basic/SourceManager.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h" #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h" #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h" @@ -117,12 +118,12 @@ public: } }; -/// \class RuntimeDefinition +/// \class RuntimeDefinition /// Defines the runtime definition of the called function. -/// -/// Encapsulates the information we have about which Decl will be used +/// +/// Encapsulates the information we have about which Decl will be used /// when the call is executed on the given path. When dealing with dynamic -/// dispatch, the information is based on DynamicTypeInfo and might not be +/// dispatch, the information is based on DynamicTypeInfo and might not be /// precise. class RuntimeDefinition { /// The Declaration of the function which could be called at runtime. @@ -141,13 +142,13 @@ public: RuntimeDefinition(const Decl *InD, const MemRegion *InR): D(InD), R(InR) {} const Decl *getDecl() { return D; } - - /// Check if the definition we have is precise. - /// If not, it is possible that the call dispatches to another definition at + + /// Check if the definition we have is precise. + /// If not, it is possible that the call dispatches to another definition at /// execution time. bool mayHaveOtherDefinitions() { return R != nullptr; } - - /// When other definitions are possible, returns the region whose runtime type + + /// When other definitions are possible, returns the region whose runtime type /// determines the method definition. const MemRegion *getDispatchRegion() { return R; } }; @@ -404,6 +405,46 @@ public: /// \p D must not be null. static bool isVariadic(const Decl *D); + /// Returns AnalysisDeclContext for the callee stack frame. + /// Currently may fail; returns null on failure. + AnalysisDeclContext *getCalleeAnalysisDeclContext() const; + + /// Returns the callee stack frame. That stack frame will only be entered + /// during analysis if the call is inlined, but it may still be useful + /// in intermediate calculations even if the call isn't inlined. + /// May fail; returns null on failure. + const StackFrameContext *getCalleeStackFrame() const; + + /// Returns memory location for a parameter variable within the callee stack + /// frame. May fail; returns null on failure. + const VarRegion *getParameterLocation(unsigned Index) const; + + /// Returns true if on the current path, the argument was constructed by + /// calling a C++ constructor over it. This is an internal detail of the + /// analysis which doesn't necessarily represent the program semantics: + /// if we are supposed to construct an argument directly, we may still + /// not do that because we don't know how (i.e., construction context is + /// unavailable in the CFG or not supported by the analyzer). + bool isArgumentConstructedDirectly(unsigned Index) const { + // This assumes that the object was not yet removed from the state. + return ExprEngine::getObjectUnderConstruction( + getState(), {getOriginExpr(), Index}, getCalleeStackFrame()).hasValue(); + } + + /// Some calls have parameter numbering mismatched from argument numbering. + /// This function converts an argument index to the corresponding + /// parameter index. Returns None is the argument doesn't correspond + /// to any parameter variable. + Optional<unsigned> getAdjustedParameterIndex(unsigned ArgumentIndex) const { + if (dyn_cast_or_null<CXXOperatorCallExpr>(getOriginExpr()) && + dyn_cast_or_null<CXXMethodDecl>(getDecl())) { + // For member operator calls argument 0 on the expression corresponds + // to implicit this-parameter on the declaration. + return (ArgumentIndex > 0) ? Optional<unsigned>(ArgumentIndex - 1) : None; + } + return ArgumentIndex; + } + // Iterator access to formal parameters and their types. private: struct GetTypeFn { @@ -628,7 +669,7 @@ protected: : AnyFunctionCall(D, St, LCtx) {} CXXInstanceCall(const CXXInstanceCall &Other) = default; - void getExtraInvalidatedValues(ValueList &Values, + void getExtraInvalidatedValues(ValueList &Values, RegionAndSymbolInvalidationTraits *ETraits) const override; public: diff --git a/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h b/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h index f3a0ca7b6608..ce2b711a4a1b 100644 --- a/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h +++ b/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h @@ -51,7 +51,7 @@ namespace ento { /// be accessible from more than one translation unit. #define REGISTER_SET_WITH_PROGRAMSTATE(Name, Elem) \ REGISTER_TRAIT_WITH_PROGRAMSTATE(Name, llvm::ImmutableSet<Elem>) - + /// Declares an immutable list of type \p NameTy, suitable for placement into /// the ProgramState. This is implementing using llvm::ImmutableList. /// @@ -83,7 +83,7 @@ public: /// If we are post visiting a call, this flag will be set if the /// call was inlined. In all other cases it will be false. const bool wasInlined; - + CheckerContext(NodeBuilder &builder, ExprEngine &eng, ExplodedNode *pred, @@ -110,7 +110,7 @@ public: StoreManager &getStoreManager() { return Eng.getStoreManager(); } - + /// Returns the previous node in the exploded graph, which includes /// the state of the program before the checker ran. Note, checkers should /// not retain the node in their state since the nodes might get invalidated. @@ -149,7 +149,7 @@ public: BugReporter &getBugReporter() { return Eng.getBugReporter(); } - + SourceManager &getSourceManager() { return getBugReporter().getSourceManager(); } @@ -308,7 +308,7 @@ public: static bool isCLibraryFunction(const FunctionDecl *FD, StringRef Name = StringRef()); - /// Depending on wither the location corresponds to a macro, return + /// Depending on wither the location corresponds to a macro, return /// either the macro name or the token spelling. /// /// This could be useful when checkers' logic depends on whether a function diff --git a/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h b/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h index 5755818cd971..17369a85bfa3 100644 --- a/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h +++ b/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h @@ -64,7 +64,7 @@ class CoreEngine { public: using BlocksExhausted = std::vector<std::pair<BlockEdge, const ExplodedNode *>>; - + using BlocksAborted = std::vector<std::pair<const CFGBlock *, const ExplodedNode *>>; @@ -87,7 +87,7 @@ private: /// The locations where we stopped doing work because we visited a location /// too many times. BlocksExhausted blocksExhausted; - + /// The locations where we stopped because the engine aborted analysis, /// usually because it could not reason about something. BlocksAborted blocksAborted; @@ -141,7 +141,7 @@ public: /// Returns true if there is still simulation state on the worklist. bool ExecuteWorkListWithInitialState(const LocationContext *L, unsigned Steps, - ProgramStateRef InitState, + ProgramStateRef InitState, ExplodedNodeSet &Dst); /// Dispatch the work list item based on the given location information. @@ -152,8 +152,8 @@ public: // Functions for external checking of whether we have unfinished work bool wasBlockAborted() const { return !blocksAborted.empty(); } bool wasBlocksExhausted() const { return !blocksExhausted.empty(); } - bool hasWorkRemaining() const { return wasBlocksExhausted() || - WList->hasWork() || + bool hasWorkRemaining() const { return wasBlocksExhausted() || + WList->hasWork() || wasBlockAborted(); } /// Inform the CoreEngine that a basic block was aborted because @@ -161,7 +161,7 @@ public: void addAbortedBlock(const ExplodedNode *node, const CFGBlock *block) { blocksAborted.push_back(std::make_pair(block, node)); } - + WorkList *getWorkList() const { return WList.get(); } BlocksExhausted::const_iterator blocks_exhausted_begin() const { @@ -255,7 +255,7 @@ protected: /// Allow subclasses to finalize results before result_begin() is executed. virtual void finalizeResults() {} - + ExplodedNode *generateNodeImpl(const ProgramPoint &PP, ProgramStateRef State, ExplodedNode *Pred, @@ -474,7 +474,7 @@ class IndirectGotoNodeBuilder { ExplodedNode *Pred; public: - IndirectGotoNodeBuilder(ExplodedNode *pred, const CFGBlock *src, + IndirectGotoNodeBuilder(ExplodedNode *pred, const CFGBlock *src, const Expr *e, const CFGBlock *dispatch, CoreEngine* eng) : Eng(*eng), Src(src), DispatchBlock(*dispatch), E(e), Pred(pred) {} @@ -508,7 +508,7 @@ public: const Expr *getTarget() const { return E; } ProgramStateRef getState() const { return Pred->State; } - + const LocationContext *getLocationContext() const { return Pred->getLocationContext(); } @@ -562,7 +562,7 @@ public: const Expr *getCondition() const { return Condition; } ProgramStateRef getState() const { return Pred->State; } - + const LocationContext *getLocationContext() const { return Pred->getLocationContext(); } diff --git a/include/clang/StaticAnalyzer/Core/PathSensitive/Environment.h b/include/clang/StaticAnalyzer/Core/PathSensitive/Environment.h index d49aa81bc958..77e35398077c 100644 --- a/include/clang/StaticAnalyzer/Core/PathSensitive/Environment.h +++ b/include/clang/StaticAnalyzer/Core/PathSensitive/Environment.h @@ -40,14 +40,14 @@ public: const Stmt *getStmt() const { return first; } const LocationContext *getLocationContext() const { return second; } - + /// Profile an EnvironmentEntry for inclusion in a FoldingSet. static void Profile(llvm::FoldingSetNodeID &ID, const EnvironmentEntry &E) { ID.AddPointer(E.getStmt()); ID.AddPointer(E.getLocationContext()); } - + void Profile(llvm::FoldingSetNodeID &ID) const { Profile(ID, *this); } diff --git a/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h b/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h index c12198db6598..4e0c02e6d65b 100644 --- a/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h +++ b/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h @@ -87,7 +87,7 @@ class ExplodedNode : public llvm::FoldingSetNode { // for the nodes in the group. // This is not a PointerIntPair in order to keep the storage type opaque. uintptr_t P; - + public: NodeGroup(bool Flag = false) : P(Flag) { assert(getFlag() == Flag); @@ -251,7 +251,7 @@ public: }; static void SetAuditor(Auditor* A); - + private: void replaceSuccessor(ExplodedNode *node) { Succs.replaceNode(node); } void replacePredecessor(ExplodedNode *node) { Preds.replaceNode(node); } @@ -286,18 +286,18 @@ protected: /// NumNodes - The number of nodes in the graph. unsigned NumNodes = 0; - + /// A list of recently allocated nodes that can potentially be recycled. NodeVector ChangedNodes; - + /// A list of nodes that can be reused. NodeVector FreeNodes; - + /// Determines how often nodes are reclaimed. /// /// If this is 0, nodes will never be reclaimed. unsigned ReclaimNodeInterval = 0; - + /// Counter to determine when to reclaim nodes. unsigned ReclaimCounter; diff --git a/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h b/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h index 25849e94c8ff..06a90fa847a6 100644 --- a/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h +++ b/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h @@ -69,7 +69,7 @@ namespace cross_tu { class CrossTranslationUnitContext; } // namespace cross_tu - + namespace ento { class BasicValueFactory; @@ -117,7 +117,7 @@ private: cross_tu::CrossTranslationUnitContext &CTU; AnalysisManager &AMgr; - + AnalysisDeclContextManager &AnalysisDeclContexts; CoreEngine Engine; @@ -136,11 +136,11 @@ private: unsigned int currStmtIdx = 0; const NodeBuilderContext *currBldrCtx = nullptr; - + /// Helper object to determine if an Objective-C message expression /// implicitly never returns. ObjCNoReturn ObjCNoRet; - + /// Whether or not GC is enabled in this analysis. bool ObjCGCEnabled; @@ -173,7 +173,7 @@ public: /// state of the function call. Returns true if there is still simulation /// state on the worklist. bool ExecuteWorkListWithInitialState(const LocationContext *L, unsigned Steps, - ProgramStateRef InitState, + ProgramStateRef InitState, ExplodedNodeSet &Dst) { return Engine.ExecuteWorkListWithInitialState(L, Steps, InitState, Dst); } @@ -276,17 +276,17 @@ public: ExplodedNode *Pred, ExplodedNodeSet &Dst); void ProcessMemberDtor(const CFGMemberDtor D, ExplodedNode *Pred, ExplodedNodeSet &Dst); - void ProcessTemporaryDtor(const CFGTemporaryDtor D, + void ProcessTemporaryDtor(const CFGTemporaryDtor D, ExplodedNode *Pred, ExplodedNodeSet &Dst); /// Called by CoreEngine when processing the entrance of a CFGBlock. void processCFGBlockEntrance(const BlockEdge &L, NodeBuilderWithSinks &nodeBuilder, ExplodedNode *Pred) override; - + /// ProcessBranch - Called by CoreEngine. Used to generate successor /// nodes by processing the 'effects' of a branch condition. - void processBranch(const Stmt *Condition, const Stmt *Term, + void processBranch(const Stmt *Condition, const Stmt *Term, NodeBuilderContext& BuilderCtx, ExplodedNode *Pred, ExplodedNodeSet &Dst, @@ -354,7 +354,7 @@ public: /// processRegionChanges - Called by ProgramStateManager whenever a change is made /// to the store. Used to update checkers that track region values. - ProgramStateRef + ProgramStateRef processRegionChanges(ProgramStateRef state, const InvalidatedSymbols *invalidated, ArrayRef<const MemRegion *> ExplicitRegions, @@ -410,15 +410,15 @@ public: ExplodedNodeSet &Dst); /// VisitBlockExpr - Transfer function logic for BlockExprs. - void VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred, + void VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred, ExplodedNodeSet &Dst); /// VisitLambdaExpr - Transfer function logic for LambdaExprs. - void VisitLambdaExpr(const LambdaExpr *LE, ExplodedNode *Pred, + void VisitLambdaExpr(const LambdaExpr *LE, ExplodedNode *Pred, ExplodedNodeSet &Dst); /// VisitBinaryOperator - Transfer function logic for binary operators. - void VisitBinaryOperator(const BinaryOperator* B, ExplodedNode *Pred, + void VisitBinaryOperator(const BinaryOperator* B, ExplodedNode *Pred, ExplodedNodeSet &Dst); @@ -431,21 +431,21 @@ public: ExplodedNodeSet &Dst); /// VisitCompoundLiteralExpr - Transfer function logic for compound literals. - void VisitCompoundLiteralExpr(const CompoundLiteralExpr *CL, + void VisitCompoundLiteralExpr(const CompoundLiteralExpr *CL, ExplodedNode *Pred, ExplodedNodeSet &Dst); /// Transfer function logic for DeclRefExprs and BlockDeclRefExprs. void VisitCommonDeclRefExpr(const Expr *DR, const NamedDecl *D, ExplodedNode *Pred, ExplodedNodeSet &Dst); - + /// VisitDeclStmt - Transfer function logic for DeclStmts. - void VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred, + void VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred, ExplodedNodeSet &Dst); /// VisitGuardedExpr - Transfer function logic for ?, __builtin_choose - void VisitGuardedExpr(const Expr *Ex, const Expr *L, const Expr *R, + void VisitGuardedExpr(const Expr *Ex, const Expr *L, const Expr *R, ExplodedNode *Pred, ExplodedNodeSet &Dst); - + void VisitInitListExpr(const InitListExpr *E, ExplodedNode *Pred, ExplodedNodeSet &Dst); @@ -454,7 +454,7 @@ public: ExplodedNodeSet &Dst); /// VisitMemberExpr - Transfer function for member expressions. - void VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred, + void VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred, ExplodedNodeSet &Dst); /// VisitAtomicExpr - Transfer function for builtin atomic expressions @@ -471,16 +471,16 @@ public: /// VisitObjCForCollectionStmt - Transfer function logic for /// ObjCForCollectionStmt. - void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S, + void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S, ExplodedNode *Pred, ExplodedNodeSet &Dst); void VisitObjCMessage(const ObjCMessageExpr *ME, ExplodedNode *Pred, ExplodedNodeSet &Dst); /// VisitReturnStmt - Transfer function logic for return statements. - void VisitReturnStmt(const ReturnStmt *R, ExplodedNode *Pred, + void VisitReturnStmt(const ReturnStmt *R, ExplodedNode *Pred, ExplodedNodeSet &Dst); - + /// VisitOffsetOfExpr - Transfer function for offsetof. void VisitOffsetOfExpr(const OffsetOfExpr *Ex, ExplodedNode *Pred, ExplodedNodeSet &Dst); @@ -490,7 +490,7 @@ public: ExplodedNode *Pred, ExplodedNodeSet &Dst); /// VisitUnaryOperator - Transfer function logic for unary operators. - void VisitUnaryOperator(const UnaryOperator* B, ExplodedNode *Pred, + void VisitUnaryOperator(const UnaryOperator* B, ExplodedNode *Pred, ExplodedNodeSet &Dst); /// Handle ++ and -- (both pre- and post-increment). @@ -505,7 +505,7 @@ public: void VisitCXXCatchStmt(const CXXCatchStmt *CS, ExplodedNode *Pred, ExplodedNodeSet &Dst); - void VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred, + void VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred, ExplodedNodeSet & Dst); void VisitCXXConstructExpr(const CXXConstructExpr *E, ExplodedNode *Pred, @@ -528,15 +528,15 @@ public: /// Create a C++ temporary object for an rvalue. void CreateCXXTemporaryObject(const MaterializeTemporaryExpr *ME, - ExplodedNode *Pred, + ExplodedNode *Pred, ExplodedNodeSet &Dst); - + /// evalEagerlyAssumeBinOpBifurcation - Given the nodes in 'Src', eagerly assume symbolic /// expressions of the form 'x != 0' and generate new nodes (stored in Dst) /// with those assumptions. - void evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst, ExplodedNodeSet &Src, + void evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst, ExplodedNodeSet &Src, const Expr *Ex); - + static std::pair<const ProgramPointTag *, const ProgramPointTag *> geteagerlyAssumeBinOpBifurcationTags(); @@ -580,7 +580,15 @@ public: SVal LHS, SVal RHS, QualType T) { return svalBuilder.evalBinOp(ST, Op, LHS, RHS, T); } - + + /// By looking at a certain item that may be potentially part of an object's + /// ConstructionContext, retrieve such object's location. A particular + /// statement can be transparently passed as \p Item in most cases. + static Optional<SVal> + getObjectUnderConstruction(ProgramStateRef State, + const ConstructionContextItem &Item, + const LocationContext *LC); + protected: /// evalBind - Handle the semantics of binding a value to a specific location. /// This method is used by evalStore, VisitDeclStmt, and others. @@ -761,24 +769,17 @@ private: /// This allows, among other things, to keep bindings to variable's fields /// made within the constructor alive until its declaration actually /// goes into scope. - static ProgramStateRef addObjectUnderConstruction( - ProgramStateRef State, - llvm::PointerUnion<const Stmt *, const CXXCtorInitializer *> P, - const LocationContext *LC, SVal V); + static ProgramStateRef + addObjectUnderConstruction(ProgramStateRef State, + const ConstructionContextItem &Item, + const LocationContext *LC, SVal V); /// Mark the object sa fully constructed, cleaning up the state trait /// that tracks objects under construction. - static ProgramStateRef finishObjectConstruction( - ProgramStateRef State, - llvm::PointerUnion<const Stmt *, const CXXCtorInitializer *> P, - const LocationContext *LC); - - /// If the given statement corresponds to an object under construction, - /// being part of its construciton context, retrieve that object's location. - static Optional<SVal> getObjectUnderConstruction( - ProgramStateRef State, - llvm::PointerUnion<const Stmt *, const CXXCtorInitializer *> P, - const LocationContext *LC); + static ProgramStateRef + finishObjectConstruction(ProgramStateRef State, + const ConstructionContextItem &Item, + const LocationContext *LC); /// If the given expression corresponds to a temporary that was used for /// passing into an elidable copy/move constructor and that constructor diff --git a/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h b/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h index f3846eba6b96..3a93aae5a9bc 100644 --- a/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h +++ b/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h @@ -131,9 +131,9 @@ public: bool hasGlobalsOrParametersStorage() const; bool hasStackStorage() const; - + bool hasStackNonParametersStorage() const; - + bool hasStackParametersStorage() const; /// Compute the offset within the top level memory object. @@ -253,7 +253,7 @@ class StaticGlobalSpaceRegion : public GlobalsSpaceRegion { friend class MemRegionManager; const CodeTextRegion *CR; - + StaticGlobalSpaceRegion(MemRegionManager *mgr, const CodeTextRegion *cr) : GlobalsSpaceRegion(mgr, StaticGlobalSpaceRegionKind), CR(cr) { assert(cr); @@ -348,7 +348,7 @@ public: class HeapSpaceRegion : public MemSpaceRegion { friend class MemRegionManager; - + HeapSpaceRegion(MemRegionManager *mgr) : MemSpaceRegion(mgr, HeapSpaceRegionKind) {} @@ -359,7 +359,7 @@ public: return R->getKind() == HeapSpaceRegionKind; } }; - + class UnknownSpaceRegion : public MemSpaceRegion { friend class MemRegionManager; @@ -613,7 +613,7 @@ public: return R->getKind() == FunctionCodeRegionKind; } }; - + /// BlockCodeRegion - A region that represents code texts of blocks (closures). /// Blocks are represented with two kinds of regions. BlockCodeRegions /// represent the "code", while BlockDataRegions represent instances of blocks, @@ -643,7 +643,7 @@ public: QualType getLocationType() const override { return locTy; } - + const BlockDecl *getDecl() const { return BD; } @@ -658,7 +658,7 @@ public: return R->getKind() == BlockCodeRegionKind; } }; - + /// BlockDataRegion - A region that represents a block instance. /// Blocks are represented with two kinds of regions. BlockCodeRegions /// represent the "code", while BlockDataRegions represent instances of blocks, @@ -733,9 +733,9 @@ public: /// Return the original region for a captured region, if /// one exists. const VarRegion *getOriginalRegion(const VarRegion *VR) const; - + referenced_vars_iterator referenced_vars_begin() const; - referenced_vars_iterator referenced_vars_end() const; + referenced_vars_iterator referenced_vars_end() const; void dumpToStream(raw_ostream &os) const override; @@ -824,7 +824,7 @@ public: return R->getKind() == StringRegionKind; } }; - + /// The region associated with an ObjCStringLiteral. class ObjCStringRegion : public TypedValueRegion { friend class MemRegionManager; @@ -840,7 +840,7 @@ class ObjCStringRegion : public TypedValueRegion { static void ProfileRegion(llvm::FoldingSetNodeID &ID, const ObjCStringLiteral *Str, const MemRegion *superRegion); - + public: const ObjCStringLiteral *getObjCStringLiteral() const { return Str; } @@ -897,9 +897,9 @@ public: class DeclRegion : public TypedValueRegion { protected: - const Decl *D; + const ValueDecl *D; - DeclRegion(const Decl *d, const MemRegion *sReg, Kind k) + DeclRegion(const ValueDecl *d, const MemRegion *sReg, Kind k) : TypedValueRegion(sReg, k), D(d) { assert(classof(this)); assert(d); @@ -909,7 +909,7 @@ protected: const MemRegion* superRegion, Kind k); public: - const Decl *getDecl() const { return D; } + const ValueDecl *getDecl() const { return D; } void Profile(llvm::FoldingSetNodeID& ID) const override; static bool classof(const MemRegion* R) { @@ -959,7 +959,7 @@ public: return R->getKind() == VarRegionKind; } }; - + /// CXXThisRegion - Represents the region for the implicit 'this' parameter /// in a call to a C++ method. This region doesn't represent the object /// referred to by 'this', but rather 'this' itself. @@ -1141,7 +1141,7 @@ public: } }; -// CXXBaseObjectRegion represents a base object within a C++ object. It is +// CXXBaseObjectRegion represents a base object within a C++ object. It is // identified by the base class declaration and the region of its parent object. class CXXBaseObjectRegion : public TypedValueRegion { friend class MemRegionManager; @@ -1197,7 +1197,7 @@ class MemRegionManager { GlobalSystemSpaceRegion *SystemGlobals = nullptr; GlobalImmutableSpaceRegion *ImmutableGlobals = nullptr; - llvm::DenseMap<const StackFrameContext *, StackLocalsSpaceRegion *> + llvm::DenseMap<const StackFrameContext *, StackLocalsSpaceRegion *> StackLocalsSpaceRegions; llvm::DenseMap<const StackFrameContext *, StackArgumentsSpaceRegion *> StackArgumentsSpaceRegions; @@ -1213,7 +1213,7 @@ public: ~MemRegionManager(); ASTContext &getContext() { return C; } - + llvm::BumpPtrAllocator &getAllocator() { return A; } /// getStackLocalsRegion - Retrieve the memory region associated with the @@ -1251,7 +1251,7 @@ public: const CompoundLiteralRegion* getCompoundLiteralRegion(const CompoundLiteralExpr *CL, const LocationContext *LC); - + /// getCXXThisRegion - Retrieve the [artificial] region associated with the /// parameter 'this'. const CXXThisRegion *getCXXThisRegion(QualType thisPointerTy, @@ -1320,7 +1320,7 @@ public: /// Create a CXXBaseObjectRegion with the same CXXRecordDecl but a different /// super region. const CXXBaseObjectRegion * - getCXXBaseObjectRegionWithSuper(const CXXBaseObjectRegion *baseReg, + getCXXBaseObjectRegionWithSuper(const CXXBaseObjectRegion *baseReg, const SubRegion *superRegion) { return getCXXBaseObjectRegion(baseReg->getDecl(), superRegion, baseReg->isVirtual()); @@ -1330,7 +1330,7 @@ public: const BlockCodeRegion *getBlockCodeRegion(const BlockDecl *BD, CanQualType locTy, AnalysisDeclContext *AC); - + /// getBlockDataRegion - Get the memory region associated with an instance /// of a block. Unlike many other MemRegions, the LocationContext* /// argument is allowed to be NULL for cases where we have no known @@ -1363,7 +1363,7 @@ private: template <typename REG> const REG* LazyAllocate(REG*& region); - + template <typename REG, typename ARG> const REG* LazyAllocate(REG*& region, ARG a); }; @@ -1408,7 +1408,7 @@ public: /// should be invalidated. TK_EntireMemSpace = 0x8 - // Do not forget to extend StorageTypeForKinds if number of traits exceed + // Do not forget to extend StorageTypeForKinds if number of traits exceed // the number of bits StorageTypeForKinds can store. }; diff --git a/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h b/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h index 17ab7379fdba..b86301a03470 100644 --- a/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h +++ b/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h @@ -36,6 +36,7 @@ class ASTContext; namespace ento { +class AnalysisManager; class CallEvent; class CallEventManager; @@ -111,6 +112,8 @@ public: return *stateMgr; } + AnalysisManager &getAnalysisManager() const; + /// Return the ConstraintManager. ConstraintManager &getConstraintManager() const; diff --git a/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h b/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h index 31300d69f2ff..865014b22830 100644 --- a/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h +++ b/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h @@ -55,7 +55,7 @@ class SValBuilder { protected: ASTContext &Context; - + /// Manager of APSInt values. BasicValueFactory BasicVals; @@ -69,7 +69,7 @@ protected: /// The scalar type to use for array indices. const QualType ArrayIndexTy; - + /// The width of the scalar type used for array indices. const unsigned ArrayIndexWidth; @@ -137,7 +137,7 @@ public: /// that represents the same value, but is hopefully easier to work with /// than the original SVal. virtual SVal simplifySVal(ProgramStateRef State, SVal Val) = 0; - + /// Constructs a symbolic expression for two non-location values. SVal makeSymExprValNN(ProgramStateRef state, BinaryOperator::Opcode op, NonLoc lhs, NonLoc rhs, QualType resultTy); @@ -157,11 +157,11 @@ public: const ASTContext &getContext() const { return Context; } ProgramStateManager &getStateManager() { return StateMgr; } - + QualType getConditionType() const { return Context.getLangOpts().CPlusPlus ? Context.BoolTy : Context.IntTy; } - + QualType getArrayIndexType() const { return ArrayIndexTy; } @@ -237,7 +237,7 @@ public: DefinedSVal getMemberPointer(const DeclaratorDecl *DD); DefinedSVal getFunctionPointer(const FunctionDecl *func); - + DefinedSVal getBlockPointer(const BlockDecl *block, CanQualType locTy, const LocationContext *locContext, unsigned blockCount); @@ -252,7 +252,7 @@ public: return nonloc::CompoundVal(BasicVals.getCompoundValData(type, vals)); } - NonLoc makeLazyCompoundVal(const StoreRef &store, + NonLoc makeLazyCompoundVal(const StoreRef &store, const TypedValueRegion *region) { return nonloc::LazyCompoundVal( BasicVals.getLazyCompoundValData(store, region)); diff --git a/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h b/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h index 0fde63e9eb09..1b79bfc3f8cf 100644 --- a/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h +++ b/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h @@ -202,7 +202,7 @@ public: return SymExpr::symbol_iterator(); } - SymExpr::symbol_iterator symbol_end() const { + SymExpr::symbol_iterator symbol_end() const { return SymExpr::symbol_end(); } }; @@ -230,13 +230,13 @@ public: // tautologically false. bool isUndef() const = delete; bool isValid() const = delete; - + protected: DefinedOrUnknownSVal() = default; explicit DefinedOrUnknownSVal(const void *d, bool isLoc, unsigned ValKind) : SVal(d, isLoc, ValKind) {} explicit DefinedOrUnknownSVal(BaseKind k, void *D = nullptr) : SVal(k, D) {} - + private: friend class SVal; @@ -244,11 +244,11 @@ private: return !V.isUndef(); } }; - + class UnknownVal : public DefinedOrUnknownSVal { public: explicit UnknownVal() : DefinedOrUnknownSVal(UnknownValKind) {} - + private: friend class SVal; @@ -325,7 +325,7 @@ public: void dumpToStream(raw_ostream &Out) const; static bool isLocType(QualType T) { - return T->isAnyPointerType() || T->isBlockPointerType() || + return T->isAnyPointerType() || T->isBlockPointerType() || T->isReferenceType() || T->isNullPtrType(); } @@ -664,7 +664,7 @@ private: } }; -} // namespace loc +} // namespace loc } // namespace ento diff --git a/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h b/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h index dc0644df8aab..fc072a380074 100644 --- a/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h +++ b/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h @@ -149,7 +149,7 @@ public: // FIXME: This should soon be eliminated altogether; clients should deal with // region extents directly. - virtual DefinedOrUnknownSVal getSizeInElements(ProgramStateRef state, + virtual DefinedOrUnknownSVal getSizeInElements(ProgramStateRef state, const MemRegion *region, QualType EleTy) { return UnknownVal(); @@ -176,8 +176,8 @@ public: /// - Successful cast (ex: derived is subclass of base). /// - Failed cast (ex: derived is definitely not a subclass of base). /// The distinction of this case from the next one is necessary to model - /// dynamic_cast. - /// - We don't know (base is a symbolic region and we don't have + /// dynamic_cast. + /// - We don't know (base is a symbolic region and we don't have /// enough info to determine if the cast will succeed at run time). /// The function returns an SVal representing the derived class; it's /// valid only if Failed flag is set to false. @@ -195,7 +195,7 @@ public: virtual bool includedInBindings(Store store, const MemRegion *region) const = 0; - + /// If the StoreManager supports it, increment the reference count of /// the specified Store object. virtual void incrementReferenceCount(Store store) {} @@ -221,7 +221,7 @@ public: /// globals should get invalidated. /// \param[in,out] IS A set to fill with any symbols that are no longer /// accessible. Pass \c NULL if this information will not be used. - /// \param[in] ITraits Information about invalidation for a particular + /// \param[in] ITraits Information about invalidation for a particular /// region/symbol. /// \param[in,out] InvalidatedTopLevel A vector to fill with regions //// explicitly being invalidated. Pass \c NULL if this @@ -305,16 +305,16 @@ inline StoreRef::StoreRef(Store store, StoreManager & smgr) inline StoreRef::StoreRef(const StoreRef &sr) : store(sr.store), mgr(sr.mgr) -{ +{ if (store) mgr.incrementReferenceCount(store); } - + inline StoreRef::~StoreRef() { if (store) mgr.decrementReferenceCount(store); } - + inline StoreRef &StoreRef::operator=(StoreRef const &newStore) { assert(&newStore.mgr == &mgr); if (store != newStore.store) { diff --git a/include/clang/StaticAnalyzer/Core/PathSensitive/StoreRef.h b/include/clang/StaticAnalyzer/Core/PathSensitive/StoreRef.h index c5b4e5036bdf..22259a239cf6 100644 --- a/include/clang/StaticAnalyzer/Core/PathSensitive/StoreRef.h +++ b/include/clang/StaticAnalyzer/Core/PathSensitive/StoreRef.h @@ -18,15 +18,15 @@ namespace clang { namespace ento { - + class StoreManager; - + /// Store - This opaque type encapsulates an immutable mapping from /// locations to values. At a high-level, it represents the symbolic /// memory model. Different subclasses of StoreManager may choose /// different types to represent the locations and values. using Store = const void *; - + class StoreRef { Store store; StoreManager &mgr; @@ -36,14 +36,14 @@ public: StoreRef(const StoreRef &sr); StoreRef &operator=(StoreRef const &newStore); ~StoreRef(); - + bool operator==(const StoreRef &x) const { assert(&mgr == &x.mgr); return x.store == store; } bool operator!=(const StoreRef &x) const { return !operator==(x); } - + Store getStore() const { return store; } const StoreManager &getStoreManager() const { return mgr; } }; diff --git a/include/clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h b/include/clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h index e574ffdd6a15..d6aa4feddff2 100644 --- a/include/clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h +++ b/include/clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h @@ -29,7 +29,7 @@ class CrossTranslationUnitContext; } namespace ento { - + struct NodeBuilderContext; class AnalysisManager; class ExplodedNodeSet; @@ -133,7 +133,7 @@ public: /// processRegionChanges - Called by ProgramStateManager whenever a change is /// made to the store. Used to update checkers that track region values. - virtual ProgramStateRef + virtual ProgramStateRef processRegionChanges(ProgramStateRef state, const InvalidatedSymbols *invalidated, ArrayRef<const MemRegion *> ExplicitRegions, @@ -142,7 +142,7 @@ public: const CallEvent *Call) = 0; - inline ProgramStateRef + inline ProgramStateRef processRegionChange(ProgramStateRef state, const MemRegion* MR, const LocationContext *LCtx) { diff --git a/include/clang/StaticAnalyzer/Core/PathSensitive/SummaryManager.h b/include/clang/StaticAnalyzer/Core/PathSensitive/SummaryManager.h index 52d78b6a3c82..0a75eeb3ea53 100644 --- a/include/clang/StaticAnalyzer/Core/PathSensitive/SummaryManager.h +++ b/include/clang/StaticAnalyzer/Core/PathSensitive/SummaryManager.h @@ -21,9 +21,9 @@ namespace ento { namespace summMgr { - + /* Key kinds: - + - C functions - C++ functions (name + parameter types) - ObjC methods: @@ -34,21 +34,21 @@ namespace summMgr { - C++ methods - Class, function name + parameter types + const */ - + class SummaryKey { - + }; } // end namespace clang::summMgr - + class SummaryManagerImpl { - + }; - + template <typename T> class SummaryManager : SummaryManagerImpl { - + }; } // end GR namespace diff --git a/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h b/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h index cc3ce72f9e56..074551962607 100644 --- a/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h +++ b/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h @@ -167,7 +167,7 @@ public: /// SubRegion::getExtent instead -- the value returned may not be a symbol. class SymbolExtent : public SymbolData { const SubRegion *R; - + public: SymbolExtent(SymbolID sym, const SubRegion *r) : SymbolData(SymbolExtentKind, sym), R(r) { @@ -300,7 +300,7 @@ public: } }; -/// Represents a symbolic expression involving a binary operator +/// Represents a symbolic expression involving a binary operator class BinarySymExpr : public SymExpr { BinaryOperator::Opcode Op; QualType T; @@ -558,7 +558,7 @@ class SymbolReaper { SymbolSetTy TheDead; RegionSetTy RegionRoots; - + const StackFrameContext *LCtx; const Stmt *Loc; SymbolManager& SymMgr; @@ -614,7 +614,7 @@ public: bool hasDeadSymbols() const { return !TheDead.empty(); } - + using region_iterator = RegionSetTy::const_iterator; region_iterator region_begin() const { return RegionRoots.begin(); } @@ -627,10 +627,10 @@ public: bool isDead(SymbolRef sym) const { return TheDead.count(sym); } - + void markLive(const MemRegion *region); void markElementIndicesLive(const MemRegion *region); - + /// Set to the value of the symbolic store after /// StoreManager::removeDeadBindings has been called. void setReapedStore(StoreRef st) { reapedStore = st; } diff --git a/include/clang/StaticAnalyzer/Core/PathSensitive/WorkList.h b/include/clang/StaticAnalyzer/Core/PathSensitive/WorkList.h index 7df8f373b366..07edd35ff944 100644 --- a/include/clang/StaticAnalyzer/Core/PathSensitive/WorkList.h +++ b/include/clang/StaticAnalyzer/Core/PathSensitive/WorkList.h @@ -20,7 +20,7 @@ #include <cassert> namespace clang { - + class CFGBlock; namespace ento { @@ -47,13 +47,13 @@ public: /// Returns the node associated with the worklist unit. ExplodedNode *getNode() const { return node; } - + /// Returns the block counter map associated with the worklist unit. BlockCounter getBlockCounter() const { return counter; } /// Returns the CFGblock associated with the worklist unit. const CFGBlock *getBlock() const { return block; } - + /// Return the index within the CFGBlock for the worklist unit. unsigned getIndex() const { return blockIdx; } }; diff --git a/lib/ARCMigrate/ARCMT.cpp b/lib/ARCMigrate/ARCMT.cpp index 74c9974cc810..3c7b593be6d4 100644 --- a/lib/ARCMigrate/ARCMT.cpp +++ b/lib/ARCMigrate/ARCMT.cpp @@ -226,7 +226,7 @@ static void emitPremigrationErrors(const CapturedDiagList &arcDiags, new DiagnosticsEngine(DiagID, diagOpts, &printer, /*ShouldOwnClient=*/false)); Diags->setSourceManager(&PP.getSourceManager()); - + printer.BeginSourceFile(PP.getLangOpts(), &PP); arcDiags.reportDiagnostics(*Diags); printer.EndSourceFile(); @@ -305,7 +305,7 @@ bool arcmt::checkForManualIssues( // After parsing of source files ended, we want to reuse the // diagnostics objects to emit further diagnostics. - // We call BeginSourceFile because DiagnosticConsumer requires that + // We call BeginSourceFile because DiagnosticConsumer requires that // diagnostics with source range information are emitted only in between // BeginSourceFile() and EndSourceFile(). DiagClient->BeginSourceFile(Ctx.getLangOpts(), &Unit->getPreprocessor()); @@ -572,7 +572,7 @@ bool MigrationProcess::applyTransform(TransformFn trans, // After parsing of source files ended, we want to reuse the // diagnostics objects to emit further diagnostics. - // We call BeginSourceFile because DiagnosticConsumer requires that + // We call BeginSourceFile because DiagnosticConsumer requires that // diagnostics with source range information are emitted only in between // BeginSourceFile() and EndSourceFile(). DiagClient->BeginSourceFile(Ctx.getLangOpts(), &Unit->getPreprocessor()); diff --git a/lib/ARCMigrate/FileRemapper.cpp b/lib/ARCMigrate/FileRemapper.cpp index 4dedac88f982..ccc8c9ee30ff 100644 --- a/lib/ARCMigrate/FileRemapper.cpp +++ b/lib/ARCMigrate/FileRemapper.cpp @@ -67,7 +67,7 @@ bool FileRemapper::initFromFile(StringRef filePath, DiagnosticsEngine &Diag, llvm::MemoryBuffer::getFile(infoFile); if (!fileBuf) return report("Error opening file: " + infoFile, Diag); - + SmallVector<StringRef, 64> lines; fileBuf.get()->getBuffer().split(lines, "\n"); @@ -78,7 +78,7 @@ bool FileRemapper::initFromFile(StringRef filePath, DiagnosticsEngine &Diag, return report("Invalid file data: '" + lines[idx+1] + "' not a number", Diag); StringRef toFilename = lines[idx+2]; - + const FileEntry *origFE = FileMgr->getFile(fromFilename); if (!origFE) { if (ignoreIfFilesChanged) @@ -152,7 +152,7 @@ bool FileRemapper::flushToFile(StringRef outputPath, DiagnosticsEngine &Diag) { llvm::MemoryBuffer *mem = I->second.get<llvm::MemoryBuffer *>(); newOut.write(mem->getBufferStart(), mem->getBufferSize()); newOut.close(); - + const FileEntry *newE = FileMgr->getFile(tempPath); remap(origFE, newE); infoOut << newE->getName() << '\n'; diff --git a/lib/ARCMigrate/Internals.h b/lib/ARCMigrate/Internals.h index 4f153b1ad2f4..1a261c1e31aa 100644 --- a/lib/ARCMigrate/Internals.h +++ b/lib/ARCMigrate/Internals.h @@ -25,7 +25,7 @@ namespace arcmt { class CapturedDiagList { typedef std::list<StoredDiagnostic> ListTy; ListTy List; - + public: void push_back(const StoredDiagnostic &diag) { List.push_back(diag); } diff --git a/lib/ARCMigrate/ObjCMT.cpp b/lib/ARCMigrate/ObjCMT.cpp index 433e6194a2c2..7e9bc6a5bdc6 100644 --- a/lib/ARCMigrate/ObjCMT.cpp +++ b/lib/ARCMigrate/ObjCMT.cpp @@ -46,7 +46,7 @@ class ObjCMigrateASTConsumer : public ASTConsumer { CF_BRIDGING_ENABLE, CF_BRIDGING_MAY_INCLUDE }; - + void migrateDecl(Decl *D); void migrateObjCContainerDecl(ASTContext &Ctx, ObjCContainerDecl *D); void migrateProtocolConformance(ASTContext &Ctx, @@ -63,26 +63,26 @@ class ObjCMigrateASTConsumer : public ASTConsumer { void migrateFactoryMethod(ASTContext &Ctx, ObjCContainerDecl *CDecl, ObjCMethodDecl *OM, ObjCInstanceTypeFamily OIT_Family = OIT_None); - + void migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl); void AddCFAnnotations(ASTContext &Ctx, const CallEffects &CE, const FunctionDecl *FuncDecl, bool ResultAnnotated); void AddCFAnnotations(ASTContext &Ctx, const CallEffects &CE, const ObjCMethodDecl *MethodDecl, bool ResultAnnotated); - + void AnnotateImplicitBridging(ASTContext &Ctx); - + CF_BRIDGING_KIND migrateAddFunctionAnnotation(ASTContext &Ctx, const FunctionDecl *FuncDecl); - + void migrateARCSafeAnnotation(ASTContext &Ctx, ObjCContainerDecl *CDecl); - + void migrateAddMethodAnnotation(ASTContext &Ctx, const ObjCMethodDecl *MethodDecl); void inferDesignatedInitializers(ASTContext &Ctx, const ObjCImplementationDecl *ImplD); - + bool InsertFoundation(ASTContext &Ctx, SourceLocation Loc); public: @@ -225,7 +225,7 @@ namespace { isa<ObjCIvarRefExpr>(Expr) || isa<ParenExpr>(FullExpr) || isa<ParenListExpr>(Expr) || isa<SizeOfPackExpr>(Expr)); } - + /// - Rewrite message expression for Objective-C setter and getters into /// property-dot syntax. bool rewriteToPropertyDotSyntax(const ObjCMessageExpr *Msg, @@ -239,17 +239,17 @@ namespace { if (const Expr *Receiver = Msg->getInstanceReceiver()) if (Receiver->getType()->isObjCBuiltinType()) return false; - + const ObjCMethodDecl *Method = Msg->getMethodDecl(); if (!Method) return false; if (!Method->isPropertyAccessor()) return false; - + const ObjCPropertyDecl *Prop = Method->findPropertyDecl(); if (!Prop) return false; - + SourceRange MsgRange = Msg->getSourceRange(); bool ReceiverIsSuper = (Msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); @@ -276,7 +276,7 @@ namespace { PropertyDotString = "."; PropertyDotString += Prop->getName(); commit.replace(SpaceRange, PropertyDotString); - + // remove '[' ']' commit.replace(SourceRange(MsgRange.getBegin(), MsgRange.getBegin()), ""); commit.replace(SourceRange(MsgRange.getEnd(), MsgRange.getEnd()), ""); @@ -465,7 +465,7 @@ static void rewriteToObjCProperty(const ObjCMethodDecl *Getter, PropertyString += "(nonatomic"; LParenAdded = true; } - + std::string PropertyNameString = Getter->getNameAsString(); StringRef PropertyName(PropertyNameString); if (LengthOfPrefix > 0) { @@ -480,8 +480,8 @@ static void rewriteToObjCProperty(const ObjCMethodDecl *Getter, // Property with no setter may be suggested as a 'readonly' property. if (!Setter) append_attr(PropertyString, "readonly", LParenAdded); - - + + // Short circuit 'delegate' properties that contain the name "delegate" or // "dataSource", or have exact name "target" to have 'assign' attribute. if (PropertyName.equals("target") || @@ -542,7 +542,7 @@ static void rewriteToObjCProperty(const ObjCMethodDecl *Getter, } SourceLocation StartGetterSelectorLoc = Getter->getSelectorStartLoc(); Selector GetterSelector = Getter->getSelector(); - + SourceLocation EndGetterSelectorLoc = StartGetterSelectorLoc.getLocWithOffset(GetterSelector.getNameForSlot(0).size()); commit.replace(CharSourceRange::getCharRange(Getter->getLocStart(), @@ -572,7 +572,7 @@ void ObjCMigrateASTConsumer::migrateObjCContainerDecl(ASTContext &Ctx, ObjCContainerDecl *D) { if (D->isDeprecated() || IsCategoryNameWithDeprecatedSuffix(D)) return; - + for (auto *Method : D->methods()) { if (Method->isDeprecated()) continue; @@ -587,7 +587,7 @@ void ObjCMigrateASTConsumer::migrateObjCContainerDecl(ASTContext &Ctx, } if (!(ASTMigrateActions & FrontendOptions::ObjCMT_ReturnsInnerPointerProperty)) return; - + for (auto *Prop : D->instance_properties()) { if ((ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) && !Prop->isDeprecated()) @@ -628,7 +628,7 @@ ClassImplementsAllMethodsAndProperties(ASTContext &Ctx, else return false; } - + // At this point, all required properties in this protocol conform to those // declared in the class. // Check that class implements the required methods of the protocol too. @@ -666,7 +666,7 @@ static bool rewriteToObjCInterfaceDecl(const ObjCInterfaceDecl *IDecl, std::string ClassString; SourceLocation EndLoc = IDecl->getSuperClass() ? IDecl->getSuperClassLoc() : IDecl->getLocation(); - + if (Protocols.empty()) { ClassString = '<'; for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) { @@ -686,7 +686,7 @@ static bool rewriteToObjCInterfaceDecl(const ObjCInterfaceDecl *IDecl, ObjCInterfaceDecl::protocol_loc_iterator PL = IDecl->protocol_loc_end() - 1; EndLoc = *PL; } - + commit.insertAfterToken(EndLoc, ClassString); return true; } @@ -717,7 +717,7 @@ static bool rewriteToNSEnumDecl(const EnumDecl *EnumDcl, ClassString += NSIntegerName; } ClassString += ", "; - + ClassString += TypedefDcl->getIdentifier()->getName(); ClassString += ')'; SourceRange R(EnumDcl->getLocStart(), EnumDcl->getLocStart()); @@ -731,7 +731,7 @@ static bool rewriteToNSEnumDecl(const EnumDecl *EnumDcl, } else return false; - + SourceLocation EndTypedefDclLoc = TypedefDcl->getLocEnd(); EndTypedefDclLoc = trans::findSemiAfterLocation(EndTypedefDclLoc, NS.getASTContext(), /*IsDecl*/true); @@ -763,13 +763,13 @@ static void rewriteToNSMacroDecl(ASTContext &Ctx, QualType DesignatedEnumType = EnumDcl->getIntegerType(); assert(!DesignatedEnumType.isNull() && "rewriteToNSMacroDecl - underlying enum type is null"); - + PrintingPolicy Policy(Ctx.getPrintingPolicy()); std::string TypeString = DesignatedEnumType.getAsString(Policy); std::string ClassString = IsNSIntegerType ? "NS_ENUM(" : "NS_OPTIONS("; ClassString += TypeString; ClassString += ", "; - + ClassString += TypedefDcl->getIdentifier()->getName(); ClassString += ") "; SourceLocation EndLoc = EnumDcl->getBraceRange().getBegin(); @@ -781,7 +781,7 @@ static void rewriteToNSMacroDecl(ASTContext &Ctx, SourceLocation StartTypedefLoc = EnumDcl->getLocEnd(); StartTypedefLoc = StartTypedefLoc.getLocWithOffset(+1); SourceLocation EndTypedefLoc = TypedefDcl->getLocEnd(); - + commit.remove(SourceRange(StartTypedefLoc, EndTypedefLoc)); } @@ -801,7 +801,7 @@ static bool UseNSOptionsMacro(Preprocessor &PP, ASTContext &Ctx, if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) if (BO->isShiftOp() || BO->isBitwiseOp()) return true; - + uint64_t EnumVal = Enumerator->getInitVal().getZExtValue(); if (PowerOfTwo && EnumVal) { if (!llvm::isPowerOf2_64(EnumVal)) @@ -826,7 +826,7 @@ static bool UseNSOptionsMacro(Preprocessor &PP, ASTContext &Ctx, return AllHexdecimalEnumerator || (PowerOfTwo && (MaxPowerOfTwoVal > 2)); } -void ObjCMigrateASTConsumer::migrateProtocolConformance(ASTContext &Ctx, +void ObjCMigrateASTConsumer::migrateProtocolConformance(ASTContext &Ctx, const ObjCImplementationDecl *ImpDecl) { const ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface(); if (!IDecl || ObjCProtocolDecls.empty() || IDecl->isDeprecated()) @@ -836,11 +836,11 @@ void ObjCMigrateASTConsumer::migrateProtocolConformance(ASTContext &Ctx, llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ExplicitProtocols; Ctx.CollectInheritedProtocols(IDecl, ExplicitProtocols); llvm::SmallVector<ObjCProtocolDecl *, 8> PotentialImplicitProtocols; - + for (ObjCProtocolDecl *ProtDecl : ObjCProtocolDecls) if (!ExplicitProtocols.count(ProtDecl)) PotentialImplicitProtocols.push_back(ProtDecl); - + if (PotentialImplicitProtocols.empty()) return; @@ -852,10 +852,10 @@ void ObjCMigrateASTConsumer::migrateProtocolConformance(ASTContext &Ctx, if (ClassImplementsAllMethodsAndProperties(Ctx, ImpDecl, IDecl, PotentialImplicitProtocols[i])) ConformingProtocols.push_back(PotentialImplicitProtocols[i]); - + if (ConformingProtocols.empty()) return; - + // Further reduce number of conforming protocols. If protocol P1 is in the list // protocol P2 (P2<P1>), No need to include P1. llvm::SmallVector<ObjCProtocolDecl*, 8> MinimalConformingProtocols; @@ -885,7 +885,7 @@ void ObjCMigrateASTConsumer::migrateProtocolConformance(ASTContext &Ctx, void ObjCMigrateASTConsumer::CacheObjCNSIntegerTypedefed( const TypedefDecl *TypedefDcl) { - + QualType qt = TypedefDcl->getTypeSourceInfo()->getType(); if (NSAPIObj->isObjCNSIntegerType(qt)) NSIntegerTypedefed = TypedefDcl; @@ -919,10 +919,10 @@ bool ObjCMigrateASTConsumer::migrateNSEnumDecl(ASTContext &Ctx, } if (TypedefDcl->isDeprecated()) return false; - + QualType qt = TypedefDcl->getTypeSourceInfo()->getType(); StringRef NSIntegerName = NSAPIObj->GetNSIntegralKind(qt); - + if (NSIntegerName.empty()) { // Also check for typedef enum {...} TD; if (const EnumType *EnumTy = qt->getAs<EnumType>()) { @@ -938,7 +938,7 @@ bool ObjCMigrateASTConsumer::migrateNSEnumDecl(ASTContext &Ctx, } return false; } - + // We may still use NS_OPTIONS based on what we find in the enumertor list. bool NSOptions = UseNSOptionsMacro(PP, Ctx, EnumDcl); if (!InsertFoundation(Ctx, TypedefDcl->getLocStart())) @@ -1000,7 +1000,7 @@ void ObjCMigrateASTConsumer::migrateMethodInstanceType(ASTContext &Ctx, ObjCMethodDecl *OM) { ObjCInstanceTypeFamily OIT_Family = Selector::getInstTypeMethodFamily(OM->getSelector()); - + std::string ClassName; switch (OIT_Family) { case OIT_None: @@ -1025,7 +1025,7 @@ void ObjCMigrateASTConsumer::migrateMethodInstanceType(ASTContext &Ctx, } if (!OM->getReturnType()->isObjCIdType()) return; - + ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl); if (!IDecl) { if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl)) @@ -1080,7 +1080,7 @@ static bool AvailabilityAttrsMatch(Attr *At1, Attr *At2) { if (!AA1) return true; const AvailabilityAttr *AA2 = dyn_cast<AvailabilityAttr>(At2); - + VersionTuple Introduced1 = AA1->getIntroduced(); VersionTuple Deprecated1 = AA1->getDeprecated(); VersionTuple Obsoleted1 = AA1->getObsoleted(); @@ -1159,14 +1159,14 @@ bool ObjCMigrateASTConsumer::migrateProperty(ASTContext &Ctx, QualType GRT = Method->getReturnType(); if (GRT->isVoidType()) return false; - + Selector GetterSelector = Method->getSelector(); ObjCInstanceTypeFamily OIT_Family = Selector::getInstTypeMethodFamily(GetterSelector); - + if (OIT_Family != OIT_None) return false; - + IdentifierInfo *getterName = GetterSelector.getIdentifierInfoForSlot(0); Selector SetterSelector = SelectorTable::constructSetterSelector(PP.getIdentifierTable(), @@ -1199,7 +1199,7 @@ bool ObjCMigrateASTConsumer::migrateProperty(ASTContext &Ctx, } } } - + if (SetterMethod) { if ((ASTMigrateActions & FrontendOptions::ObjCMT_ReadwriteProperty) == 0) return false; @@ -1207,7 +1207,7 @@ bool ObjCMigrateASTConsumer::migrateProperty(ASTContext &Ctx, if (SetterMethod->isDeprecated() || !AttributesMatch(Method, SetterMethod, AvailabilityArgsMatch)) return false; - + // Is this a valid setter, matching the target getter? QualType SRT = SetterMethod->getReturnType(); if (!SRT->isVoidType()) @@ -1255,7 +1255,7 @@ void ObjCMigrateASTConsumer::migrateNsReturnsInnerPointer(ASTContext &Ctx, if (!TypeIsInnerPointer(RT) || !NSAPIObj->isMacroDefined("NS_RETURNS_INNER_POINTER")) return; - + edit::Commit commit(*Editor); commit.insertBefore(OM->getLocEnd(), " NS_RETURNS_INNER_POINTER"); Editor->commit(commit); @@ -1277,7 +1277,7 @@ void ObjCMigrateASTConsumer::migrateAllMethodInstaceType(ASTContext &Ctx, ObjCContainerDecl *CDecl) { if (CDecl->isDeprecated() || IsCategoryNameWithDeprecatedSuffix(CDecl)) return; - + // migrate methods which can have instancetype as their result type. for (auto *Method : CDecl->methods()) { if (Method->isDeprecated()) @@ -1294,7 +1294,7 @@ void ObjCMigrateASTConsumer::migrateFactoryMethod(ASTContext &Ctx, OM->getReturnType() == Ctx.getObjCInstanceType() || !OM->getReturnType()->isObjCIdType()) return; - + // Candidate factory methods are + (id) NaMeXXX : ... which belong to a class // NSYYYNamE with matching names be at least 3 characters long. ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl); @@ -1306,17 +1306,17 @@ void ObjCMigrateASTConsumer::migrateFactoryMethod(ASTContext &Ctx, } if (!IDecl) return; - + std::string StringClassName = IDecl->getName(); StringRef LoweredClassName(StringClassName); std::string StringLoweredClassName = LoweredClassName.lower(); LoweredClassName = StringLoweredClassName; - + IdentifierInfo *MethodIdName = OM->getSelector().getIdentifierInfoForSlot(0); // Handle method with no name at its first selector slot; e.g. + (id):(int)x. if (!MethodIdName) return; - + std::string MethodName = MethodIdName->getName(); if (OIT_Family == OIT_Singleton || OIT_Family == OIT_ReturnsSelf) { StringRef STRefMethodName(MethodName); @@ -1353,10 +1353,10 @@ void ObjCMigrateASTConsumer::migrateFactoryMethod(ASTContext &Ctx, static bool IsVoidStarType(QualType Ty) { if (!Ty->isPointerType()) return false; - + while (const TypedefType *TD = dyn_cast<TypedefType>(Ty.getTypePtr())) Ty = TD->getDecl()->getUnderlyingType(); - + // Is the type void*? const PointerType* PT = Ty->getAs<PointerType>(); if (PT->getPointeeType().getUnqualifiedType()->isVoidType()) @@ -1418,14 +1418,14 @@ void ObjCMigrateASTConsumer::AnnotateImplicitBridging(ASTContext &Ctx) { void ObjCMigrateASTConsumer::migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl) { if (Decl->isDeprecated()) return; - + if (Decl->hasAttr<CFAuditedTransferAttr>()) { assert(CFFunctionIBCandidates.empty() && "Cannot have audited functions/methods inside user " "provided CF_IMPLICIT_BRIDGING_ENABLE"); return; } - + // Finction must be annotated first. if (const FunctionDecl *FuncDecl = dyn_cast<FunctionDecl>(Decl)) { CF_BRIDGING_KIND AuditKind = migrateAddFunctionAnnotation(Ctx, FuncDecl); @@ -1469,7 +1469,7 @@ void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx, if (Ret.isOwned() && NSAPIObj->isMacroDefined("NS_RETURNS_RETAINED")) AnnotationString = " NS_RETURNS_RETAINED"; } - + if (AnnotationString) { edit::Commit commit(*Editor); commit.insertAfterToken(FuncDecl->getLocEnd(), AnnotationString); @@ -1503,18 +1503,18 @@ ObjCMigrateASTConsumer::CF_BRIDGING_KIND const FunctionDecl *FuncDecl) { if (FuncDecl->hasBody()) return CF_BRIDGING_NONE; - + CallEffects CE = CallEffects::getEffect(FuncDecl); bool FuncIsReturnAnnotated = (FuncDecl->hasAttr<CFReturnsRetainedAttr>() || FuncDecl->hasAttr<CFReturnsNotRetainedAttr>() || FuncDecl->hasAttr<NSReturnsRetainedAttr>() || FuncDecl->hasAttr<NSReturnsNotRetainedAttr>() || FuncDecl->hasAttr<NSReturnsAutoreleasedAttr>()); - + // Trivial case of when function is annotated and has no argument. if (FuncIsReturnAnnotated && FuncDecl->getNumParams() == 0) return CF_BRIDGING_NONE; - + bool ReturnCFAudited = false; if (!FuncIsReturnAnnotated) { RetEffect Ret = CE.getReturnValue(); @@ -1524,7 +1524,7 @@ ObjCMigrateASTConsumer::CF_BRIDGING_KIND else if (!AuditedType(FuncDecl->getReturnType())) return CF_BRIDGING_NONE; } - + // At this point result type is audited for potential inclusion. // Now, how about argument types. ArrayRef<ArgEffect> AEArgs = CE.getArgs(); @@ -1550,7 +1550,7 @@ ObjCMigrateASTConsumer::CF_BRIDGING_KIND } if (ReturnCFAudited || ArgCFAudited) return CF_BRIDGING_ENABLE; - + return CF_BRIDGING_MAY_INCLUDE; } @@ -1558,7 +1558,7 @@ void ObjCMigrateASTConsumer::migrateARCSafeAnnotation(ASTContext &Ctx, ObjCContainerDecl *CDecl) { if (!isa<ObjCInterfaceDecl>(CDecl) || CDecl->isDeprecated()) return; - + // migrate methods which can have instancetype as their result type. for (const auto *Method : CDecl->methods()) migrateCFAnnotation(Ctx, Method); @@ -1588,14 +1588,14 @@ void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx, case clang::OMF_init: case clang::OMF_mutableCopy: break; - + default: if (Ret.isOwned() && NSAPIObj->isMacroDefined("NS_RETURNS_RETAINED")) AnnotationString = " NS_RETURNS_RETAINED"; break; } } - + if (AnnotationString) { edit::Commit commit(*Editor); commit.insertBefore(MethodDecl->getLocEnd(), AnnotationString); @@ -1622,7 +1622,7 @@ void ObjCMigrateASTConsumer::migrateAddMethodAnnotation( const ObjCMethodDecl *MethodDecl) { if (MethodDecl->hasBody() || MethodDecl->isImplicit()) return; - + CallEffects CE = CallEffects::getEffect(MethodDecl); bool MethodIsReturnAnnotated = (MethodDecl->hasAttr<CFReturnsRetainedAttr>() || MethodDecl->hasAttr<CFReturnsNotRetainedAttr>() || @@ -1639,12 +1639,12 @@ void ObjCMigrateASTConsumer::migrateAddMethodAnnotation( commit.insertBefore(MethodDecl->getLocEnd(), " NS_CONSUMES_SELF"); Editor->commit(commit); } - + // Trivial case of when function is annotated and has no argument. if (MethodIsReturnAnnotated && (MethodDecl->param_begin() == MethodDecl->param_end())) return; - + if (!MethodIsReturnAnnotated) { RetEffect Ret = CE.getReturnValue(); if ((Ret.getObjKind() == RetEffect::CF || @@ -1655,7 +1655,7 @@ void ObjCMigrateASTConsumer::migrateAddMethodAnnotation( } else if (!AuditedType(MethodDecl->getReturnType())) return; } - + // At this point result type is either annotated or audited. // Now, how about argument types. ArrayRef<ArgEffect> AEArgs = CE.getArgs(); @@ -1811,7 +1811,7 @@ private: OS.write_escaped(Text) << "\",\n"; } }; - + void insert(SourceLocation Loc, StringRef Text) override { EntryWriter Writer(SourceMgr, OS); Writer.writeLoc(Loc); @@ -1835,7 +1835,7 @@ private: } // end anonymous namespace void ObjCMigrateASTConsumer::HandleTranslationUnit(ASTContext &Ctx) { - + TranslationUnitDecl *TU = Ctx.getTranslationUnitDecl(); if (ASTMigrateActions & FrontendOptions::ObjCMT_MigrateDecls) { for (DeclContext::decl_iterator D = TU->decls_begin(), DEnd = TU->decls_end(); @@ -1846,7 +1846,7 @@ void ObjCMigrateASTConsumer::HandleTranslationUnit(ASTContext &Ctx) { if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) AnnotateImplicitBridging(Ctx); } - + if (ObjCInterfaceDecl *CDecl = dyn_cast<ObjCInterfaceDecl>(*D)) if (canModify(CDecl)) migrateObjCContainerDecl(Ctx, CDecl); @@ -1911,7 +1911,7 @@ void ObjCMigrateASTConsumer::HandleTranslationUnit(ASTContext &Ctx) { canModify(FD)) migrateCFAnnotation(Ctx, FD); } - + if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(*D)) { bool CanModify = canModify(CDecl); // migrate methods which can have instancetype as their result type. @@ -1934,7 +1934,7 @@ void ObjCMigrateASTConsumer::HandleTranslationUnit(ASTContext &Ctx) { if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) AnnotateImplicitBridging(Ctx); } - + if (IsOutputFile) { std::error_code EC; llvm::raw_fd_ostream OS(MigrateDir, EC, llvm::sys::fs::F_None); diff --git a/lib/ARCMigrate/PlistReporter.cpp b/lib/ARCMigrate/PlistReporter.cpp index 2ad1c8591a9e..9e4cb3f4cd83 100644 --- a/lib/ARCMigrate/PlistReporter.cpp +++ b/lib/ARCMigrate/PlistReporter.cpp @@ -81,7 +81,7 @@ void arcmt::writeARCDiagsToPlist(const std::string &outPath, for (ArrayRef<StoredDiagnostic>::iterator DI = diags.begin(), DE = diags.end(); DI != DE; ++DI) { - + const StoredDiagnostic &D = *DI; if (D.getLevel() == DiagnosticsEngine::Ignored) diff --git a/lib/ARCMigrate/TransARCAssign.cpp b/lib/ARCMigrate/TransARCAssign.cpp index 80bfd22d6258..d2b4de4891c3 100644 --- a/lib/ARCMigrate/TransARCAssign.cpp +++ b/lib/ARCMigrate/TransARCAssign.cpp @@ -65,7 +65,7 @@ public: } } } - + return true; } }; diff --git a/lib/ARCMigrate/TransAutoreleasePool.cpp b/lib/ARCMigrate/TransAutoreleasePool.cpp index a8a99fa712a3..2d35655d186f 100644 --- a/lib/ARCMigrate/TransAutoreleasePool.cpp +++ b/lib/ARCMigrate/TransAutoreleasePool.cpp @@ -80,7 +80,7 @@ public: Body = body; TraverseStmt(body); } - + ~AutoreleasePoolRewriter() { SmallVector<VarDecl *, 8> VarsToHandle; @@ -174,7 +174,7 @@ public: PoolVarInfo &info = PoolVars[VD]; info.Dcl = DclS; collectRefs(VD, S, info.Refs); - // Does this statement follow the pattern: + // Does this statement follow the pattern: // NSAutoreleasePool * pool = [NSAutoreleasePool new]; if (isPoolCreation(VD->getInit())) { Scopes.push_back(PoolScope()); @@ -188,7 +188,7 @@ public: } else if (BinaryOperator *bop = dyn_cast<BinaryOperator>(child)) { if (DeclRefExpr *dref = dyn_cast<DeclRefExpr>(bop->getLHS())) { if (VarDecl *VD = dyn_cast<VarDecl>(dref->getDecl())) { - // Does this statement follow the pattern: + // Does this statement follow the pattern: // pool = [NSAutoreleasePool new]; if (isNSAutoreleasePool(VD->getType()) && isPoolCreation(bop->getRHS())) { @@ -311,7 +311,7 @@ private: scope.IsFollowedBySimpleReturnStmt = true; ++SI; // the return will be included in scope, don't check it. } - + for (; SI != SE; ++SI) { nameUsedOutsideScope = !NameReferenceChecker(Pass.Ctx, scope, referenceLoc, @@ -415,7 +415,7 @@ private: IdentifierInfo *PoolII; Selector DrainSel; - + struct PoolVarInfo { DeclStmt *Dcl; ExprSet Refs; diff --git a/lib/ARCMigrate/TransBlockObjCVariable.cpp b/lib/ARCMigrate/TransBlockObjCVariable.cpp index fac6a84c45e5..85bdabb50461 100644 --- a/lib/ARCMigrate/TransBlockObjCVariable.cpp +++ b/lib/ARCMigrate/TransBlockObjCVariable.cpp @@ -43,11 +43,11 @@ class RootBlockObjCVarRewriter : class BlockVarChecker : public RecursiveASTVisitor<BlockVarChecker> { VarDecl *Var; - + typedef RecursiveASTVisitor<BlockVarChecker> base; public: BlockVarChecker(VarDecl *var) : Var(var) { } - + bool TraverseImplicitCastExpr(ImplicitCastExpr *castE) { if (DeclRefExpr * ref = dyn_cast<DeclRefExpr>(castE->getSubExpr())) { @@ -77,7 +77,7 @@ public: bool VisitBlockDecl(BlockDecl *block) { SmallVector<VarDecl *, 4> BlockVars; - + for (const auto &I : block->captures()) { VarDecl *var = I.getVariable(); if (I.isByRef() && diff --git a/lib/ARCMigrate/TransEmptyStatementsAndDealloc.cpp b/lib/ARCMigrate/TransEmptyStatementsAndDealloc.cpp index cbc22ed60172..0327b0def1e6 100644 --- a/lib/ARCMigrate/TransEmptyStatementsAndDealloc.cpp +++ b/lib/ARCMigrate/TransEmptyStatementsAndDealloc.cpp @@ -208,7 +208,7 @@ static void cleanupDeallocOrFinalize(MigrationPass &pass) { for (auto *MD : I->instance_methods()) { if (!MD->hasBody()) continue; - + if (MD->getMethodFamily() == OMF_dealloc) { DeallocM = MD; } else if (MD->isInstanceMethod() && MD->getSelector() == FinalizeSel) { diff --git a/lib/ARCMigrate/TransGCAttrs.cpp b/lib/ARCMigrate/TransGCAttrs.cpp index 4fd21aa6c269..fb45cd92c1f6 100644 --- a/lib/ARCMigrate/TransGCAttrs.cpp +++ b/lib/ARCMigrate/TransGCAttrs.cpp @@ -48,7 +48,7 @@ public: return true; SaveAndRestore<bool> Save(FullyMigratable, isMigratable(D)); - + if (ObjCPropertyDecl *PropD = dyn_cast<ObjCPropertyDecl>(D)) { lookForAttribute(PropD, PropD->getTypeSourceInfo()); AllProps.push_back(PropD); @@ -107,7 +107,7 @@ public: Kind = MigrationContext::GCAttrOccurrence::Weak; else return false; - + MigrateCtx.AttrSet.insert(RawLoc); MigrateCtx.GCAttrs.push_back(MigrationContext::GCAttrOccurrence()); MigrationContext::GCAttrOccurrence &Attr = MigrateCtx.GCAttrs.back(); @@ -164,7 +164,7 @@ public: for (auto I : D->redecls()) if (!isInMainFile(I->getLocation())) return false; - + return true; } diff --git a/lib/ARCMigrate/TransProperties.cpp b/lib/ARCMigrate/TransProperties.cpp index 1468c21a0093..912f77aeb789 100644 --- a/lib/ARCMigrate/TransProperties.cpp +++ b/lib/ARCMigrate/TransProperties.cpp @@ -47,7 +47,7 @@ class PropertiesRewriter { MigrationContext &MigrateCtx; MigrationPass &Pass; ObjCImplementationDecl *CurImplD; - + enum PropActionKind { PropAction_None, PropAction_RetainReplacedWithStrong, @@ -118,7 +118,7 @@ public: AtPropDeclsTy::iterator findAtLoc = AtProps.find(rawAtLoc); if (findAtLoc == AtProps.end()) continue; - + PropsTy &props = findAtLoc->second; for (PropsTy::iterator I = props.begin(), E = props.end(); I != E; ++I) { if (I->PropD == propD) { @@ -137,7 +137,7 @@ public: continue; if (hasIvarWithExplicitARCOwnership(props)) continue; - + Transaction Trans(Pass.TA); rewriteProperty(props, atLoc); } @@ -170,7 +170,7 @@ private: void rewriteProperty(PropsTy &props, SourceLocation atLoc) { ObjCPropertyDecl::PropertyAttributeKind propAttrs = getPropertyAttrs(props); - + if (propAttrs & (ObjCPropertyDecl::OBJC_PR_copy | ObjCPropertyDecl::OBJC_PR_unsafe_unretained | ObjCPropertyDecl::OBJC_PR_strong | @@ -215,7 +215,7 @@ private: void rewriteAssign(PropsTy &props, SourceLocation atLoc) const { bool canUseWeak = canApplyWeak(Pass.Ctx, getPropertyType(props), /*AllowOnUnknownClass=*/Pass.isGCMigration()); - const char *toWhich = + const char *toWhich = (Pass.isGCMigration() && !hasGCWeak(props, atLoc)) ? "strong" : (canUseWeak ? "weak" : "unsafe_unretained"); @@ -227,7 +227,7 @@ private: if (isUserDeclared(I->IvarD)) { if (I->IvarD && I->IvarD->getType().getObjCLifetime() != Qualifiers::OCL_Weak) { - const char *toWhich = + const char *toWhich = (Pass.isGCMigration() && !hasGCWeak(props, atLoc)) ? "__strong " : (canUseWeak ? "__weak " : "__unsafe_unretained "); Pass.TA.insert(I->IvarD->getLocation(), toWhich); @@ -327,7 +327,7 @@ private: } } - return false; + return false; } // Returns true if all declarations in the @property have GC __weak. diff --git a/lib/ARCMigrate/TransProtectedScope.cpp b/lib/ARCMigrate/TransProtectedScope.cpp index 0fcbcbedfe04..1bb4c1f4e449 100644 --- a/lib/ARCMigrate/TransProtectedScope.cpp +++ b/lib/ARCMigrate/TransProtectedScope.cpp @@ -46,7 +46,7 @@ struct CaseInfo { St_CannotFix, St_Fixed } State; - + CaseInfo() : SC(nullptr), State(St_Unchecked) {} CaseInfo(SwitchCase *S, SourceRange Range) : SC(S), Range(Range), State(St_Unchecked) {} diff --git a/lib/ARCMigrate/TransRetainReleaseDealloc.cpp b/lib/ARCMigrate/TransRetainReleaseDealloc.cpp index ebe289b34df8..c411044ecde3 100644 --- a/lib/ARCMigrate/TransRetainReleaseDealloc.cpp +++ b/lib/ARCMigrate/TransRetainReleaseDealloc.cpp @@ -251,7 +251,7 @@ private: while (OuterS && (isa<ParenExpr>(OuterS) || isa<CastExpr>(OuterS) || isa<ExprWithCleanups>(OuterS))); - + if (!OuterS) return std::make_pair(prevStmt, nextStmt); @@ -419,7 +419,7 @@ private: bool isRemovable(Expr *E) const { return Removables.count(E); } - + bool tryRemoving(Expr *E) const { if (isRemovable(E)) { Pass.TA.removeStmt(E); diff --git a/lib/ARCMigrate/TransUnbridgedCasts.cpp b/lib/ARCMigrate/TransUnbridgedCasts.cpp index de52bef4d206..66167d37ac95 100644 --- a/lib/ARCMigrate/TransUnbridgedCasts.cpp +++ b/lib/ARCMigrate/TransUnbridgedCasts.cpp @@ -97,7 +97,7 @@ public: if (castType->isObjCRetainableType() == castExprType->isObjCRetainableType()) return true; - + bool exprRetainable = castExprType->isObjCIndirectLifetimeType(); bool castRetainable = castType->isObjCIndirectLifetimeType(); if (exprRetainable == castRetainable) return true; @@ -153,7 +153,7 @@ private: // Do not migrate to couple of bridge transfer casts which // cancel each other out. Leave it unchanged so error gets user // attention instead. - if (FD->getName() == "CFRetain" && + if (FD->getName() == "CFRetain" && FD->getNumParams() == 1 && FD->getParent()->isTranslationUnit() && FD->isExternallyVisible()) { diff --git a/lib/ARCMigrate/TransZeroOutPropsInDealloc.cpp b/lib/ARCMigrate/TransZeroOutPropsInDealloc.cpp index 76ce0ec90db3..220102ec49ce 100644 --- a/lib/ARCMigrate/TransZeroOutPropsInDealloc.cpp +++ b/lib/ARCMigrate/TransZeroOutPropsInDealloc.cpp @@ -56,7 +56,7 @@ public: bool BackedBySynthesizeSetter = false; for (llvm::DenseMap<ObjCPropertyDecl*, ObjCPropertyImplDecl*>::iterator - P = SynthesizedProperties.begin(), + P = SynthesizedProperties.begin(), E = SynthesizedProperties.end(); P != E; ++P) { ObjCPropertyDecl *PropDecl = P->first; if (PropDecl->getSetterName() == ME->getSelector()) { @@ -66,11 +66,11 @@ public: } if (!BackedBySynthesizeSetter) return true; - + // Remove the setter message if RHS is null Transaction Trans(TA); Expr *RHS = ME->getArg(0); - bool RHSIsNull = + bool RHSIsNull = RHS->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNull); if (RHSIsNull && isRemovable(ME)) @@ -119,10 +119,10 @@ public: ObjCPropertyDecl *PD = PID->getPropertyDecl(); ObjCMethodDecl *setterM = PD->getSetterMethodDecl(); if (!(setterM && setterM->isDefined())) { - ObjCPropertyDecl::PropertyAttributeKind AttrKind = + ObjCPropertyDecl::PropertyAttributeKind AttrKind = PD->getPropertyAttributes(); - if (AttrKind & - (ObjCPropertyDecl::OBJC_PR_retain | + if (AttrKind & + (ObjCPropertyDecl::OBJC_PR_retain | ObjCPropertyDecl::OBJC_PR_copy | ObjCPropertyDecl::OBJC_PR_strong)) SynthesizedProperties[PD] = PID; @@ -173,7 +173,7 @@ private: return false; bool IvarBacksPropertySynthesis = false; for (llvm::DenseMap<ObjCPropertyDecl*, ObjCPropertyImplDecl*>::iterator - P = SynthesizedProperties.begin(), + P = SynthesizedProperties.begin(), E = SynthesizedProperties.end(); P != E; ++P) { ObjCPropertyImplDecl *PropImpDecl = P->second; if (PropImpDecl && PropImpDecl->getPropertyIvarDecl() == IVDecl) { diff --git a/lib/ARCMigrate/TransformActions.cpp b/lib/ARCMigrate/TransformActions.cpp index 704be4374d3d..3f79cc441e85 100644 --- a/lib/ARCMigrate/TransformActions.cpp +++ b/lib/ARCMigrate/TransformActions.cpp @@ -76,7 +76,7 @@ class TransformActionsImpl { End = FullSourceLoc(srcMgr.getExpansionLoc(endLoc), srcMgr); } assert(Begin.isValid() && End.isValid()); - } + } RangeComparison compareWith(const CharRange &RHS) const { if (End.isBeforeInTranslationUnitThan(RHS.Begin)) @@ -94,7 +94,7 @@ class TransformActionsImpl { else return Range_ExtendsEnd; } - + static RangeComparison compare(SourceRange LHS, SourceRange RHS, SourceManager &SrcMgr, Preprocessor &PP) { return CharRange(CharSourceRange::getTokenRange(LHS), SrcMgr, PP) @@ -485,7 +485,7 @@ void TransformActionsImpl::commitReplaceText(SourceLocation loc, SourceLocation afterText = loc.getLocWithOffset(text.size()); addRemoval(CharSourceRange::getCharRange(loc, afterText)); - commitInsert(loc, replacementText); + commitInsert(loc, replacementText); } void TransformActionsImpl::commitIncreaseIndentation(SourceRange range, diff --git a/lib/ARCMigrate/Transforms.cpp b/lib/ARCMigrate/Transforms.cpp index 1f4e6a297fc3..4a7af2858879 100644 --- a/lib/ARCMigrate/Transforms.cpp +++ b/lib/ARCMigrate/Transforms.cpp @@ -203,7 +203,7 @@ bool trans::isGlobalVar(Expr *E) { return isGlobalVar(condOp->getTrueExpr()) && isGlobalVar(condOp->getFalseExpr()); - return false; + return false; } StringRef trans::getNilString(MigrationPass &Pass) { @@ -240,9 +240,9 @@ class RemovablesCollector : public RecursiveASTVisitor<RemovablesCollector> { public: RemovablesCollector(ExprSet &removables) : Removables(removables) { } - + bool shouldWalkTypesOfTypeLocs() const { return false; } - + bool TraverseStmtExpr(StmtExpr *E) { CompoundStmt *S = E->getSubStmt(); for (CompoundStmt::body_iterator @@ -253,40 +253,40 @@ public: } return true; } - + bool VisitCompoundStmt(CompoundStmt *S) { for (auto *I : S->body()) mark(I); return true; } - + bool VisitIfStmt(IfStmt *S) { mark(S->getThen()); mark(S->getElse()); return true; } - + bool VisitWhileStmt(WhileStmt *S) { mark(S->getBody()); return true; } - + bool VisitDoStmt(DoStmt *S) { mark(S->getBody()); return true; } - + bool VisitForStmt(ForStmt *S) { mark(S->getInit()); mark(S->getInc()); mark(S->getBody()); return true; } - + private: void mark(Stmt *S) { if (!S) return; - + while (LabelStmt *Label = dyn_cast<LabelStmt>(S)) S = Label->getSubStmt(); S = S->IgnoreImplicit(); @@ -408,12 +408,12 @@ bool MigrationContext::rewritePropertyAttribute(StringRef fromAttr, return false; lexer.LexFromRawLexer(tok); if (tok.isNot(tok::l_paren)) return false; - + Token BeforeTok = tok; Token AfterTok; AfterTok.startToken(); SourceLocation AttrLoc; - + lexer.LexFromRawLexer(tok); if (tok.is(tok::r_paren)) return false; @@ -454,7 +454,7 @@ bool MigrationContext::rewritePropertyAttribute(StringRef fromAttr, return true; } - + return false; } @@ -493,7 +493,7 @@ bool MigrationContext::addPropertyAttribute(StringRef attr, Pass.TA.insert(tok.getLocation(), std::string("(") + attr.str() + ") "); return true; } - + lexer.LexFromRawLexer(tok); if (tok.is(tok::r_paren)) { Pass.TA.insert(tok.getLocation(), attr); @@ -520,7 +520,7 @@ static void GCRewriteFinalize(MigrationPass &pass) { DeclContext *DC = Ctx.getTranslationUnitDecl(); Selector FinalizeSel = Ctx.Selectors.getNullarySelector(&pass.Ctx.Idents.get("finalize")); - + typedef DeclContext::specific_decl_iterator<ObjCImplementationDecl> impl_iterator; for (impl_iterator I = impl_iterator(DC->decls_begin()), @@ -528,11 +528,11 @@ static void GCRewriteFinalize(MigrationPass &pass) { for (const auto *MD : I->instance_methods()) { if (!MD->hasBody()) continue; - + if (MD->isInstanceMethod() && MD->getSelector() == FinalizeSel) { const ObjCMethodDecl *FinalizeM = MD; Transaction Trans(TA); - TA.insert(FinalizeM->getSourceRange().getBegin(), + TA.insert(FinalizeM->getSourceRange().getBegin(), "#if !__has_feature(objc_arc)\n"); CharSourceRange::getTokenRange(FinalizeM->getSourceRange()); const SourceManager &SM = pass.Ctx.getSourceManager(); @@ -540,10 +540,10 @@ static void GCRewriteFinalize(MigrationPass &pass) { bool Invalid; std::string str = "\n#endif\n"; str += Lexer::getSourceText( - CharSourceRange::getTokenRange(FinalizeM->getSourceRange()), + CharSourceRange::getTokenRange(FinalizeM->getSourceRange()), SM, LangOpts, &Invalid); TA.insertAfterToken(FinalizeM->getSourceRange().getEnd(), str); - + break; } } diff --git a/lib/ARCMigrate/Transforms.h b/lib/ARCMigrate/Transforms.h index 8ea4f79456a8..bafe9fc52a27 100644 --- a/lib/ARCMigrate/Transforms.h +++ b/lib/ARCMigrate/Transforms.h @@ -103,7 +103,7 @@ public: explicit MigrationContext(MigrationPass &pass) : Pass(pass) {} ~MigrationContext(); - + typedef std::vector<ASTTraverser *>::iterator traverser_iterator; traverser_iterator traversers_begin() { return Traversers.begin(); } traverser_iterator traversers_end() { return Traversers.end(); } diff --git a/lib/AST/ASTContext.cpp b/lib/AST/ASTContext.cpp index 25dc4441aafd..d50f4493788a 100644 --- a/lib/AST/ASTContext.cpp +++ b/lib/AST/ASTContext.cpp @@ -492,11 +492,11 @@ comments::FullComment *ASTContext::getCommentForDecl( if (D->isInvalidDecl()) return nullptr; D = adjustDeclToTemplate(D); - + const Decl *Canonical = D->getCanonicalDecl(); llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos = ParsedComments.find(Canonical); - + if (Pos != ParsedComments.end()) { if (Canonical != D) { comments::FullComment *FC = Pos->second; @@ -505,9 +505,9 @@ comments::FullComment *ASTContext::getCommentForDecl( } return Pos->second; } - + const Decl *OriginalDecl; - + const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl); if (!RC) { if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) { @@ -558,7 +558,7 @@ comments::FullComment *ASTContext::getCommentForDecl( if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) { if (!(NonVirtualBase= NonVirtualBase->getDefinition())) continue; - + if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP)) return cloneFullComment(FC, D); } @@ -580,7 +580,7 @@ comments::FullComment *ASTContext::getCommentForDecl( } return nullptr; } - + // If the RawComment was attached to other redeclaration of this Decl, we // should parse the comment in context of that other Decl. This is important // because comments can contain references to parameter names which can be @@ -593,8 +593,8 @@ comments::FullComment *ASTContext::getCommentForDecl( return FC; } -void -ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID, +void +ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID, TemplateTemplateParmDecl *Parm) { ID.AddInteger(Parm->getDepth()); ID.AddInteger(Parm->getPosition()); @@ -602,7 +602,7 @@ ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID, TemplateParameterList *Params = Parm->getTemplateParameters(); ID.AddInteger(Params->size()); - for (TemplateParameterList::const_iterator P = Params->begin(), + for (TemplateParameterList::const_iterator P = Params->begin(), PEnd = Params->end(); P != PEnd; ++P) { if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) { @@ -610,7 +610,7 @@ ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID, ID.AddBoolean(TTP->isParameterPack()); continue; } - + if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) { ID.AddInteger(1); ID.AddBoolean(NTTP->isParameterPack()); @@ -622,11 +622,11 @@ ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID, QualType T = NTTP->getExpansionType(I); ID.AddPointer(T.getCanonicalType().getAsOpaquePtr()); } - } else + } else ID.AddBoolean(false); continue; } - + auto *TTP = cast<TemplateTemplateParmDecl>(*P); ID.AddInteger(2); Profile(ID, TTP); @@ -644,17 +644,17 @@ ASTContext::getCanonicalTemplateTemplateParmDecl( = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); if (Canonical) return Canonical->getParam(); - + // Build a canonical template parameter list. TemplateParameterList *Params = TTP->getTemplateParameters(); SmallVector<NamedDecl *, 4> CanonParams; CanonParams.reserve(Params->size()); - for (TemplateParameterList::const_iterator P = Params->begin(), + for (TemplateParameterList::const_iterator P = Params->begin(), PEnd = Params->end(); P != PEnd; ++P) { if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) CanonParams.push_back( - TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(), + TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(), SourceLocation(), SourceLocation(), TTP->getDepth(), @@ -672,7 +672,7 @@ ASTContext::getCanonicalTemplateTemplateParmDecl( ExpandedTInfos.push_back( getTrivialTypeSourceInfo(ExpandedTypes.back())); } - + Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), SourceLocation(), SourceLocation(), @@ -704,9 +704,9 @@ ASTContext::getCanonicalTemplateTemplateParmDecl( Expr *const CanonRequiresClause = nullptr; TemplateTemplateParmDecl *CanonTTP - = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(), + = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(), SourceLocation(), TTP->getDepth(), - TTP->getPosition(), + TTP->getPosition(), TTP->isParameterPack(), nullptr, TemplateParameterList::Create(*this, SourceLocation(), @@ -823,7 +823,7 @@ ASTContext::~ASTContext() { if (auto *R = const_cast<ASTRecordLayout *>((I++)->second)) R->Destroy(*this); } - + for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(), AEnd = DeclAttrs.end(); A != AEnd; ++A) @@ -1001,7 +1001,7 @@ void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) { ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) { auto It = ModuleInitializers.find(M); - if (It == ModuleInitializers.end()) + if (It == ModuleInitializers.end()) return None; auto *Inits = It->second; @@ -1098,7 +1098,7 @@ void ASTContext::InitBuiltinTypes(const TargetInfo &Target, ABI.reset(createCXXABI(Target)); AddrSpaceMap = getAddressSpaceMap(Target, LangOpts); AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts); - + // C99 6.2.5p19. InitBuiltinType(VoidTy, BuiltinType::Void); @@ -1242,13 +1242,13 @@ void ASTContext::InitBuiltinTypes(const TargetInfo &Target, InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue); InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID); } - + // Builtin type for __objc_yes and __objc_no ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ? SignedCharTy : BoolTy); - + ObjCConstantStringType = QualType(); - + ObjCSuperType = QualType(); // void * type @@ -1281,7 +1281,7 @@ AttrVec& ASTContext::getDeclAttrs(const Decl *D) { void *Mem = Allocate(sizeof(AttrVec)); Result = new (Mem) AttrVec; } - + return *Result; } @@ -1361,11 +1361,11 @@ void ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) { assert((isa<UsingDecl>(Pattern) || isa<UnresolvedUsingValueDecl>(Pattern) || - isa<UnresolvedUsingTypenameDecl>(Pattern)) && + isa<UnresolvedUsingTypenameDecl>(Pattern)) && "pattern decl is not a using decl"); assert((isa<UsingDecl>(Inst) || isa<UnresolvedUsingValueDecl>(Inst) || - isa<UnresolvedUsingTypenameDecl>(Inst)) && + isa<UnresolvedUsingTypenameDecl>(Inst)) && "instantiation did not produce a using decl"); assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists"); InstantiatedFromUsingDecl[Inst] = Pattern; @@ -1432,7 +1432,7 @@ ASTContext::overridden_methods(const CXXMethodDecl *Method) const { return overridden_method_range(Pos->second.begin(), Pos->second.end()); } -void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method, +void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method, const CXXMethodDecl *Overridden) { assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl()); OverriddenMethods[Method].push_back(Overridden); @@ -1466,7 +1466,7 @@ void ASTContext::addedLocalImportDecl(ImportDecl *Import) { LastLocalImport = Import; return; } - + LastLocalImport->NextLocalImport = Import; LastLocalImport = Import; } @@ -1513,7 +1513,7 @@ CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const { } } else if (isa<FieldDecl>(D)) - UseAlignAttrOnly = + UseAlignAttrOnly = D->hasAttr<PackedAttr>() || cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>(); @@ -1881,7 +1881,7 @@ TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const { case BuiltinType::ObjCId: case BuiltinType::ObjCClass: case BuiltinType::ObjCSel: - Width = Target->getPointerWidth(0); + Width = Target->getPointerWidth(0); Align = Target->getPointerAlign(0); break; case BuiltinType::OCLSampler: @@ -2056,6 +2056,27 @@ TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const { return TypeInfo(Width, Align, AlignIsRequired); } +unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const { + UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T); + if (I != MemoizedUnadjustedAlign.end()) + return I->second; + + unsigned UnadjustedAlign; + if (const auto *RT = T->getAs<RecordType>()) { + const RecordDecl *RD = RT->getDecl(); + const ASTRecordLayout &Layout = getASTRecordLayout(RD); + UnadjustedAlign = toBits(Layout.getUnadjustedAlignment()); + } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) { + const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); + UnadjustedAlign = toBits(Layout.getUnadjustedAlignment()); + } else { + UnadjustedAlign = getTypeAlign(T); + } + + MemoizedUnadjustedAlign[T] = UnadjustedAlign; + return UnadjustedAlign; +} + unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const { unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign(); // Target ppc64 with QPX: simd default alignment for pointer to double is 32. @@ -2086,7 +2107,7 @@ CharUnits ASTContext::getTypeSizeInChars(const Type *T) const { return getTypeInfoInChars(T).first; } -/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in +/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in /// characters. This method does not work on incomplete types. CharUnits ASTContext::getTypeAlignInChars(QualType T) const { return toCharUnitsFromBits(getTypeAlign(T)); @@ -2095,6 +2116,16 @@ CharUnits ASTContext::getTypeAlignInChars(const Type *T) const { return toCharUnitsFromBits(getTypeAlign(T)); } +/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a +/// type, in characters, before alignment adustments. This method does +/// not work on incomplete types. +CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const { + return toCharUnitsFromBits(getTypeUnadjustedAlign(T)); +} +CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const { + return toCharUnitsFromBits(getTypeUnadjustedAlign(T)); +} + /// getPreferredTypeAlign - Return the "preferred" alignment of the specified /// type for the current target in bits. This can be different than the ABI /// alignment in cases where it is beneficial for performance to overalign @@ -2172,7 +2203,7 @@ void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, Ivars.push_back(I); } else { auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI); - for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv; + for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv; Iv= Iv->getNextIvar()) Ivars.push_back(Iv); } @@ -2184,11 +2215,11 @@ void ASTContext::CollectInheritedProtocols(const Decl *CDecl, llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) { if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) { // We can use protocol_iterator here instead of - // all_referenced_protocol_iterator since we are walking all categories. + // all_referenced_protocol_iterator since we are walking all categories. for (auto *Proto : OI->all_referenced_protocols()) { CollectInheritedProtocols(Proto, Protocols); } - + // Categories of this Interface. for (const auto *Cat : OI->visible_categories()) CollectInheritedProtocols(Cat, Protocols); @@ -2379,11 +2410,11 @@ bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const { } unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const { - unsigned count = 0; + unsigned count = 0; // Count ivars declared in class extension. for (const auto *Ext : OI->known_extensions()) count += Ext->ivar_size(); - + // Count ivar defined in this class's implementation. This // includes synthesized ivars. if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) @@ -2471,7 +2502,7 @@ const ObjCInterfaceDecl *ASTContext::getObjContainingInterface( /// none exists. Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) { assert(VD && "Passed null params"); - assert(VD->hasAttr<BlocksAttr>() && + assert(VD->hasAttr<BlocksAttr>() && "getBlockVarCopyInits - not __block var"); llvm::DenseMap<const VarDecl*, Expr*>::iterator I = BlockVarCopyInits.find(VD); @@ -2481,7 +2512,7 @@ Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) { /// Set the copy inialization expression of a block var decl. void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) { assert(VD && Init && "Passed null params"); - assert(VD->hasAttr<BlocksAttr>() && + assert(VD->hasAttr<BlocksAttr>() && "setBlockVarCopyInits - not __block var"); BlockVarCopyInits[VD] = Init; } @@ -2868,9 +2899,9 @@ QualType ASTContext::getBlockPointerType(QualType T) const { /// lvalue reference to the specified type. QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const { - assert(getCanonicalType(T) != OverloadTy && + assert(getCanonicalType(T) != OverloadTy && "Unresolved overloaded function type"); - + // Unique pointers, to guarantee there is only one pointer of a particular // structure. llvm::FoldingSetNodeID ID; @@ -3159,7 +3190,7 @@ QualType ASTContext::getVariableArrayType(QualType EltTy, // Since we don't unique expressions, it isn't possible to unique VLA's // that have an expression provided for their size. QualType Canon; - + // Be sure to pull qualifiers off the element type. if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) { SplitQualType canonSplit = getCanonicalType(EltTy).split(); @@ -3167,7 +3198,7 @@ QualType ASTContext::getVariableArrayType(QualType EltTy, IndexTypeQuals, Brackets); Canon = getQualifiedType(Canon, canonSplit.Quals); } - + auto *New = new (*this, TypeAlignment) VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets); @@ -3184,7 +3215,7 @@ QualType ASTContext::getDependentSizedArrayType(QualType elementType, ArrayType::ArraySizeModifier ASM, unsigned elementTypeQuals, SourceRange brackets) const { - assert((!numElements || numElements->isTypeDependent() || + assert((!numElements || numElements->isTypeDependent() || numElements->isValueDependent()) && "Size must be type- or value-dependent!"); @@ -3417,7 +3448,7 @@ ASTContext::getDependentSizedExtVectorType(QualType vecType, } else { QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr, SourceLocation()); - New = new (*this, TypeAlignment) + New = new (*this, TypeAlignment) DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc); } } @@ -3426,10 +3457,10 @@ ASTContext::getDependentSizedExtVectorType(QualType vecType, return QualType(New, 0); } -QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType, - Expr *AddrSpaceExpr, +QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType, + Expr *AddrSpaceExpr, SourceLocation AttrLoc) const { - assert(AddrSpaceExpr->isInstantiationDependent()); + assert(AddrSpaceExpr->isInstantiationDependent()); QualType canonPointeeType = getCanonicalType(PointeeType); @@ -3443,22 +3474,22 @@ QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType, if (!canonTy) { canonTy = new (*this, TypeAlignment) - DependentAddressSpaceType(*this, canonPointeeType, + DependentAddressSpaceType(*this, canonPointeeType, QualType(), AddrSpaceExpr, AttrLoc); DependentAddressSpaceTypes.InsertNode(canonTy, insertPos); Types.push_back(canonTy); } - + if (canonPointeeType == PointeeType && canonTy->getAddrSpaceExpr() == AddrSpaceExpr) - return QualType(canonTy, 0); + return QualType(canonTy, 0); auto *sugaredType = new (*this, TypeAlignment) - DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0), + DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0), AddrSpaceExpr, AttrLoc); Types.push_back(sugaredType); - return QualType(sugaredType, 0); + return QualType(sugaredType, 0); } /// Determine whether \p T is canonical as the result type of a function. @@ -3818,7 +3849,7 @@ QualType ASTContext::getRecordType(const RecordDecl *Decl) const { if (const RecordDecl *PrevDecl = Decl->getPreviousDecl()) if (PrevDecl->TypeForDecl) - return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); + return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); auto *newType = new (*this, TypeAlignment) RecordType(Decl); Decl->TypeForDecl = newType; @@ -3831,7 +3862,7 @@ QualType ASTContext::getEnumType(const EnumDecl *Decl) const { if (const EnumDecl *PrevDecl = Decl->getPreviousDecl()) if (PrevDecl->TypeForDecl) - return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); + return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); auto *newType = new (*this, TypeAlignment) EnumType(Decl); Decl->TypeForDecl = newType; @@ -3882,7 +3913,7 @@ ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm, return QualType(SubstParm, 0); } -/// Retrieve a +/// Retrieve a QualType ASTContext::getSubstTemplateTypeParmPackType( const TemplateTypeParmType *Parm, const TemplateArgument &ArgPack) { @@ -3892,14 +3923,14 @@ QualType ASTContext::getSubstTemplateTypeParmPackType( assert(P.getAsType().isCanonical() && "Pack contains non-canonical type"); } #endif - + llvm::FoldingSetNodeID ID; SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack); void *InsertPos = nullptr; if (SubstTemplateTypeParmPackType *SubstParm = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos)) return QualType(SubstParm, 0); - + QualType Canon; if (!Parm->isCanonicalUnqualified()) { Canon = getCanonicalType(QualType(Parm, 0)); @@ -3913,7 +3944,7 @@ QualType ASTContext::getSubstTemplateTypeParmPackType( ArgPack); Types.push_back(SubstParm); SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos); - return QualType(SubstParm, 0); + return QualType(SubstParm, 0); } /// Retrieve the template type parameter type for a template @@ -3935,7 +3966,7 @@ QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index, QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack); TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon); - TemplateTypeParmType *TypeCheck + TemplateTypeParmType *TypeCheck = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); assert(!TypeCheck && "Template type parameter canonical type broken"); (void)TypeCheck; @@ -3954,7 +3985,7 @@ ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name, SourceLocation NameLoc, const TemplateArgumentListInfo &Args, QualType Underlying) const { - assert(!Name.getAsDependentTemplateName() && + assert(!Name.getAsDependentTemplateName() && "No dependent template names here!"); QualType TST = getTemplateSpecializationType(Name, Args, Underlying); @@ -3974,7 +4005,7 @@ QualType ASTContext::getTemplateSpecializationType(TemplateName Template, const TemplateArgumentListInfo &Args, QualType Underlying) const { - assert(!Template.getAsDependentTemplateName() && + assert(!Template.getAsDependentTemplateName() && "No dependent template names here!"); SmallVector<TemplateArgument, 4> ArgVec; @@ -3990,7 +4021,7 @@ static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) { for (const TemplateArgument &Arg : Args) if (Arg.isPackExpansion()) return true; - + return true; } #endif @@ -3999,13 +4030,13 @@ QualType ASTContext::getTemplateSpecializationType(TemplateName Template, ArrayRef<TemplateArgument> Args, QualType Underlying) const { - assert(!Template.getAsDependentTemplateName() && + assert(!Template.getAsDependentTemplateName() && "No dependent template names here!"); // Look through qualified template names. if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) Template = TemplateName(QTN->getTemplateDecl()); - - bool IsTypeAlias = + + bool IsTypeAlias = Template.getAsTemplateDecl() && isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl()); QualType CanonType; @@ -4037,13 +4068,13 @@ ASTContext::getTemplateSpecializationType(TemplateName Template, QualType ASTContext::getCanonicalTemplateSpecializationType( TemplateName Template, ArrayRef<TemplateArgument> Args) const { - assert(!Template.getAsDependentTemplateName() && + assert(!Template.getAsDependentTemplateName() && "No dependent template names here!"); // Look through qualified template names. if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) Template = TemplateName(QTN->getTemplateDecl()); - + // Build the canonical template specialization type. TemplateName CanonTemplate = getCanonicalTemplateName(Template); SmallVector<TemplateArgument, 4> CanonArgs; @@ -4174,7 +4205,7 @@ ASTContext::getDependentTemplateSpecializationType( NestedNameSpecifier *NNS, const IdentifierInfo *Name, ArrayRef<TemplateArgument> Args) const { - assert((!NNS || NNS->isDependent()) && + assert((!NNS || NNS->isDependent()) && "nested-name-specifier must be dependent"); llvm::FoldingSetNodeID ID; @@ -4309,7 +4340,7 @@ static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) { if (Protocols[0]->getCanonicalDecl() != Protocols[0]) return false; - + for (unsigned i = 1; i != Protocols.size(); ++i) if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 || Protocols[i]->getCanonicalDecl() != Protocols[i]) @@ -4534,7 +4565,7 @@ bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT, ObjCInterfaceDecl *IC) { if (!QT->isObjCQualifiedIdType()) return false; - + if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) { // If both the right and left sides have qualifiers. for (auto *Proto : OPT->quals()) { @@ -4578,7 +4609,7 @@ bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT, } if (Conforms) return true; - + for (auto *PI : InheritedProtocols) { // If both the right and left sides have qualifiers. bool Adopts = false; @@ -4639,7 +4670,7 @@ QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl, // Prefer the definition, if there is one. if (const ObjCInterfaceDecl *Def = Decl->getDefinition()) Decl = Def; - + void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment); auto *T = new (Mem) ObjCInterfaceType(Decl); Decl->TypeForDecl = T; @@ -4870,7 +4901,7 @@ CanQualType ASTContext::getSizeType() const { return getFromTargetType(Target->getSizeType()); } -/// Return the unique signed counterpart of the integer type +/// Return the unique signed counterpart of the integer type /// corresponding to size_t. CanQualType ASTContext::getSignedSizeType() const { return getFromTargetType(Target->getSignedSizeType()); @@ -5059,14 +5090,14 @@ bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2) { const auto *T1MPType = T1->getAs<MemberPointerType>(); const auto *T2MPType = T2->getAs<MemberPointerType>(); - if (T1MPType && T2MPType && - hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0), + if (T1MPType && T2MPType && + hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0), QualType(T2MPType->getClass(), 0))) { T1 = T1MPType->getPointeeType(); T2 = T2MPType->getPointeeType(); return true; } - + if (getLangOpts().ObjC1) { const auto *T1OPType = T1->getAs<ObjCObjectPointerType>(); const auto *T2OPType = T2->getAs<ObjCObjectPointerType>(); @@ -5076,9 +5107,9 @@ bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2) { return true; } } - + // FIXME: Block pointers, too? - + return false; } @@ -5170,7 +5201,7 @@ TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const { TemplateDecl *Template = Name.getAsTemplateDecl(); if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template)) Template = getCanonicalTemplateTemplateParmDecl(TTP); - + // The canonical template name is the canonical template declaration. return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl())); } @@ -5245,7 +5276,7 @@ ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const { case TemplateArgument::Pack: { if (Arg.pack_size() == 0) return Arg; - + auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()]; unsigned Idx = 0; for (TemplateArgument::pack_iterator A = Arg.pack_begin(), @@ -5289,7 +5320,7 @@ ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const { case NestedNameSpecifier::TypeSpec: case NestedNameSpecifier::TypeSpecWithTemplate: { QualType T = getCanonicalType(QualType(NNS->getAsType(), 0)); - + // If we have some kind of dependent-named type (e.g., "typename T::type"), // break it apart into its prefix and identifier, then reconsititute those // as the canonical nested-name-specifier. This is required to canonicalize @@ -5298,7 +5329,7 @@ ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const { // typedef typename T::type T1; // typedef typename T1::type T2; if (const auto *DNT = T->getAs<DependentNameType>()) - return NestedNameSpecifier::Create(*this, DNT->getQualifier(), + return NestedNameSpecifier::Create(*this, DNT->getQualifier(), const_cast<IdentifierInfo *>(DNT->getIdentifier())); // Otherwise, just canonicalize the type, and force it to be a TypeSpec. @@ -5930,24 +5961,24 @@ bool ASTContext::BlockRequiresCopying(QualType Ty, if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) { const Expr *copyExpr = getBlockVarCopyInits(D); if (!copyExpr && record->hasTrivialDestructor()) return false; - + return true; } - + // The block needs copy/destroy helpers if Ty is non-trivial to destructively // move or destroy. if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType()) return true; if (!Ty->isObjCRetainableType()) return false; - + Qualifiers qs = Ty.getQualifiers(); - + // If we have lifetime, that dominates. if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) { switch (lifetime) { case Qualifiers::OCL_None: llvm_unreachable("impossible"); - + // These are just bits as far as the runtime is concerned. case Qualifiers::OCL_ExplicitNone: case Qualifiers::OCL_Autoreleasing: @@ -5971,7 +6002,7 @@ bool ASTContext::getByrefLifetime(QualType Ty, if (!getLangOpts().ObjC1 || getLangOpts().getGC() != LangOptions::NonGC) return false; - + HasByrefExtendedLayout = false; if (Ty->isRecordType()) { HasByrefExtendedLayout = true; @@ -6009,7 +6040,7 @@ static bool isTypeTypedefedAsBOOL(QualType T) { CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const { if (!type->isIncompleteArrayType() && type->isIncompleteType()) return CharUnits::Zero(); - + CharUnits sz = getTypeSizeInChars(type); // Make all integer and enum types at least as large as an int @@ -6085,11 +6116,11 @@ std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const { S += charUnitsToString(ParmOffset); // Block pointer and offset. S += "@?0"; - + // Argument types. ParmOffset = PtrSize; for (auto PVDecl : Decl->parameters()) { - QualType PType = PVDecl->getOriginalType(); + QualType PType = PVDecl->getOriginalType(); if (const auto *AT = dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { // Use array's original type only if it has known number of @@ -6122,8 +6153,8 @@ ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const { CharUnits sz = getObjCEncodingTypeSize(PType); if (sz.isZero()) continue; - - assert(sz.isPositive() && + + assert(sz.isPositive() && "getObjCEncodingForFunctionDecl - Incomplete param type"); ParmOffset += sz; } @@ -6145,12 +6176,12 @@ ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const { S += charUnitsToString(ParmOffset); ParmOffset += getObjCEncodingTypeSize(PType); } - + return S; } /// getObjCEncodingForMethodParameter - Return the encoded type for a single -/// method parameter or return type. If Extended, include class names and +/// method parameter or return type. If Extended, include class names and /// block object types. void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, QualType T, std::string& S, @@ -6160,9 +6191,9 @@ void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, // Encode parameter type. getObjCEncodingForTypeImpl(T, S, true, true, nullptr, true /*OutermostType*/, - false /*EncodingProperty*/, - false /*StructField*/, - Extended /*EncodeBlockParameters*/, + false /*EncodingProperty*/, + false /*StructField*/, + Extended /*EncodeBlockParameters*/, Extended /*EncodeClassNames*/); } @@ -6188,8 +6219,8 @@ std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, CharUnits sz = getObjCEncodingTypeSize(PType); if (sz.isZero()) continue; - - assert(sz.isPositive() && + + assert(sz.isPositive() && "getObjCEncodingForMethodDecl - Incomplete param type"); ParmOffset += sz; } @@ -6211,12 +6242,12 @@ std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, PType = PVDecl->getType(); } else if (PType->isFunctionType()) PType = PVDecl->getType(); - getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(), + getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(), PType, S, Extended); S += charUnitsToString(ParmOffset); ParmOffset += getObjCEncodingTypeSize(PType); } - + return S; } @@ -6457,11 +6488,11 @@ static char getObjCEncodingForPrimitiveKind(const ASTContext *C, static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) { EnumDecl *Enum = ET->getDecl(); - + // The encoding of an non-fixed enum type is always 'i', regardless of size. if (!Enum->isFixed()) return 'i'; - + // The encoding of a fixed enum type matches its fixed underlying type. const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>(); return getObjCEncodingForPrimitiveKind(C, BT->getKind()); @@ -6709,7 +6740,7 @@ void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S, S += "@?"; // Unlike a pointer-to-function, which is "^?". if (EncodeBlockParameters) { const auto *FT = BT->getPointeeType()->castAs<FunctionType>(); - + S += '<'; // Block return type getObjCEncodingForTypeImpl( @@ -6747,7 +6778,7 @@ void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S, // TODO: Double check to make sure this intentionally falls through. LLVM_FALLTHROUGH; } - + case Type::ObjCInterface: { // Ignore protocol qualifiers when mangling at this level. // @encode(class_name) @@ -6837,7 +6868,7 @@ void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S, } S += '@'; - if (OPT->getInterfaceDecl() && + if (OPT->getInterfaceDecl() && (FD || EncodingProperty || EncodeClassNames)) { S += '"'; S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString(); @@ -6862,7 +6893,7 @@ void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S, if (NotEncodedT) *NotEncodedT = T; return; - + // We could see an undeduced auto type here during error recovery. // Just ignore it. case Type::Auto: @@ -6910,7 +6941,7 @@ void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl, } } } - + unsigned i = 0; for (auto *Field : RDecl->fields()) { uint64_t offs = layout.getFieldOffset(i); @@ -6971,7 +7002,7 @@ void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl, #ifndef NDEBUG assert(CurOffs <= CurLayObj->first); if (CurOffs < CurLayObj->first) { - uint64_t padding = CurLayObj->first - CurOffs; + uint64_t padding = CurLayObj->first - CurOffs; // FIXME: There doesn't seem to be a way to indicate in the encoding that // packing/alignment of members is different that normal, in which case // the encoding will be out-of-sync with the real layout. @@ -7071,15 +7102,15 @@ TypedefDecl *ASTContext::getObjCClassDecl() const { ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const { if (!ObjCProtocolClassDecl) { - ObjCProtocolClassDecl - = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(), + ObjCProtocolClassDecl + = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(), SourceLocation(), &Idents.get("Protocol"), /*typeParamList=*/nullptr, /*PrevDecl=*/nullptr, - SourceLocation(), true); + SourceLocation(), true); } - + return ObjCProtocolClassDecl; } @@ -7485,7 +7516,7 @@ ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS, bool TemplateKeyword, TemplateDecl *Template) const { assert(NNS && "Missing nested-name-specifier in qualified template name"); - + // FIXME: Canonicalization? llvm::FoldingSetNodeID ID; QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template); @@ -7540,22 +7571,22 @@ ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, /// Retrieve the template name that represents a dependent /// template name such as \c MetaFun::template operator+. -TemplateName +TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, OverloadedOperatorKind Operator) const { assert((!NNS || NNS->isDependent()) && "Nested name specifier must be dependent"); - + llvm::FoldingSetNodeID ID; DependentTemplateName::Profile(ID, NNS, Operator); void *InsertPos = nullptr; DependentTemplateName *QTN = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); - + if (QTN) return TemplateName(QTN); - + NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); if (CanonNNS == NNS) { QTN = new (*this, alignof(DependentTemplateName)) @@ -7570,12 +7601,12 @@ ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, assert(!CheckQTN && "Dependent template name canonicalization broken"); (void)CheckQTN; } - + DependentTemplateNames.InsertNode(QTN, InsertPos); return TemplateName(QTN); } -TemplateName +TemplateName ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param, TemplateName replacement) const { llvm::FoldingSetNodeID ID; @@ -7584,7 +7615,7 @@ ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param, void *insertPos = nullptr; SubstTemplateTemplateParmStorage *subst = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos); - + if (!subst) { subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement); SubstTemplateTemplateParms.InsertNode(subst, insertPos); @@ -7593,7 +7624,7 @@ ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param, return TemplateName(subst); } -TemplateName +TemplateName ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param, const TemplateArgument &ArgPack) const { auto &Self = const_cast<ASTContext &>(*this); @@ -7603,9 +7634,9 @@ ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param, void *InsertPos = nullptr; SubstTemplateTemplateParmPackStorage *Subst = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos); - + if (!Subst) { - Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param, + Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param, ArgPack.pack_size(), ArgPack.pack_begin()); SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos); @@ -7725,12 +7756,12 @@ ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and /// Class<pr1, ...>. -bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs, +bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs, QualType rhs) { const auto *lhsQID = lhs->getAs<ObjCObjectPointerType>(); const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); assert((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible"); - + for (auto *lhsProto : lhsQID->quals()) { bool match = false; for (auto *rhsProto : rhsOPT->quals()) { @@ -7835,7 +7866,7 @@ bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs, if (!match) return false; } - + // Static class's protocols, or its super class or category protocols // must be found, direct or indirect in rhs's qualifier list or it is a mismatch. if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) { @@ -7897,12 +7928,12 @@ bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, QualType(RHSOPT,0), false)); } - + if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) { return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0), QualType(RHSOPT,0))); } - + // If we have 2 user-defined types, fall into that path. if (LHS->getInterface() && RHS->getInterface()) { return finish(canAssignObjCInterfaces(LHS, RHS)); @@ -7912,7 +7943,7 @@ bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, } /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written -/// for providing type-safety for objective-c pointers used to pass/return +/// for providing type-safety for objective-c pointers used to pass/return /// arguments in block literals. When passed as arguments, passing 'A*' where /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is /// not OK. For the return type, the opposite is not OK. @@ -7941,17 +7972,17 @@ bool ASTContext::canAssignObjCInterfacesInBlockPointer( if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType()) return true; - + if (LHSOPT->isObjCBuiltinType()) { return finish(RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType()); } - + if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0), QualType(RHSOPT,0), false)); - + const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType(); const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType(); if (LHS && RHS) { // We have 2 user-defined types. @@ -7979,13 +8010,13 @@ static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs, /// the given common base. /// It is used to build composite qualifier list of the composite type of /// the conditional expression involving two objective-c pointer objects. -static +static void getIntersectionOfProtocols(ASTContext &Context, const ObjCInterfaceDecl *CommonBase, const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT, SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) { - + const ObjCObjectType* LHS = LHSOPT->getObjectType(); const ObjCObjectType* RHS = RHSOPT->getObjectType(); assert(LHS->getInterface() && "LHS must have an interface base"); @@ -8254,7 +8285,7 @@ bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS, // If there is no protocols associated with RHS, it is not a match. if (SuperClassInheritedProtocols.empty()) return false; - + for (const auto *LHSProto : LHS->quals()) { bool SuperImplementsProtocol = false; for (auto *SuperClassProto : SuperClassInheritedProtocols) @@ -8367,7 +8398,7 @@ QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs, return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified); } -QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs, +QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs, bool OfBlockPointer, bool Unqualified) { const auto *lbase = lhs->getAs<FunctionType>(); @@ -8392,7 +8423,7 @@ QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs, Unqualified); if (retType.isNull()) return {}; - + if (Unqualified) retType = retType.getUnqualifiedType(); @@ -8402,7 +8433,7 @@ QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs, LRetType = LRetType.getUnqualifiedType(); RRetType = RRetType.getUnqualifiedType(); } - + if (getCanonicalType(retType) != LRetType) allLTypes = false; if (getCanonicalType(retType) != RRetType) @@ -8491,7 +8522,7 @@ QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs, if (getCanonicalType(paramType) != getCanonicalType(rParamType)) allRTypes = false; } - + if (allLTypes) return lhs; if (allRTypes) return rhs; @@ -8566,7 +8597,7 @@ static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET, return {}; } -QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, +QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer, bool Unqualified, bool BlockReturnType) { // C++ [expr]: If an expression initially has the type "reference to T", the @@ -8581,7 +8612,7 @@ QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, LHS = LHS.getUnqualifiedType(); RHS = RHS.getUnqualifiedType(); } - + QualType LHSCan = getCanonicalType(LHS), RHSCan = getCanonicalType(RHS); @@ -8663,7 +8694,7 @@ QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, if (RHS->isObjCIdType() && LHS->isBlockPointerType()) return RHS; } - + return {}; } @@ -8700,7 +8731,7 @@ QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, LHSPointee = LHSPointee.getUnqualifiedType(); RHSPointee = RHSPointee.getUnqualifiedType(); } - QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false, + QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false, Unqualified); if (ResultType.isNull()) return {}; @@ -8752,7 +8783,7 @@ QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, LHSValue = LHSValue.getUnqualifiedType(); RHSValue = RHSValue.getUnqualifiedType(); } - QualType ResultType = mergeTypes(LHSValue, RHSValue, false, + QualType ResultType = mergeTypes(LHSValue, RHSValue, false, Unqualified); if (ResultType.isNull()) return {}; @@ -8775,7 +8806,7 @@ QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, LHSElem = LHSElem.getUnqualifiedType(); RHSElem = RHSElem.getUnqualifiedType(); } - + QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified); if (ResultType.isNull()) return {}; @@ -8958,7 +8989,7 @@ QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) { cast<FunctionType>(RHSCan.getTypePtr())->getReturnType(); QualType NewReturnType = cast<FunctionType>(LHSCan.getTypePtr())->getReturnType(); - QualType ResReturnType = + QualType ResReturnType = mergeObjCGCQualifiers(NewReturnType, OldReturnType); if (ResReturnType.isNull()) return {}; @@ -8976,7 +9007,7 @@ QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) { } return {}; } - + // If the qualifiers are different, the types can still be merged. Qualifiers LQuals = LHSCan.getLocalQualifiers(); Qualifiers RQuals = RHSCan.getLocalQualifiers(); @@ -8985,7 +9016,7 @@ QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) { if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || LQuals.getAddressSpace() != RQuals.getAddressSpace()) return {}; - + // Exactly one GC qualifier difference is allowed: __strong is // okay if the other type has no GC qualifier but is an Objective // C object pointer (i.e. implicitly strong by default). We fix @@ -8994,17 +9025,17 @@ QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) { Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); - + if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) return {}; - + if (GC_L == Qualifiers::Strong) return LHS; if (GC_R == Qualifiers::Strong) return RHS; return {}; } - + if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) { QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType(); QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType(); @@ -9033,7 +9064,7 @@ unsigned ASTContext::getIntWidth(QualType T) const { QualType ASTContext::getCorrespondingUnsignedType(QualType T) const { assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) && "Unexpected type"); - + // Turn <4 x signed int> -> <4 x unsigned int> if (const auto *VTy = T->getAs<VectorType>()) return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()), @@ -9042,7 +9073,7 @@ QualType ASTContext::getCorrespondingUnsignedType(QualType T) const { // For enums, we return the unsigned version of the base type. if (const auto *ETy = T->getAs<EnumType>()) T = ETy->getDecl()->getIntegerType(); - + const auto *BTy = T->getAs<BuiltinType>(); assert(BTy && "Unexpected signed integer or fixed point type"); switch (BTy->getKind()) { @@ -9114,7 +9145,7 @@ static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, int HowLong = 0; bool Signed = false, Unsigned = false; RequiresICE = false; - + // Read the prefixed modifiers first. bool Done = false; #ifndef NDEBUG @@ -9278,10 +9309,10 @@ static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, assert(End != Str && "Missing vector size"); Str = End; - QualType ElementType = DecodeTypeFromStr(Str, Context, Error, + QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, false); assert(!RequiresICE && "Can't require vector ICE"); - + // TODO: No way to make AltiVec vectors in builtins yet. Type = Context.getVectorType(ElementType, NumElements, VectorType::GenericVector); @@ -9289,16 +9320,16 @@ static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, } case 'E': { char *End; - + unsigned NumElements = strtoul(Str, &End, 10); assert(End != Str && "Missing vector size"); - + Str = End; - + QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, false); Type = Context.getExtVectorType(ElementType, NumElements); - break; + break; } case 'X': { QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, @@ -9306,7 +9337,7 @@ static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, assert(!RequiresICE && "Can't require complex ICE"); Type = Context.getComplexType(ElementType); break; - } + } case 'Y': Type = Context.getPointerDiffType(); break; @@ -9376,9 +9407,9 @@ static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, break; } } - + assert((!RequiresICE || Type->isIntegralOrEnumerationType()) && - "Integer constant 'I' type must be an integer"); + "Integer constant 'I' type must be an integer"); return Type; } @@ -9397,9 +9428,9 @@ QualType ASTContext::GetBuiltinType(unsigned Id, RequiresICE, true); if (Error != GE_None) return {}; - + assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE"); - + while (TypeStr[0] && TypeStr[0] != '.') { QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true); if (Error != GE_None) @@ -9409,7 +9440,7 @@ QualType ASTContext::GetBuiltinType(unsigned Id, // caller cares, fill in the bitmask we return. if (RequiresICE && IntegerConstantArgs) *IntegerConstantArgs |= 1 << ArgTypes.size(); - + // Do array -> pointer decay. The builtin should use the decayed type. if (Ty->isArrayType()) Ty = getArrayDecayedType(Ty); @@ -9504,21 +9535,6 @@ static GVALinkage basicGVALinkageForFunction(const ASTContext &Context, return GVA_DiscardableODR; } -static bool isDeclareTargetToDeclaration(const Decl *VD) { - for (const Decl *D : VD->redecls()) { - if (!D->hasAttrs()) - continue; - if (const auto *Attr = D->getAttr<OMPDeclareTargetDeclAttr>()) - return Attr->getMapType() == OMPDeclareTargetDeclAttr::MT_To; - } - if (const auto *V = dyn_cast<VarDecl>(VD)) { - if (const VarDecl *TD = V->getTemplateInstantiationPattern()) - return isDeclareTargetToDeclaration(TD); - } - - return false; -} - static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context, const Decl *D, GVALinkage L) { // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx @@ -9535,12 +9551,6 @@ static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context, // visible externally so they can be launched from host. if (L == GVA_DiscardableODR || L == GVA_Internal) return GVA_StrongODR; - } else if (Context.getLangOpts().OpenMP && Context.getLangOpts().OpenMPIsDevice && - isDeclareTargetToDeclaration(D)) { - // Static variables must be visible externally so they can be mapped from - // host. - if (L == GVA_Internal) - return GVA_StrongODR; } return L; } @@ -10006,7 +10016,7 @@ void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) { unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const { ParameterIndexTable::const_iterator I = ParamIndices.find(D); - assert(I != ParamIndices.end() && + assert(I != ParamIndices.end() && "ParmIndices lacks entry set by ParmVarDecl"); return I->second; } @@ -10240,10 +10250,10 @@ ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl, return false; if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType())) return false; - + if (MethodDecl->param_size() != MethodImpl->param_size()) return false; - + for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(), IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(), EF = MethodDecl->param_end(); diff --git a/lib/AST/ASTDiagnostic.cpp b/lib/AST/ASTDiagnostic.cpp index c4c0f6e5ebe3..50d2d2999e51 100644 --- a/lib/AST/ASTDiagnostic.cpp +++ b/lib/AST/ASTDiagnostic.cpp @@ -200,7 +200,7 @@ break; \ return QC.apply(Context, QT); } -/// Convert the given type to a string suitable for printing as part of +/// Convert the given type to a string suitable for printing as part of /// a diagnostic. /// /// There are four main criteria when determining whether we should have an @@ -254,7 +254,7 @@ ConvertTypeToDiagnosticString(ASTContext &Context, QualType Ty, // and the desugared comparison string. std::string CompareCanS = CompareCanTy.getAsString(Context.getPrintingPolicy()); - + if (CompareCanS == CanS) continue; // No new info from canonical type @@ -327,11 +327,11 @@ void clang::FormatASTNodeDiagnosticArgument( void *Cookie, ArrayRef<intptr_t> QualTypeVals) { ASTContext &Context = *static_cast<ASTContext*>(Cookie); - + size_t OldEnd = Output.size(); llvm::raw_svector_ostream OS(Output); bool NeedQuotes = true; - + switch (Kind) { default: llvm_unreachable("unknown ArgumentKind"); case DiagnosticsEngine::ak_qualtype_pair: { @@ -365,7 +365,7 @@ void clang::FormatASTNodeDiagnosticArgument( case DiagnosticsEngine::ak_qualtype: { assert(Modifier.empty() && Argument.empty() && "Invalid modifier for QualType argument"); - + QualType Ty(QualType::getFromOpaquePtr(reinterpret_cast<void*>(Val))); OS << ConvertTypeToDiagnosticString(Context, Ty, PrevArgs, QualTypeVals); NeedQuotes = false; @@ -2040,7 +2040,7 @@ public: /// is successful. static bool FormatTemplateTypeDiff(ASTContext &Context, QualType FromType, QualType ToType, bool PrintTree, - bool PrintFromType, bool ElideType, + bool PrintFromType, bool ElideType, bool ShowColors, raw_ostream &OS) { if (PrintTree) PrintFromType = true; diff --git a/lib/AST/ASTDumper.cpp b/lib/AST/ASTDumper.cpp index f46ae58d192d..8a653ecebae3 100644 --- a/lib/AST/ASTDumper.cpp +++ b/lib/AST/ASTDumper.cpp @@ -1966,7 +1966,7 @@ void ASTDumper::dumpStmt(const Stmt *S) { } void ASTDumper::VisitStmt(const Stmt *Node) { - { + { ColorScope Color(*this, StmtColor); OS << Node->getStmtClassName(); } diff --git a/lib/AST/ASTImporter.cpp b/lib/AST/ASTImporter.cpp index 6668067233e4..b360b3910636 100644 --- a/lib/AST/ASTImporter.cpp +++ b/lib/AST/ASTImporter.cpp @@ -221,8 +221,8 @@ namespace clang { QualType VisitObjCObjectPointerType(const ObjCObjectPointerType *T); // Importing declarations - bool ImportDeclParts(NamedDecl *D, DeclContext *&DC, - DeclContext *&LexicalDC, DeclarationName &Name, + bool ImportDeclParts(NamedDecl *D, DeclContext *&DC, + DeclContext *&LexicalDC, DeclarationName &Name, NamedDecl *&ToD, SourceLocation &Loc); void ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD = nullptr); void ImportDeclarationNameLoc(const DeclarationNameInfo &From, @@ -237,9 +237,9 @@ namespace clang { Designator ImportDesignator(const Designator &D); Optional<LambdaCapture> ImportLambdaCapture(const LambdaCapture &From); - + /// What we should import from the definition. - enum ImportDefinitionKind { + enum ImportDefinitionKind { /// Import the default subset of the definition, which might be /// nothing (if minimal import is set) or might be everything (if minimal /// import is not set). @@ -258,7 +258,7 @@ namespace clang { (IDK == IDK_Default && !Importer.isMinimalImport()); } - bool ImportDefinition(RecordDecl *From, RecordDecl *To, + bool ImportDefinition(RecordDecl *From, RecordDecl *To, ImportDefinitionKind Kind = IDK_Default); bool ImportDefinition(VarDecl *From, VarDecl *To, ImportDefinitionKind Kind = IDK_Default); @@ -600,21 +600,21 @@ QualType ASTNodeImporter::VisitBuiltinType(const BuiltinType *T) { // context supports ObjC. case BuiltinType::Char_U: - // The context we're importing from has an unsigned 'char'. If we're - // importing into a context with a signed 'char', translate to + // The context we're importing from has an unsigned 'char'. If we're + // importing into a context with a signed 'char', translate to // 'unsigned char' instead. if (Importer.getToContext().getLangOpts().CharIsSigned) return Importer.getToContext().UnsignedCharTy; - + return Importer.getToContext().CharTy; case BuiltinType::Char_S: - // The context we're importing from has an unsigned 'char'. If we're - // importing into a context with a signed 'char', translate to + // The context we're importing from has an unsigned 'char'. If we're + // importing into a context with a signed 'char', translate to // 'unsigned char' instead. if (!Importer.getToContext().getLangOpts().CharIsSigned) return Importer.getToContext().SignedCharTy; - + return Importer.getToContext().CharTy; case BuiltinType::WChar_S: @@ -639,7 +639,7 @@ QualType ASTNodeImporter::VisitComplexType(const ComplexType *T) { QualType ToElementType = Importer.Import(T->getElementType()); if (ToElementType.isNull()) return {}; - + return Importer.getToContext().getComplexType(ToElementType); } @@ -647,7 +647,7 @@ QualType ASTNodeImporter::VisitPointerType(const PointerType *T) { QualType ToPointeeType = Importer.Import(T->getPointeeType()); if (ToPointeeType.isNull()) return {}; - + return Importer.getToContext().getPointerType(ToPointeeType); } @@ -656,7 +656,7 @@ QualType ASTNodeImporter::VisitBlockPointerType(const BlockPointerType *T) { QualType ToPointeeType = Importer.Import(T->getPointeeType()); if (ToPointeeType.isNull()) return {}; - + return Importer.getToContext().getBlockPointerType(ToPointeeType); } @@ -666,7 +666,7 @@ ASTNodeImporter::VisitLValueReferenceType(const LValueReferenceType *T) { QualType ToPointeeType = Importer.Import(T->getPointeeTypeAsWritten()); if (ToPointeeType.isNull()) return {}; - + return Importer.getToContext().getLValueReferenceType(ToPointeeType); } @@ -676,8 +676,8 @@ ASTNodeImporter::VisitRValueReferenceType(const RValueReferenceType *T) { QualType ToPointeeType = Importer.Import(T->getPointeeTypeAsWritten()); if (ToPointeeType.isNull()) return {}; - - return Importer.getToContext().getRValueReferenceType(ToPointeeType); + + return Importer.getToContext().getRValueReferenceType(ToPointeeType); } QualType ASTNodeImporter::VisitMemberPointerType(const MemberPointerType *T) { @@ -685,9 +685,9 @@ QualType ASTNodeImporter::VisitMemberPointerType(const MemberPointerType *T) { QualType ToPointeeType = Importer.Import(T->getPointeeType()); if (ToPointeeType.isNull()) return {}; - + QualType ClassType = Importer.Import(QualType(T->getClass(), 0)); - return Importer.getToContext().getMemberPointerType(ToPointeeType, + return Importer.getToContext().getMemberPointerType(ToPointeeType, ClassType.getTypePtr()); } @@ -695,8 +695,8 @@ QualType ASTNodeImporter::VisitConstantArrayType(const ConstantArrayType *T) { QualType ToElementType = Importer.Import(T->getElementType()); if (ToElementType.isNull()) return {}; - - return Importer.getToContext().getConstantArrayType(ToElementType, + + return Importer.getToContext().getConstantArrayType(ToElementType, T->getSize(), T->getSizeModifier(), T->getIndexTypeCVRQualifiers()); @@ -707,8 +707,8 @@ ASTNodeImporter::VisitIncompleteArrayType(const IncompleteArrayType *T) { QualType ToElementType = Importer.Import(T->getElementType()); if (ToElementType.isNull()) return {}; - - return Importer.getToContext().getIncompleteArrayType(ToElementType, + + return Importer.getToContext().getIncompleteArrayType(ToElementType, T->getSizeModifier(), T->getIndexTypeCVRQualifiers()); } @@ -721,7 +721,7 @@ QualType ASTNodeImporter::VisitVariableArrayType(const VariableArrayType *T) { Expr *Size = Importer.Import(T->getSizeExpr()); if (!Size) return {}; - + SourceRange Brackets = Importer.Import(T->getBracketsRange()); return Importer.getToContext().getVariableArrayType(ToElementType, Size, T->getSizeModifier(), @@ -751,8 +751,8 @@ QualType ASTNodeImporter::VisitVectorType(const VectorType *T) { QualType ToElementType = Importer.Import(T->getElementType()); if (ToElementType.isNull()) return {}; - - return Importer.getToContext().getVectorType(ToElementType, + + return Importer.getToContext().getVectorType(ToElementType, T->getNumElements(), T->getVectorKind()); } @@ -761,14 +761,14 @@ QualType ASTNodeImporter::VisitExtVectorType(const ExtVectorType *T) { QualType ToElementType = Importer.Import(T->getElementType()); if (ToElementType.isNull()) return {}; - - return Importer.getToContext().getExtVectorType(ToElementType, + + return Importer.getToContext().getExtVectorType(ToElementType, T->getNumElements()); } QualType ASTNodeImporter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) { - // FIXME: What happens if we're importing a function without a prototype + // FIXME: What happens if we're importing a function without a prototype // into C++? Should we make it variadic? QualType ToResultType = Importer.Import(T->getReturnType()); if (ToResultType.isNull()) @@ -782,7 +782,7 @@ QualType ASTNodeImporter::VisitFunctionProtoType(const FunctionProtoType *T) { QualType ToResultType = Importer.Import(T->getReturnType()); if (ToResultType.isNull()) return {}; - + // Import argument types SmallVector<QualType, 4> ArgTypes; for (const auto &A : T->param_types()) { @@ -791,7 +791,7 @@ QualType ASTNodeImporter::VisitFunctionProtoType(const FunctionProtoType *T) { return {}; ArgTypes.push_back(ArgType); } - + // Import exception types SmallVector<QualType, 4> ExceptionTypes; for (const auto &E : T->exceptions()) { @@ -841,7 +841,7 @@ QualType ASTNodeImporter::VisitParenType(const ParenType *T) { QualType ToInnerType = Importer.Import(T->getInnerType()); if (ToInnerType.isNull()) return {}; - + return Importer.getToContext().getParenType(ToInnerType); } @@ -850,7 +850,7 @@ QualType ASTNodeImporter::VisitTypedefType(const TypedefType *T) { dyn_cast_or_null<TypedefNameDecl>(Importer.Import(T->getDecl())); if (!ToDecl) return {}; - + return Importer.getToContext().getTypeDeclType(ToDecl); } @@ -858,7 +858,7 @@ QualType ASTNodeImporter::VisitTypeOfExprType(const TypeOfExprType *T) { Expr *ToExpr = Importer.Import(T->getUnderlyingExpr()); if (!ToExpr) return {}; - + return Importer.getToContext().getTypeOfExprType(ToExpr); } @@ -866,7 +866,7 @@ QualType ASTNodeImporter::VisitTypeOfType(const TypeOfType *T) { QualType ToUnderlyingType = Importer.Import(T->getUnderlyingType()); if (ToUnderlyingType.isNull()) return {}; - + return Importer.getToContext().getTypeOfType(ToUnderlyingType); } @@ -875,7 +875,7 @@ QualType ASTNodeImporter::VisitDecltypeType(const DecltypeType *T) { Expr *ToExpr = Importer.Import(T->getUnderlyingExpr()); if (!ToExpr) return {}; - + QualType UnderlyingType = Importer.Import(T->getUnderlyingType()); if (UnderlyingType.isNull()) return {}; @@ -903,7 +903,7 @@ QualType ASTNodeImporter::VisitAutoType(const AutoType *T) { if (ToDeduced.isNull()) return {}; } - + return Importer.getToContext().getAutoType(ToDeduced, T->getKeyword(), /*IsDependent*/false); } @@ -1000,20 +1000,20 @@ QualType ASTNodeImporter::VisitTemplateSpecializationType( TemplateName ToTemplate = Importer.Import(T->getTemplateName()); if (ToTemplate.isNull()) return {}; - + SmallVector<TemplateArgument, 2> ToTemplateArgs; if (ImportTemplateArguments(T->getArgs(), T->getNumArgs(), ToTemplateArgs)) return {}; - + QualType ToCanonType; if (!QualType(T, 0).isCanonical()) { - QualType FromCanonType + QualType FromCanonType = Importer.getFromContext().getCanonicalType(QualType(T, 0)); ToCanonType =Importer.Import(FromCanonType); if (ToCanonType.isNull()) return {}; } - return Importer.getToContext().getTemplateSpecializationType(ToTemplate, + return Importer.getToContext().getTemplateSpecializationType(ToTemplate, ToTemplateArgs, ToCanonType); } @@ -1136,9 +1136,9 @@ ASTNodeImporter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) { //---------------------------------------------------------------------------- // Import Declarations //---------------------------------------------------------------------------- -bool ASTNodeImporter::ImportDeclParts(NamedDecl *D, DeclContext *&DC, - DeclContext *&LexicalDC, - DeclarationName &Name, +bool ASTNodeImporter::ImportDeclParts(NamedDecl *D, DeclContext *&DC, + DeclContext *&LexicalDC, + DeclarationName &Name, NamedDecl *&ToD, SourceLocation &Loc) { // Check if RecordDecl is in FunctionDecl parameters to avoid infinite loop. @@ -1163,19 +1163,19 @@ bool ASTNodeImporter::ImportDeclParts(NamedDecl *D, DeclContext *&DC, DC = Importer.ImportContext(OrigDC); if (!DC) return true; - + LexicalDC = DC; if (D->getDeclContext() != D->getLexicalDeclContext()) { LexicalDC = Importer.ImportContext(D->getLexicalDeclContext()); if (!LexicalDC) return true; } - + // Import the name of this declaration. Name = Importer.Import(D->getDeclName()); if (D->getDeclName() && !Name) return true; - + // Import the location of this declaration. Loc = Importer.Import(D->getLocation()); ToD = cast_or_null<NamedDecl>(Importer.GetAlreadyImportedOrNull(D)); @@ -1185,13 +1185,13 @@ bool ASTNodeImporter::ImportDeclParts(NamedDecl *D, DeclContext *&DC, void ASTNodeImporter::ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD) { if (!FromD) return; - + if (!ToD) { ToD = Importer.Import(FromD); if (!ToD) return; } - + if (auto *FromRecord = dyn_cast<RecordDecl>(FromD)) { if (auto *ToRecord = cast_or_null<RecordDecl>(ToD)) { if (FromRecord->getDefinition() && FromRecord->isCompleteDefinition() && !ToRecord->getDefinition()) { @@ -1246,12 +1246,12 @@ ASTNodeImporter::ImportDeclarationNameLoc(const DeclarationNameInfo &From, llvm_unreachable("Unknown name kind."); } -void ASTNodeImporter::ImportDeclContext(DeclContext *FromDC, bool ForceImport) { +void ASTNodeImporter::ImportDeclContext(DeclContext *FromDC, bool ForceImport) { if (Importer.isMinimalImport() && !ForceImport) { Importer.ImportContext(FromDC); return; } - + for (auto *From : FromDC->decls()) Importer.Import(From); } @@ -1260,7 +1260,7 @@ void ASTNodeImporter::ImportImplicitMethods( const CXXRecordDecl *From, CXXRecordDecl *To) { assert(From->isCompleteDefinition() && To->getDefinition() == To && "Import implicit methods to or from non-definition"); - + for (CXXMethodDecl *FromM : From->methods()) if (FromM->isImplicit()) Importer.Import(FromM); @@ -1277,19 +1277,19 @@ static void setTypedefNameForAnonDecl(TagDecl *From, TagDecl *To, } } -bool ASTNodeImporter::ImportDefinition(RecordDecl *From, RecordDecl *To, +bool ASTNodeImporter::ImportDefinition(RecordDecl *From, RecordDecl *To, ImportDefinitionKind Kind) { if (To->getDefinition() || To->isBeingDefined()) { if (Kind == IDK_Everything) ImportDeclContext(From, /*ForceImport=*/true); - + return false; } - + To->startDefinition(); setTypedefNameForAnonDecl(From, To, Importer); - + // Add base classes. if (auto *ToCXX = dyn_cast<CXXRecordDecl>(To)) { auto *FromCXX = cast<CXXRecordDecl>(From); @@ -1374,9 +1374,9 @@ bool ASTNodeImporter::ImportDefinition(RecordDecl *From, RecordDecl *To, // Ensure that we have a definition for the base. ImportDefinitionIfNeeded(Base1.getType()->getAsCXXRecordDecl()); - + Bases.push_back( - new (Importer.getToContext()) + new (Importer.getToContext()) CXXBaseSpecifier(Importer.Import(Base1.getSourceRange()), Base1.isVirtual(), Base1.isBaseOfClass(), @@ -1387,10 +1387,10 @@ bool ASTNodeImporter::ImportDefinition(RecordDecl *From, RecordDecl *To, if (!Bases.empty()) ToCXX->setBases(Bases.data(), Bases.size()); } - + if (shouldForceImportDeclContext(Kind)) ImportDeclContext(From, /*ForceImport=*/true); - + To->completeDefinition(); return false; } @@ -1410,14 +1410,14 @@ bool ASTNodeImporter::ImportDefinition(VarDecl *From, VarDecl *To, return false; } -bool ASTNodeImporter::ImportDefinition(EnumDecl *From, EnumDecl *To, +bool ASTNodeImporter::ImportDefinition(EnumDecl *From, EnumDecl *To, ImportDefinitionKind Kind) { if (To->getDefinition() || To->isBeingDefined()) { if (Kind == IDK_Everything) ImportDeclContext(From, /*ForceImport=*/true); return false; } - + To->startDefinition(); setTypedefNameForAnonDecl(From, To, Importer); @@ -1425,14 +1425,14 @@ bool ASTNodeImporter::ImportDefinition(EnumDecl *From, EnumDecl *To, QualType T = Importer.Import(Importer.getFromContext().getTypeDeclType(From)); if (T.isNull()) return true; - + QualType ToPromotionType = Importer.Import(From->getPromotionType()); if (ToPromotionType.isNull()) return true; if (shouldForceImportDeclContext(Kind)) ImportDeclContext(From, /*ForceImport=*/true); - + // FIXME: we might need to merge the number of positive or negative bits // if the enumerator lists don't match. To->completeDefinition(T, ToPromotionType, @@ -1446,7 +1446,7 @@ TemplateParameterList *ASTNodeImporter::ImportTemplateParameterList( SmallVector<NamedDecl *, 4> ToParams(Params->size()); if (ImportContainerChecked(*Params, ToParams)) return nullptr; - + Expr *ToRequiresClause; if (Expr *const R = Params->getRequiresClause()) { ToRequiresClause = Importer.Import(R); @@ -1464,19 +1464,19 @@ TemplateParameterList *ASTNodeImporter::ImportTemplateParameterList( ToRequiresClause); } -TemplateArgument +TemplateArgument ASTNodeImporter::ImportTemplateArgument(const TemplateArgument &From) { switch (From.getKind()) { case TemplateArgument::Null: return TemplateArgument(); - + case TemplateArgument::Type: { QualType ToType = Importer.Import(From.getAsType()); if (ToType.isNull()) return {}; return TemplateArgument(ToType); } - + case TemplateArgument::Integral: { QualType ToType = Importer.Import(From.getIntegralType()); if (ToType.isNull()) @@ -1503,16 +1503,16 @@ ASTNodeImporter::ImportTemplateArgument(const TemplateArgument &From) { TemplateName ToTemplate = Importer.Import(From.getAsTemplate()); if (ToTemplate.isNull()) return {}; - + return TemplateArgument(ToTemplate); } case TemplateArgument::TemplateExpansion: { - TemplateName ToTemplate + TemplateName ToTemplate = Importer.Import(From.getAsTemplateOrTemplatePattern()); if (ToTemplate.isNull()) return {}; - + return TemplateArgument(ToTemplate, From.getNumTemplateExpansions()); } @@ -1520,7 +1520,7 @@ ASTNodeImporter::ImportTemplateArgument(const TemplateArgument &From) { if (Expr *ToExpr = Importer.Import(From.getAsExpr())) return TemplateArgument(ToExpr); return TemplateArgument(); - + case TemplateArgument::Pack: { SmallVector<TemplateArgument, 2> ToPack; ToPack.reserve(From.pack_size()); @@ -1531,7 +1531,7 @@ ASTNodeImporter::ImportTemplateArgument(const TemplateArgument &From) { llvm::makeArrayRef(ToPack).copy(Importer.getToContext())); } } - + llvm_unreachable("Invalid template argument kind"); } @@ -1566,10 +1566,10 @@ bool ASTNodeImporter::ImportTemplateArguments(const TemplateArgument *FromArgs, TemplateArgument To = ImportTemplateArgument(FromArgs[I]); if (To.isNull() && !FromArgs[I].isNull()) return true; - + ToArgs.push_back(To); } - + return false; } @@ -1714,11 +1714,11 @@ Decl *ASTNodeImporter::VisitEmptyDecl(EmptyDecl *D) { } Decl *ASTNodeImporter::VisitTranslationUnitDecl(TranslationUnitDecl *D) { - TranslationUnitDecl *ToD = + TranslationUnitDecl *ToD = Importer.getToContext().getTranslationUnitDecl(); - + Importer.MapImported(D, ToD); - + return ToD; } @@ -1801,23 +1801,23 @@ Decl *ASTNodeImporter::VisitNamespaceDecl(NamespaceDecl *D) { for (auto *FoundDecl : FoundDecls) { if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Namespace)) continue; - + if (auto *FoundNS = dyn_cast<NamespaceDecl>(FoundDecl)) { MergeWithNamespace = FoundNS; ConflictingDecls.clear(); break; } - + ConflictingDecls.push_back(FoundDecl); } - + if (!ConflictingDecls.empty()) { Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Namespace, - ConflictingDecls.data(), + ConflictingDecls.data(), ConflictingDecls.size()); } } - + // Create the "to" namespace, if needed. NamespaceDecl *ToNamespace = MergeWithNamespace; if (!ToNamespace) { @@ -1828,7 +1828,7 @@ Decl *ASTNodeImporter::VisitNamespaceDecl(NamespaceDecl *D) { return ToNamespace; ToNamespace->setLexicalDeclContext(LexicalDC); LexicalDC->addDeclInternal(ToNamespace); - + // If this is an anonymous namespace, register it as the anonymous // namespace within its context. if (!Name) { @@ -1839,9 +1839,9 @@ Decl *ASTNodeImporter::VisitNamespaceDecl(NamespaceDecl *D) { } } Importer.MapImported(D, ToNamespace); - + ImportDeclContext(D); - + return ToNamespace; } @@ -1918,7 +1918,7 @@ Decl *ASTNodeImporter::VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias) { if (!ConflictingDecls.empty()) { Name = Importer.HandleNameConflict(Name, DC, IDNS, - ConflictingDecls.data(), + ConflictingDecls.data(), ConflictingDecls.size()); if (!Name) return nullptr; @@ -2076,7 +2076,7 @@ Decl *ASTNodeImporter::VisitEnumDecl(EnumDecl *D) { IDNS = Decl::IDNS_Ordinary; } else if (Importer.getToContext().getLangOpts().CPlusPlus) IDNS |= Decl::IDNS_Ordinary; - + // We may already have an enum of the same name; try to find and match it. if (!DC->isFunctionOrMethod() && SearchName) { SmallVector<NamedDecl *, 4> ConflictingDecls; @@ -2085,24 +2085,24 @@ Decl *ASTNodeImporter::VisitEnumDecl(EnumDecl *D) { for (auto *FoundDecl : FoundDecls) { if (!FoundDecl->isInIdentifierNamespace(IDNS)) continue; - + Decl *Found = FoundDecl; if (auto *Typedef = dyn_cast<TypedefNameDecl>(Found)) { if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>()) Found = Tag->getDecl(); } - + if (auto *FoundEnum = dyn_cast<EnumDecl>(Found)) { if (IsStructuralMatch(D, FoundEnum)) return Importer.MapImported(D, FoundEnum); } - + ConflictingDecls.push_back(FoundDecl); } - + if (!ConflictingDecls.empty()) { Name = Importer.HandleNameConflict(Name, DC, IDNS, - ConflictingDecls.data(), + ConflictingDecls.data(), ConflictingDecls.size()); } } @@ -2126,7 +2126,7 @@ Decl *ASTNodeImporter::VisitEnumDecl(EnumDecl *D) { if (ToIntegerType.isNull()) return nullptr; D2->setIntegerType(ToIntegerType); - + // Import the definition if (D->isCompleteDefinition() && ImportDefinition(D, D2)) return nullptr; @@ -2189,7 +2189,7 @@ Decl *ASTNodeImporter::VisitRecordDecl(RecordDecl *D) { for (auto *FoundDecl : FoundDecls) { if (!FoundDecl->isInIdentifierNamespace(IDNS)) continue; - + Decl *Found = FoundDecl; if (auto *Typedef = dyn_cast<TypedefNameDecl>(Found)) { if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>()) @@ -2237,38 +2237,38 @@ Decl *ASTNodeImporter::VisitRecordDecl(RecordDecl *D) { } else if (!D->isCompleteDefinition()) { // We have a forward declaration of this type, so adopt that forward // declaration rather than building a new one. - + // If one or both can be completed from external storage then try one // last time to complete and compare them before doing this. - + if (FoundRecord->hasExternalLexicalStorage() && !FoundRecord->isCompleteDefinition()) FoundRecord->getASTContext().getExternalSource()->CompleteType(FoundRecord); if (D->hasExternalLexicalStorage()) D->getASTContext().getExternalSource()->CompleteType(D); - + if (FoundRecord->isCompleteDefinition() && D->isCompleteDefinition() && !IsStructuralMatch(D, FoundRecord)) continue; - + AdoptDecl = FoundRecord; continue; } else if (!SearchName) { continue; } } - + ConflictingDecls.push_back(FoundDecl); } - + if (!ConflictingDecls.empty() && SearchName) { Name = Importer.HandleNameConflict(Name, DC, IDNS, - ConflictingDecls.data(), + ConflictingDecls.data(), ConflictingDecls.size()); } } - + // Create the record declaration. RecordDecl *D2 = AdoptDecl; SourceLocation StartLoc = Importer.Import(D->getLocStart()); @@ -2392,7 +2392,7 @@ Decl *ASTNodeImporter::VisitEnumConstantDecl(EnumConstantDecl *D) { if (T.isNull()) return nullptr; - // Determine whether there are any other declarations with the same name and + // Determine whether there are any other declarations with the same name and // in the same context. if (!LexicalDC->isFunctionOrMethod()) { SmallVector<NamedDecl *, 4> ConflictingDecls; @@ -2410,16 +2410,16 @@ Decl *ASTNodeImporter::VisitEnumConstantDecl(EnumConstantDecl *D) { ConflictingDecls.push_back(FoundDecl); } - + if (!ConflictingDecls.empty()) { Name = Importer.HandleNameConflict(Name, DC, IDNS, - ConflictingDecls.data(), + ConflictingDecls.data(), ConflictingDecls.size()); if (!Name) return nullptr; } } - + Expr *Init = Importer.Import(D->getInitExpr()); if (D->getInitExpr() && !Init) return nullptr; @@ -2608,7 +2608,7 @@ Decl *ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) { // Complain about inconsistent function types. Importer.ToDiag(Loc, diag::err_odr_function_type_inconsistent) << Name << D->getType() << FoundFunction->getType(); - Importer.ToDiag(FoundFunction->getLocation(), + Importer.ToDiag(FoundFunction->getLocation(), diag::note_odr_value_here) << FoundFunction->getType(); } @@ -2619,11 +2619,11 @@ Decl *ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) { if (!ConflictingDecls.empty()) { Name = Importer.HandleNameConflict(Name, DC, IDNS, - ConflictingDecls.data(), + ConflictingDecls.data(), ConflictingDecls.size()); if (!Name) return nullptr; - } + } } DeclarationNameInfo NameInfo(Name, Loc); @@ -2663,7 +2663,7 @@ Decl *ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) { Parameters.push_back(ToP); } - + TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo()); if (D->getTypeSourceInfo() && !TInfo) return nullptr; @@ -2851,7 +2851,7 @@ Decl *ASTNodeImporter::VisitFieldDecl(FieldDecl *D) { if (ToD) return ToD; - // Determine whether we've already imported this field. + // Determine whether we've already imported this field. SmallVector<NamedDecl *, 2> FoundDecls; DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls); for (auto *FoundDecl : FoundDecls) { @@ -2916,7 +2916,7 @@ Decl *ASTNodeImporter::VisitIndirectFieldDecl(IndirectFieldDecl *D) { if (ToD) return ToD; - // Determine whether we've already imported this field. + // Determine whether we've already imported this field. SmallVector<NamedDecl *, 2> FoundDecls; DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls); for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) { @@ -3153,7 +3153,7 @@ Decl *ASTNodeImporter::VisitVarDecl(VarDecl *D) { << FoundVar->getType(); } } - + ConflictingDecls.push_back(FoundDecl); } @@ -3165,7 +3165,7 @@ Decl *ASTNodeImporter::VisitVarDecl(VarDecl *D) { if (VarDecl *DDef = D->getDefinition()) { if (VarDecl *ExistingDef = MergeWithVar->getDefinition()) { - Importer.ToDiag(ExistingDef->getLocation(), + Importer.ToDiag(ExistingDef->getLocation(), diag::err_odr_variable_multiple_def) << Name; Importer.FromDiag(DDef->getLocation(), diag::note_odr_defined_here); @@ -3179,19 +3179,19 @@ Decl *ASTNodeImporter::VisitVarDecl(VarDecl *D) { } } } - + return MergeWithVar; } - + if (!ConflictingDecls.empty()) { Name = Importer.HandleNameConflict(Name, DC, IDNS, - ConflictingDecls.data(), + ConflictingDecls.data(), ConflictingDecls.size()); if (!Name) return nullptr; } } - + // Import the type. QualType T = Importer.Import(D->getType()); if (T.isNull()) @@ -3228,7 +3228,7 @@ Decl *ASTNodeImporter::VisitImplicitParamDecl(ImplicitParamDecl *D) { // Parameters are created in the translation unit's context, then moved // into the function declaration's context afterward. DeclContext *DC = Importer.getToContext().getTranslationUnitDecl(); - + // Import the name of this declaration. DeclarationName Name = Importer.Import(D->getDeclName()); if (D->getDeclName() && !Name) @@ -3236,7 +3236,7 @@ Decl *ASTNodeImporter::VisitImplicitParamDecl(ImplicitParamDecl *D) { // Import the location of this declaration. SourceLocation Loc = Importer.Import(D->getLocation()); - + // Import the parameter's type. QualType T = Importer.Import(D->getType()); if (T.isNull()) @@ -3255,7 +3255,7 @@ Decl *ASTNodeImporter::VisitParmVarDecl(ParmVarDecl *D) { // Parameters are created in the translation unit's context, then moved // into the function declaration's context afterward. DeclContext *DC = Importer.getToContext().getTranslationUnitDecl(); - + // Import the name of this declaration. DeclarationName Name = Importer.Import(D->getDeclName()); if (D->getDeclName() && !Name) @@ -3263,7 +3263,7 @@ Decl *ASTNodeImporter::VisitParmVarDecl(ParmVarDecl *D) { // Import the location of this declaration. SourceLocation Loc = Importer.Import(D->getLocation()); - + // Import the parameter's type. QualType T = Importer.Import(D->getType()); if (T.isNull()) @@ -3334,7 +3334,7 @@ Decl *ASTNodeImporter::VisitObjCMethodDecl(ObjCMethodDecl *D) { Importer.ToDiag(Loc, diag::err_odr_objc_method_result_type_inconsistent) << D->isInstanceMethod() << Name << D->getReturnType() << FoundMethod->getReturnType(); - Importer.ToDiag(FoundMethod->getLocation(), + Importer.ToDiag(FoundMethod->getLocation(), diag::note_odr_objc_method_here) << D->isInstanceMethod() << Name; return nullptr; @@ -3345,7 +3345,7 @@ Decl *ASTNodeImporter::VisitObjCMethodDecl(ObjCMethodDecl *D) { Importer.ToDiag(Loc, diag::err_odr_objc_method_num_params_inconsistent) << D->isInstanceMethod() << Name << D->param_size() << FoundMethod->param_size(); - Importer.ToDiag(FoundMethod->getLocation(), + Importer.ToDiag(FoundMethod->getLocation(), diag::note_odr_objc_method_here) << D->isInstanceMethod() << Name; return nullptr; @@ -3372,7 +3372,7 @@ Decl *ASTNodeImporter::VisitObjCMethodDecl(ObjCMethodDecl *D) { if (D->isVariadic() != FoundMethod->isVariadic()) { Importer.ToDiag(Loc, diag::err_odr_objc_method_variadic_inconsistent) << D->isInstanceMethod() << Name; - Importer.ToDiag(FoundMethod->getLocation(), + Importer.ToDiag(FoundMethod->getLocation(), diag::note_odr_objc_method_here) << D->isInstanceMethod() << Name; return nullptr; @@ -3411,7 +3411,7 @@ Decl *ASTNodeImporter::VisitObjCMethodDecl(ObjCMethodDecl *D) { ToParams.push_back(ToP); } - + // Set the parameters. for (auto *ToParam : ToParams) { ToParam->setOwningFunction(ToMethod); @@ -3494,7 +3494,7 @@ Decl *ASTNodeImporter::VisitObjCCategoryDecl(ObjCCategoryDecl *D) { // loops when bringing in their DeclContext. ToCategory->setTypeParamList(ImportObjCTypeParamList( D->getTypeParamList())); - + // Import protocols SmallVector<ObjCProtocolDecl *, 4> Protocols; SmallVector<SourceLocation, 4> ProtocolLocs; @@ -3511,17 +3511,17 @@ Decl *ASTNodeImporter::VisitObjCCategoryDecl(ObjCCategoryDecl *D) { Protocols.push_back(ToProto); ProtocolLocs.push_back(Importer.Import(*FromProtoLoc)); } - + // FIXME: If we're merging, make sure that the protocol list is the same. ToCategory->setProtocolList(Protocols.data(), Protocols.size(), ProtocolLocs.data(), Importer.getToContext()); } else { Importer.MapImported(D, ToCategory); } - + // Import all of the members of this category. ImportDeclContext(D); - + // If we have an implementation, import it as well. if (D->getImplementation()) { auto *Impl = @@ -3532,11 +3532,11 @@ Decl *ASTNodeImporter::VisitObjCCategoryDecl(ObjCCategoryDecl *D) { ToCategory->setImplementation(Impl); } - + return ToCategory; } -bool ASTNodeImporter::ImportDefinition(ObjCProtocolDecl *From, +bool ASTNodeImporter::ImportDefinition(ObjCProtocolDecl *From, ObjCProtocolDecl *To, ImportDefinitionKind Kind) { if (To->getDefinition()) { @@ -3547,11 +3547,11 @@ bool ASTNodeImporter::ImportDefinition(ObjCProtocolDecl *From, // Start the protocol definition To->startDefinition(); - + // Import protocols SmallVector<ObjCProtocolDecl *, 4> Protocols; SmallVector<SourceLocation, 4> ProtocolLocs; - ObjCProtocolDecl::protocol_loc_iterator + ObjCProtocolDecl::protocol_loc_iterator FromProtoLoc = From->protocol_loc_begin(); for (ObjCProtocolDecl::protocol_iterator FromProto = From->protocol_begin(), FromProtoEnd = From->protocol_end(); @@ -3563,7 +3563,7 @@ bool ASTNodeImporter::ImportDefinition(ObjCProtocolDecl *From, Protocols.push_back(ToProto); ProtocolLocs.push_back(Importer.Import(*FromProtoLoc)); } - + // FIXME: If we're merging, make sure that the protocol list is the same. To->setProtocolList(Protocols.data(), Protocols.size(), ProtocolLocs.data(), Importer.getToContext()); @@ -3576,7 +3576,7 @@ bool ASTNodeImporter::ImportDefinition(ObjCProtocolDecl *From, } Decl *ASTNodeImporter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) { - // If this protocol has a definition in the translation unit we're coming + // If this protocol has a definition in the translation unit we're coming // from, but this particular declaration is not that definition, import the // definition and map to that. ObjCProtocolDecl *Definition = D->getDefinition(); @@ -3604,11 +3604,11 @@ Decl *ASTNodeImporter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) { for (auto *FoundDecl : FoundDecls) { if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_ObjCProtocol)) continue; - + if ((MergeWithProtocol = dyn_cast<ObjCProtocolDecl>(FoundDecl))) break; } - + ObjCProtocolDecl *ToProto = MergeWithProtocol; if (!ToProto) { if (GetImportedOrCreateDecl(ToProto, D, Importer.getToContext(), DC, @@ -3831,7 +3831,7 @@ Decl *ASTNodeImporter::VisitUnresolvedUsingTypenameDecl( return ToUsing; } -bool ASTNodeImporter::ImportDefinition(ObjCInterfaceDecl *From, +bool ASTNodeImporter::ImportDefinition(ObjCInterfaceDecl *From, ObjCInterfaceDecl *To, ImportDefinitionKind Kind) { if (To->getDefinition()) { @@ -3842,36 +3842,36 @@ bool ASTNodeImporter::ImportDefinition(ObjCInterfaceDecl *From, if (!FromSuper) return true; } - - ObjCInterfaceDecl *ToSuper = To->getSuperClass(); + + ObjCInterfaceDecl *ToSuper = To->getSuperClass(); if ((bool)FromSuper != (bool)ToSuper || (FromSuper && !declaresSameEntity(FromSuper, ToSuper))) { - Importer.ToDiag(To->getLocation(), + Importer.ToDiag(To->getLocation(), diag::err_odr_objc_superclass_inconsistent) << To->getDeclName(); if (ToSuper) Importer.ToDiag(To->getSuperClassLoc(), diag::note_odr_objc_superclass) << To->getSuperClass()->getDeclName(); else - Importer.ToDiag(To->getLocation(), + Importer.ToDiag(To->getLocation(), diag::note_odr_objc_missing_superclass); if (From->getSuperClass()) - Importer.FromDiag(From->getSuperClassLoc(), + Importer.FromDiag(From->getSuperClassLoc(), diag::note_odr_objc_superclass) << From->getSuperClass()->getDeclName(); else - Importer.FromDiag(From->getLocation(), - diag::note_odr_objc_missing_superclass); + Importer.FromDiag(From->getLocation(), + diag::note_odr_objc_missing_superclass); } - + if (shouldForceImportDeclContext(Kind)) ImportDeclContext(From); return false; } - + // Start the definition. To->startDefinition(); - + // If this class has a superclass, import it. if (From->getSuperClass()) { TypeSourceInfo *SuperTInfo = Importer.Import(From->getSuperClassTInfo()); @@ -3880,13 +3880,13 @@ bool ASTNodeImporter::ImportDefinition(ObjCInterfaceDecl *From, To->setSuperClass(SuperTInfo); } - + // Import protocols SmallVector<ObjCProtocolDecl *, 4> Protocols; SmallVector<SourceLocation, 4> ProtocolLocs; - ObjCInterfaceDecl::protocol_loc_iterator + ObjCInterfaceDecl::protocol_loc_iterator FromProtoLoc = From->protocol_loc_begin(); - + for (ObjCInterfaceDecl::protocol_iterator FromProto = From->protocol_begin(), FromProtoEnd = From->protocol_end(); FromProto != FromProtoEnd; @@ -3897,23 +3897,23 @@ bool ASTNodeImporter::ImportDefinition(ObjCInterfaceDecl *From, Protocols.push_back(ToProto); ProtocolLocs.push_back(Importer.Import(*FromProtoLoc)); } - + // FIXME: If we're merging, make sure that the protocol list is the same. To->setProtocolList(Protocols.data(), Protocols.size(), ProtocolLocs.data(), Importer.getToContext()); - + // Import categories. When the categories themselves are imported, they'll // hook themselves into this interface. for (auto *Cat : From->known_categories()) Importer.Import(Cat); - + // If we have an @implementation, import it as well. if (From->getImplementation()) { auto *Impl = cast_or_null<ObjCImplementationDecl>( Importer.Import(From->getImplementation())); if (!Impl) return true; - + To->setImplementation(Impl); } @@ -3975,11 +3975,11 @@ Decl *ASTNodeImporter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) { for (auto *FoundDecl : FoundDecls) { if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) continue; - + if ((MergeWithIface = dyn_cast<ObjCInterfaceDecl>(FoundDecl))) break; } - + // Create an interface declaration, if one does not already exist. ObjCInterfaceDecl *ToIface = MergeWithIface; if (!ToIface) { @@ -3997,7 +3997,7 @@ Decl *ASTNodeImporter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) { // loops when bringing in their DeclContext. ToIface->setTypeParamList(ImportObjCTypeParamList( D->getTypeParamListAsWritten())); - + if (D->isThisDeclarationADefinition() && ImportDefinition(D, ToIface)) return nullptr; @@ -4032,11 +4032,11 @@ Decl *ASTNodeImporter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) { ToImpl->setLexicalDeclContext(LexicalDC); } - + LexicalDC->addDeclInternal(ToImpl); Category->setImplementation(ToImpl); } - + Importer.MapImported(D, ToImpl); ImportDeclContext(D); return ToImpl; @@ -4113,7 +4113,7 @@ Decl *ASTNodeImporter::VisitObjCImplementationDecl(ObjCImplementationDecl *D) { return nullptr; } } - + // Import all of the members of this @implementation. ImportDeclContext(D); @@ -4235,10 +4235,10 @@ Decl *ASTNodeImporter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) { // Check that we have the same kind of property implementation (@synthesize // vs. @dynamic). if (D->getPropertyImplementation() != ToImpl->getPropertyImplementation()) { - Importer.ToDiag(ToImpl->getLocation(), + Importer.ToDiag(ToImpl->getLocation(), diag::err_odr_objc_property_impl_kind_inconsistent) - << Property->getDeclName() - << (ToImpl->getPropertyImplementation() + << Property->getDeclName() + << (ToImpl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic); Importer.FromDiag(D->getLocation(), diag::note_odr_objc_property_impl_kind) @@ -4246,25 +4246,25 @@ Decl *ASTNodeImporter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) { << (D->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic); return nullptr; } - - // For @synthesize, check that we have the same + + // For @synthesize, check that we have the same if (D->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize && Ivar != ToImpl->getPropertyIvarDecl()) { - Importer.ToDiag(ToImpl->getPropertyIvarDeclLoc(), + Importer.ToDiag(ToImpl->getPropertyIvarDeclLoc(), diag::err_odr_objc_synthesize_ivar_inconsistent) << Property->getDeclName() << ToImpl->getPropertyIvarDecl()->getDeclName() << Ivar->getDeclName(); - Importer.FromDiag(D->getPropertyIvarDeclLoc(), + Importer.FromDiag(D->getPropertyIvarDeclLoc(), diag::note_odr_objc_synthesize_ivar_here) << D->getPropertyIvarDecl()->getDeclName(); return nullptr; } - + // Merge the existing implementation with the new implementation. Importer.MapImported(D, ToImpl); } - + return ToImpl; } @@ -4272,7 +4272,7 @@ Decl *ASTNodeImporter::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) { // For template arguments, we adopt the translation unit as our declaration // context. This context will be fixed when the actual template declaration // is created. - + // FIXME: Import default argument. TemplateTypeParmDecl *ToD = nullptr; (void)GetImportedOrCreateDecl( @@ -4444,16 +4444,16 @@ Decl *ASTNodeImporter::VisitClassTemplateDecl(ClassTemplateDecl *D) { return D2; ToTemplated->setDescribedClassTemplate(D2); - + D2->setAccess(D->getAccess()); D2->setLexicalDeclContext(LexicalDC); LexicalDC->addDeclInternal(D2); - + if (FromTemplated->isCompleteDefinition() && !ToTemplated->isCompleteDefinition()) { // FIXME: Import definition! } - + return D2; } @@ -4488,14 +4488,14 @@ Decl *ASTNodeImporter::VisitClassTemplateSpecializationDecl( if (!LexicalDC) return nullptr; } - + // Import the location of this declaration. SourceLocation StartLoc = Importer.Import(D->getLocStart()); SourceLocation IdLoc = Importer.Import(D->getLocation()); // Import template arguments. SmallVector<TemplateArgument, 2> TemplateArgs; - if (ImportTemplateArguments(D->getTemplateArgs().data(), + if (ImportTemplateArguments(D->getTemplateArgs().data(), D->getTemplateArgs().size(), TemplateArgs)) return nullptr; @@ -4507,9 +4507,9 @@ Decl *ASTNodeImporter::VisitClassTemplateSpecializationDecl( if (D2) { // We already have a class template specialization with these template // arguments. - + // FIXME: Check for specialization vs. instantiation errors. - + if (RecordDecl *FoundDef = D2->getDefinition()) { if (!D->isCompleteDefinition() || IsStructuralMatch(D, FoundDef)) { // The record types structurally match, or the "from" translation @@ -4557,7 +4557,7 @@ Decl *ASTNodeImporter::VisitClassTemplateSpecializationDecl( // Add this specialization to the class template. ClassTemplate->AddSpecialization(D2, InsertPos); - + // Import the qualifier, if any. D2->setQualifierInfo(Importer.Import(D->getQualifierLoc())); @@ -5484,7 +5484,7 @@ Expr *ASTNodeImporter::VisitDeclRefExpr(DeclRefExpr *E) { if (!FoundD) return nullptr; } - + QualType T = Importer.Import(E->getType()); if (T.isNull()) return nullptr; @@ -5497,7 +5497,7 @@ Expr *ASTNodeImporter::VisitDeclRefExpr(DeclRefExpr *E) { ResInfo = &ToTAInfo; } - DeclRefExpr *DRE = DeclRefExpr::Create(Importer.getToContext(), + DeclRefExpr *DRE = DeclRefExpr::Create(Importer.getToContext(), Importer.Import(E->getQualifierLoc()), Importer.Import(E->getTemplateKeywordLoc()), ToD, @@ -5583,7 +5583,7 @@ Expr *ASTNodeImporter::VisitIntegerLiteral(IntegerLiteral *E) { if (T.isNull()) return nullptr; - return IntegerLiteral::Create(Importer.getToContext(), + return IntegerLiteral::Create(Importer.getToContext(), E->getValue(), T, Importer.Import(E->getLocation())); } @@ -5674,7 +5674,7 @@ Expr *ASTNodeImporter::VisitParenExpr(ParenExpr *E) { if (!SubExpr) return nullptr; - return new (Importer.getToContext()) + return new (Importer.getToContext()) ParenExpr(Importer.Import(E->getLParen()), Importer.Import(E->getRParen()), SubExpr); @@ -5721,7 +5721,7 @@ Expr *ASTNodeImporter::VisitUnaryOperator(UnaryOperator *E) { Expr * ASTNodeImporter::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E) { QualType ResultType = Importer.Import(E->getType()); - + if (E->isArgumentType()) { TypeSourceInfo *TInfo = Importer.Import(E->getArgumentTypeInfo()); if (!TInfo) @@ -5732,7 +5732,7 @@ ASTNodeImporter::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E) { Importer.Import(E->getOperatorLoc()), Importer.Import(E->getRParenLoc())); } - + Expr *SubExpr = Importer.Import(E->getArgumentExpr()); if (!SubExpr) return nullptr; @@ -5904,7 +5904,7 @@ Expr *ASTNodeImporter::VisitCompoundAssignOperator(CompoundAssignOperator *E) { if (!RHS) return nullptr; - return new (Importer.getToContext()) + return new (Importer.getToContext()) CompoundAssignOperator(LHS, RHS, E->getOpcode(), T, E->getValueKind(), E->getObjectKind(), @@ -6354,11 +6354,11 @@ Expr *ASTNodeImporter::VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { QualType T = Importer.Import(E->getType()); if (T.isNull()) return nullptr; - + Expr *ToFn = Importer.Import(E->getCallee()); if (!ToFn) return nullptr; - + SmallVector<Expr *, 4> ToArgs(E->getNumArgs()); if (ImportContainerChecked(E->arguments(), ToArgs)) return nullptr; @@ -6372,7 +6372,7 @@ Expr *ASTNodeImporter::VisitCXXThisExpr(CXXThisExpr *E) { QualType T = Importer.Import(E->getType()); if (T.isNull()) return nullptr; - + return new (Importer.getToContext()) CXXThisExpr(Importer.Import(E->getLocation()), T, E->isImplicit()); } @@ -6381,7 +6381,7 @@ Expr *ASTNodeImporter::VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { QualType T = Importer.Import(E->getType()); if (T.isNull()) return nullptr; - + return new (Importer.getToContext()) CXXBoolLiteralExpr(E->getValue(), T, Importer.Import(E->getLocation())); } @@ -6646,7 +6646,7 @@ Expr *ASTNodeImporter::VisitCallExpr(CallExpr *E) { } return new (Importer.getToContext()) - CallExpr(Importer.getToContext(), ToCallee, + CallExpr(Importer.getToContext(), ToCallee, llvm::makeArrayRef(ToArgs_Copied, NumArgs), T, E->getValueKind(), Importer.Import(E->getRParenLoc())); } @@ -6838,18 +6838,18 @@ Expr *ASTNodeImporter::VisitCXXNamedCastExpr(CXXNamedCastExpr *E) { SourceLocation ToOperatorLoc = Importer.Import(E->getOperatorLoc()); SourceLocation ToRParenLoc = Importer.Import(E->getRParenLoc()); SourceRange ToAngleBrackets = Importer.Import(E->getAngleBrackets()); - + if (isa<CXXStaticCastExpr>(E)) { return CXXStaticCastExpr::Create( - Importer.getToContext(), ToType, VK, CK, ToOp, &BasePath, + Importer.getToContext(), ToType, VK, CK, ToOp, &BasePath, ToWritten, ToOperatorLoc, ToRParenLoc, ToAngleBrackets); } else if (isa<CXXDynamicCastExpr>(E)) { return CXXDynamicCastExpr::Create( - Importer.getToContext(), ToType, VK, CK, ToOp, &BasePath, + Importer.getToContext(), ToType, VK, CK, ToOp, &BasePath, ToWritten, ToOperatorLoc, ToRParenLoc, ToAngleBrackets); } else if (isa<CXXReinterpretCastExpr>(E)) { return CXXReinterpretCastExpr::Create( - Importer.getToContext(), ToType, VK, CK, ToOp, &BasePath, + Importer.getToContext(), ToType, VK, CK, ToOp, &BasePath, ToWritten, ToOperatorLoc, ToRParenLoc, ToAngleBrackets); } else { return nullptr; @@ -6943,22 +6943,22 @@ QualType ASTImporter::Import(QualType FromT) { return {}; const Type *fromTy = FromT.getTypePtr(); - - // Check whether we've already imported this type. + + // Check whether we've already imported this type. llvm::DenseMap<const Type *, const Type *>::iterator Pos = ImportedTypes.find(fromTy); if (Pos != ImportedTypes.end()) return ToContext.getQualifiedType(Pos->second, FromT.getLocalQualifiers()); - + // Import the type ASTNodeImporter Importer(*this); QualType ToT = Importer.Visit(fromTy); if (ToT.isNull()) return ToT; - + // Record the imported type. ImportedTypes[fromTy] = ToT.getTypePtr(); - + return ToContext.getQualifiedType(ToT, FromT.getLocalQualifiers()); } @@ -6972,7 +6972,7 @@ TypeSourceInfo *ASTImporter::Import(TypeSourceInfo *FromTSI) { if (T.isNull()) return nullptr; - return ToContext.getTrivialTypeSourceInfo(T, + return ToContext.getTrivialTypeSourceInfo(T, Import(FromTSI->getTypeLoc().getLocStart())); } @@ -7027,7 +7027,7 @@ DeclContext *ASTImporter::ImportContext(DeclContext *FromDC) { if (!ToDC) return nullptr; - // When we're using a record/enum/Objective-C class/protocol as a context, we + // When we're using a record/enum/Objective-C class/protocol as a context, we // need it to have a definition. if (auto *ToRecord = dyn_cast<RecordDecl>(ToDC)) { auto *FromRecord = cast<RecordDecl>(FromDC); @@ -7048,7 +7048,7 @@ DeclContext *ASTImporter::ImportContext(DeclContext *FromDC) { ASTNodeImporter::IDK_Basic); } else { CompleteDecl(ToEnum); - } + } } else if (auto *ToClass = dyn_cast<ObjCInterfaceDecl>(ToDC)) { auto *FromClass = cast<ObjCInterfaceDecl>(FromDC); if (ToClass->getDefinition()) { @@ -7068,9 +7068,9 @@ DeclContext *ASTImporter::ImportContext(DeclContext *FromDC) { ASTNodeImporter::IDK_Basic); } else { CompleteDecl(ToProto); - } + } } - + return ToDC; } @@ -7085,11 +7085,11 @@ Stmt *ASTImporter::Import(Stmt *FromS) { if (!FromS) return nullptr; - // Check whether we've already imported this declaration. + // Check whether we've already imported this declaration. llvm::DenseMap<Stmt *, Stmt *>::iterator Pos = ImportedStmts.find(FromS); if (Pos != ImportedStmts.end()) return Pos->second; - + // Import the type ASTNodeImporter Importer(*this); Stmt *ToS = Importer.Visit(FromS); @@ -7115,14 +7115,14 @@ NestedNameSpecifier *ASTImporter::Import(NestedNameSpecifier *FromNNS) { return nullptr; case NestedNameSpecifier::Namespace: - if (auto *NS = + if (auto *NS = cast_or_null<NamespaceDecl>(Import(FromNNS->getAsNamespace()))) { return NestedNameSpecifier::Create(ToContext, prefix, NS); } return nullptr; case NestedNameSpecifier::NamespaceAlias: - if (auto *NSAD = + if (auto *NSAD = cast_or_null<NamespaceAliasDecl>(Import(FromNNS->getAsNamespaceAlias()))) { return NestedNameSpecifier::Create(ToContext, prefix, NSAD); } @@ -7142,9 +7142,9 @@ NestedNameSpecifier *ASTImporter::Import(NestedNameSpecifier *FromNNS) { case NestedNameSpecifier::TypeSpecWithTemplate: { QualType T = Import(QualType(FromNNS->getAsType(), 0u)); if (!T.isNull()) { - bool bTemplate = FromNNS->getKind() == + bool bTemplate = FromNNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate; - return NestedNameSpecifier::Create(ToContext, prefix, + return NestedNameSpecifier::Create(ToContext, prefix, bTemplate, T.getTypePtr()); } } @@ -7231,48 +7231,48 @@ TemplateName ASTImporter::Import(TemplateName From) { if (auto *ToTemplate = cast_or_null<TemplateDecl>(Import(From.getAsTemplateDecl()))) return TemplateName(ToTemplate); - + return {}; - + case TemplateName::OverloadedTemplate: { OverloadedTemplateStorage *FromStorage = From.getAsOverloadedTemplate(); UnresolvedSet<2> ToTemplates; for (auto *I : *FromStorage) { - if (auto *To = cast_or_null<NamedDecl>(Import(I))) + if (auto *To = cast_or_null<NamedDecl>(Import(I))) ToTemplates.addDecl(To); else return {}; } - return ToContext.getOverloadedTemplateName(ToTemplates.begin(), + return ToContext.getOverloadedTemplateName(ToTemplates.begin(), ToTemplates.end()); } - + case TemplateName::QualifiedTemplate: { QualifiedTemplateName *QTN = From.getAsQualifiedTemplateName(); NestedNameSpecifier *Qualifier = Import(QTN->getQualifier()); if (!Qualifier) return {}; - + if (auto *ToTemplate = cast_or_null<TemplateDecl>(Import(From.getAsTemplateDecl()))) - return ToContext.getQualifiedTemplateName(Qualifier, - QTN->hasTemplateKeyword(), + return ToContext.getQualifiedTemplateName(Qualifier, + QTN->hasTemplateKeyword(), ToTemplate); return {}; } - + case TemplateName::DependentTemplate: { DependentTemplateName *DTN = From.getAsDependentTemplateName(); NestedNameSpecifier *Qualifier = Import(DTN->getQualifier()); if (!Qualifier) return {}; - + if (DTN->isIdentifier()) { - return ToContext.getDependentTemplateName(Qualifier, + return ToContext.getDependentTemplateName(Qualifier, Import(DTN->getIdentifier())); } - + return ToContext.getDependentTemplateName(Qualifier, DTN->getOperator()); } @@ -7287,10 +7287,10 @@ TemplateName ASTImporter::Import(TemplateName From) { TemplateName replacement = Import(subst->getReplacement()); if (replacement.isNull()) return {}; - + return ToContext.getSubstTemplateTemplateParm(param, replacement); } - + case TemplateName::SubstTemplateTemplateParmPack: { SubstTemplateTemplateParmPackStorage *SubstPack = From.getAsSubstTemplateTemplateParmPack(); @@ -7299,17 +7299,17 @@ TemplateName ASTImporter::Import(TemplateName From) { Import(SubstPack->getParameterPack())); if (!Param) return {}; - + ASTNodeImporter Importer(*this); - TemplateArgument ArgPack + TemplateArgument ArgPack = Importer.ImportTemplateArgument(SubstPack->getArgumentPack()); if (ArgPack.isNull()) return {}; - + return ToContext.getSubstTemplateTemplateParmPack(Param, ArgPack); } } - + llvm_unreachable("Invalid template name kind"); } @@ -7452,26 +7452,26 @@ void ASTImporter::ImportDefinition(Decl *From) { Decl *To = Import(From); if (!To) return; - + if (auto *FromDC = cast<DeclContext>(From)) { ASTNodeImporter Importer(*this); - + if (auto *ToRecord = dyn_cast<RecordDecl>(To)) { if (!ToRecord->getDefinition()) { - Importer.ImportDefinition(cast<RecordDecl>(FromDC), ToRecord, + Importer.ImportDefinition(cast<RecordDecl>(FromDC), ToRecord, ASTNodeImporter::IDK_Everything); return; - } + } } if (auto *ToEnum = dyn_cast<EnumDecl>(To)) { if (!ToEnum->getDefinition()) { - Importer.ImportDefinition(cast<EnumDecl>(FromDC), ToEnum, + Importer.ImportDefinition(cast<EnumDecl>(FromDC), ToEnum, ASTNodeImporter::IDK_Everything); return; - } + } } - + if (auto *ToIFace = dyn_cast<ObjCInterfaceDecl>(To)) { if (!ToIFace->getDefinition()) { Importer.ImportDefinition(cast<ObjCInterfaceDecl>(FromDC), ToIFace, @@ -7487,7 +7487,7 @@ void ASTImporter::ImportDefinition(Decl *From) { return; } } - + Importer.ImportDeclContext(FromDC, true); } } diff --git a/lib/AST/ASTStructuralEquivalence.cpp b/lib/AST/ASTStructuralEquivalence.cpp index 7853ab28810b..df3c2be9a2e2 100644 --- a/lib/AST/ASTStructuralEquivalence.cpp +++ b/lib/AST/ASTStructuralEquivalence.cpp @@ -505,7 +505,7 @@ static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, if (Proto1->getTypeQuals() != Proto2->getTypeQuals()) return false; - + // Check exceptions, this information is lost in canonical type. const auto *OrigProto1 = cast<FunctionProtoType>(OrigT1.getDesugaredType(Context.FromCtx)); @@ -513,7 +513,7 @@ static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, cast<FunctionProtoType>(OrigT2.getDesugaredType(Context.ToCtx)); auto Spec1 = OrigProto1->getExceptionSpecType(); auto Spec2 = OrigProto2->getExceptionSpecType(); - + if (Spec1 != Spec2) return false; if (Spec1 == EST_Dynamic) { diff --git a/lib/AST/CXXInheritance.cpp b/lib/AST/CXXInheritance.cpp index 2825329775ed..a0b22b6a85e0 100644 --- a/lib/AST/CXXInheritance.cpp +++ b/lib/AST/CXXInheritance.cpp @@ -99,7 +99,7 @@ bool CXXRecordDecl::isDerivedFrom(const CXXRecordDecl *Base, CXXBasePaths &Paths) const { if (getCanonicalDecl() == Base->getCanonicalDecl()) return false; - + Paths.setOrigin(const_cast<CXXRecordDecl*>(this)); const CXXRecordDecl *BaseDecl = Base->getCanonicalDecl(); @@ -120,7 +120,7 @@ bool CXXRecordDecl::isVirtuallyDerivedFrom(const CXXRecordDecl *Base) const { if (getCanonicalDecl() == Base->getCanonicalDecl()) return false; - + Paths.setOrigin(const_cast<CXXRecordDecl*>(this)); const CXXRecordDecl *BaseDecl = Base->getCanonicalDecl(); @@ -165,7 +165,7 @@ bool CXXRecordDecl::forallBases(ForallBasesCallback BaseMatches, continue; } - CXXRecordDecl *Base = + CXXRecordDecl *Base = cast_or_null<CXXRecordDecl>(Ty->getDecl()->getDefinition()); if (!Base || (Base->isDependentContext() && @@ -174,7 +174,7 @@ bool CXXRecordDecl::forallBases(ForallBasesCallback BaseMatches, AllMatches = false; continue; } - + Queue.push_back(Base); if (!BaseMatches(Base)) { if (AllowShortCircuit) return false; @@ -209,12 +209,12 @@ bool CXXBasePaths::lookupInBases(ASTContext &Context, // C++ [temp.dep]p3: // In the definition of a class template or a member of a class template, // if a base class of the class template depends on a template-parameter, - // the base class scope is not examined during unqualified name lookup - // either at the point of definition of the class template or member or + // the base class scope is not examined during unqualified name lookup + // either at the point of definition of the class template or member or // during an instantiation of the class tem- plate or member. if (!LookupInDependent && BaseType->isDependentType()) continue; - + // Determine whether we need to visit this base class at all, // updating the count of subobjects appropriately. IsVirtBaseAndNumberNonVirtBases &Subobjects = ClassSubobjects[BaseType]; @@ -261,13 +261,13 @@ bool CXXBasePaths::lookupInBases(ASTContext &Context, if (IsFirstStep) ScratchPath.Access = BaseSpec.getAccessSpecifier(); else - ScratchPath.Access = CXXRecordDecl::MergeAccess(AccessToHere, + ScratchPath.Access = CXXRecordDecl::MergeAccess(AccessToHere, BaseSpec.getAccessSpecifier()); } - + // Track whether there's a path involving this specific base. bool FoundPathThroughBase = false; - + if (BaseMatches(&BaseSpec, ScratchPath)) { // We've found a path that terminates at this base. FoundPath = FoundPathThroughBase = true; @@ -313,15 +313,15 @@ bool CXXBasePaths::lookupInBases(ASTContext &Context, // a sub-object A if A is a base class sub-object of B. Any // declarations that are so hidden are eliminated from // consideration. - - // There is a path to a base class that meets the criteria. If we're + + // There is a path to a base class that meets the criteria. If we're // not collecting paths or finding ambiguities, we're done. FoundPath = FoundPathThroughBase = true; if (!isFindingAmbiguities()) return FoundPath; } } - + // Pop this base specifier off the current path (if we're // collecting paths). if (isRecordingPaths()) { @@ -336,7 +336,7 @@ bool CXXBasePaths::lookupInBases(ASTContext &Context, // Reset the scratch path access. ScratchPath.Access = AccessToHere; - + return FoundPath; } @@ -352,7 +352,7 @@ bool CXXRecordDecl::lookupInBases(BaseMatchesCallback BaseMatches, // we're done. if (!Paths.isRecordingPaths() || !Paths.isFindingAmbiguities()) return true; - + // C++ [class.member.lookup]p6: // When virtual base classes are used, a hidden declaration can be // reached along a path through the sub-object lattice that does @@ -396,7 +396,7 @@ bool CXXRecordDecl::lookupInBases(BaseMatchesCallback BaseMatches, return true; } -bool CXXRecordDecl::FindBaseClass(const CXXBaseSpecifier *Specifier, +bool CXXRecordDecl::FindBaseClass(const CXXBaseSpecifier *Specifier, CXXBasePath &Path, const CXXRecordDecl *BaseRecord) { assert(BaseRecord->getCanonicalDecl() == BaseRecord && @@ -405,7 +405,7 @@ bool CXXRecordDecl::FindBaseClass(const CXXBaseSpecifier *Specifier, ->getCanonicalDecl() == BaseRecord; } -bool CXXRecordDecl::FindVirtualBaseClass(const CXXBaseSpecifier *Specifier, +bool CXXRecordDecl::FindVirtualBaseClass(const CXXBaseSpecifier *Specifier, CXXBasePath &Path, const CXXRecordDecl *BaseRecord) { assert(BaseRecord->getCanonicalDecl() == BaseRecord && @@ -415,7 +415,7 @@ bool CXXRecordDecl::FindVirtualBaseClass(const CXXBaseSpecifier *Specifier, ->getCanonicalDecl() == BaseRecord; } -bool CXXRecordDecl::FindTagMember(const CXXBaseSpecifier *Specifier, +bool CXXRecordDecl::FindTagMember(const CXXBaseSpecifier *Specifier, CXXBasePath &Path, DeclarationName Name) { RecordDecl *BaseRecord = @@ -490,12 +490,12 @@ bool CXXRecordDecl::FindOMPReductionMember(const CXXBaseSpecifier *Specifier, } bool CXXRecordDecl:: -FindNestedNameSpecifierMember(const CXXBaseSpecifier *Specifier, +FindNestedNameSpecifierMember(const CXXBaseSpecifier *Specifier, CXXBasePath &Path, DeclarationName Name) { RecordDecl *BaseRecord = Specifier->getType()->castAs<RecordType>()->getDecl(); - + for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); Path.Decls = Path.Decls.slice(1)) { @@ -504,7 +504,7 @@ FindNestedNameSpecifierMember(const CXXBaseSpecifier *Specifier, Path.Decls.front()->isInIdentifierNamespace(IDNS_Tag)) return true; } - + return false; } @@ -538,20 +538,20 @@ std::vector<const NamedDecl *> CXXRecordDecl::lookupDependentName( return Results; } -void OverridingMethods::add(unsigned OverriddenSubobject, +void OverridingMethods::add(unsigned OverriddenSubobject, UniqueVirtualMethod Overriding) { SmallVectorImpl<UniqueVirtualMethod> &SubobjectOverrides = Overrides[OverriddenSubobject]; - if (std::find(SubobjectOverrides.begin(), SubobjectOverrides.end(), + if (std::find(SubobjectOverrides.begin(), SubobjectOverrides.end(), Overriding) == SubobjectOverrides.end()) SubobjectOverrides.push_back(Overriding); } void OverridingMethods::add(const OverridingMethods &Other) { for (const_iterator I = Other.begin(), IE = Other.end(); I != IE; ++I) { - for (overriding_const_iterator M = I->second.begin(), + for (overriding_const_iterator M = I->second.begin(), MEnd = I->second.end(); - M != MEnd; + M != MEnd; ++M) add(I->first, *M); } @@ -586,7 +586,7 @@ public: } // namespace -void FinalOverriderCollector::Collect(const CXXRecordDecl *RD, +void FinalOverriderCollector::Collect(const CXXRecordDecl *RD, bool VirtualBase, const CXXRecordDecl *InVirtualSubobject, CXXFinalOverriderMap &Overriders) { @@ -633,7 +633,7 @@ void FinalOverriderCollector::Collect(const CXXRecordDecl *RD, // Merge the overriders from this base class into our own set of // overriders. - for (CXXFinalOverriderMap::iterator OM = BaseOverriders->begin(), + for (CXXFinalOverriderMap::iterator OM = BaseOverriders->begin(), OMEnd = BaseOverriders->end(); OM != OMEnd; ++OM) { @@ -656,7 +656,7 @@ void FinalOverriderCollector::Collect(const CXXRecordDecl *RD, if (OverriddenMethods.begin() == OverriddenMethods.end()) { // This is a new virtual function that does not override any // other virtual function. Add it to the map of virtual - // functions for which we are tracking overridders. + // functions for which we are tracking overridders. // C++ [class.virtual]p2: // For convenience we say that any virtual function overrides itself. @@ -711,12 +711,12 @@ void FinalOverriderCollector::Collect(const CXXRecordDecl *RD, FinalOverriderCollector::~FinalOverriderCollector() { for (llvm::DenseMap<const CXXRecordDecl *, CXXFinalOverriderMap *>::iterator VO = VirtualOverriders.begin(), VOEnd = VirtualOverriders.end(); - VO != VOEnd; + VO != VOEnd; ++VO) delete VO->second; } -void +void CXXRecordDecl::getFinalOverriders(CXXFinalOverriderMap &FinalOverriders) const { FinalOverriderCollector Collector; Collector.Collect(this, false, nullptr, FinalOverriders); @@ -754,7 +754,7 @@ CXXRecordDecl::getFinalOverriders(CXXFinalOverriderMap &FinalOverriders) const { } } -static void +static void AddIndirectPrimaryBases(const CXXRecordDecl *RD, ASTContext &Context, CXXIndirectPrimaryBaseSet& Bases) { // If the record has a virtual primary base class, add it to our set. @@ -777,7 +777,7 @@ AddIndirectPrimaryBases(const CXXRecordDecl *RD, ASTContext &Context, } -void +void CXXRecordDecl::getIndirectPrimaryBases(CXXIndirectPrimaryBaseSet& Bases) const { ASTContext &Context = getASTContext(); diff --git a/lib/AST/Comment.cpp b/lib/AST/Comment.cpp index dfa2a1665d40..0d759e226c42 100644 --- a/lib/AST/Comment.cpp +++ b/lib/AST/Comment.cpp @@ -205,7 +205,7 @@ void DeclInfo::fill() { return; } CurrentDecl = CommentDecl; - + Decl::Kind K = CommentDecl->getKind(); switch (K) { default: diff --git a/lib/AST/CommentLexer.cpp b/lib/AST/CommentLexer.cpp index 6ff4d45a9572..8d401ff5c7ea 100644 --- a/lib/AST/CommentLexer.cpp +++ b/lib/AST/CommentLexer.cpp @@ -274,7 +274,7 @@ const char *findCCommentEnd(const char *BufferPtr, const char *BufferEnd) { } llvm_unreachable("buffer end hit before '*/' was seen"); } - + } // end anonymous namespace void Lexer::formTokenWithChars(Token &Result, const char *TokEnd, diff --git a/lib/AST/Decl.cpp b/lib/AST/Decl.cpp index 3b9b85a20af6..8030dd0c2f41 100644 --- a/lib/AST/Decl.cpp +++ b/lib/AST/Decl.cpp @@ -633,7 +633,7 @@ LinkageComputer::getLVForNamespaceScopeDecl(const NamedDecl *D, // equivalent in C99) // The C++ modules TS adds "non-exported" to this list. if (Context.getLangOpts().CPlusPlus && - Var->getType().isConstQualified() && + Var->getType().isConstQualified() && !Var->getType().isVolatileQualified() && !Var->isInline() && !isExportedFromModuleIntefaceUnit(Var)) { @@ -1049,7 +1049,7 @@ bool NamedDecl::isLinkageValid() const { ObjCStringFormatFamily NamedDecl::getObjCFStringFormattingFamily() const { StringRef name = getName(); if (name.empty()) return SFF_None; - + if (name.front() == 'C') if (name == "CFStringCreateWithFormat" || name == "CFStringCreateWithFormatAndArguments" || @@ -1338,7 +1338,7 @@ LinkageInfo LinkageComputer::computeLVForDecl(const NamedDecl *D, case Decl::ObjCPropertyImpl: case Decl::ObjCProtocol: return getExternalLinkageFor(D); - + case Decl::CXXRecord: { const auto *Record = cast<CXXRecordDecl>(D); if (Record->isLambda()) { @@ -1348,25 +1348,25 @@ LinkageInfo LinkageComputer::computeLVForDecl(const NamedDecl *D, } // This lambda has its linkage/visibility determined: - // - either by the outermost lambda if that lambda has no mangling - // number. + // - either by the outermost lambda if that lambda has no mangling + // number. // - or by the parent of the outer most lambda - // This prevents infinite recursion in settings such as nested lambdas - // used in NSDMI's, for e.g. + // This prevents infinite recursion in settings such as nested lambdas + // used in NSDMI's, for e.g. // struct L { // int t{}; - // int t2 = ([](int a) { return [](int b) { return b; };})(t)(t); + // int t2 = ([](int a) { return [](int b) { return b; };})(t)(t); // }; - const CXXRecordDecl *OuterMostLambda = + const CXXRecordDecl *OuterMostLambda = getOutermostEnclosingLambda(Record); if (!OuterMostLambda->getLambdaManglingNumber()) return getInternalLinkageFor(D); - + return getLVForClosure( OuterMostLambda->getDeclContext()->getRedeclContext(), OuterMostLambda->getLambdaContextDecl(), computation); } - + break; } } @@ -1374,7 +1374,7 @@ LinkageInfo LinkageComputer::computeLVForDecl(const NamedDecl *D, // Handle linkage for namespace-scope names. if (D->getDeclContext()->getRedeclContext()->isFileContext()) return getLVForNamespaceScopeDecl(D, computation, IgnoreVarTypeLinkage); - + // C++ [basic.link]p5: // In addition, a member function, static data member, a named // class or enumeration of class scope, or an unnamed class or @@ -1718,7 +1718,7 @@ NamedDecl *NamedDecl::getUnderlyingDeclImpl() { bool NamedDecl::isCXXInstanceMember() const { if (!isCXXClassMember()) return false; - + const NamedDecl *D = this; if (isa<UsingShadowDecl>(D)) D = cast<UsingShadowDecl>(D)->getTargetDecl(); @@ -1938,7 +1938,7 @@ VarDecl::TLSKind VarDecl::getTLSKind() const { SourceRange VarDecl::getSourceRange() const { if (const Expr *Init = getInit()) { SourceLocation InitEnd = Init->getLocEnd(); - // If Init is implicit, ignore its source range and fallback on + // If Init is implicit, ignore its source range and fallback on // DeclaratorDecl::getSourceRange() to handle postfix elements. if (InitEnd.isValid() && InitEnd != getLocation()) return SourceRange(getOuterLocStart(), InitEnd); @@ -2174,11 +2174,11 @@ bool VarDecl::isOutOfLine() const { return false; // If this static data member was instantiated from a static data member of - // a class template, check whether that static data member was defined + // a class template, check whether that static data member was defined // out-of-line. if (VarDecl *VD = getInstantiatedFromStaticDataMember()) return VD->isOutOfLine(); - + return false; } @@ -2891,7 +2891,7 @@ FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) { assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch"); FunTmpl->setPreviousDecl(PrevFunTmpl); } - + if (PrevDecl && PrevDecl->IsInline) IsInline = true; } @@ -3043,7 +3043,7 @@ static bool RedeclForcesDefC99(const FunctionDecl *Redecl) { if (Redecl->isImplicit()) return false; - if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern) + if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern) return true; // Not an inline definition return false; @@ -3088,7 +3088,7 @@ bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const { if (!Prev->isInlineSpecified() || Prev->getStorageClass() != SC_Extern) return false; - } else if (Prev->isInlineSpecified() && + } else if (Prev->isInlineSpecified() && Prev->getStorageClass() != SC_Extern) { return false; } @@ -3100,8 +3100,8 @@ bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const { return false; // C99 6.7.4p6: - // [...] If all of the file scope declarations for a function in a - // translation unit include the inline function specifier without extern, + // [...] If all of the file scope declarations for a function in a + // translation unit include the inline function specifier without extern, // then the definition in that translation unit is an inline definition. if (isInlineSpecified() && getStorageClass() != SC_Extern) return false; @@ -3149,12 +3149,9 @@ SourceRange FunctionDecl::getExceptionSpecSourceRange() const { const Attr *FunctionDecl::getUnusedResultAttr() const { QualType RetType = getReturnType(); - if (RetType->isRecordType()) { - if (const auto *Ret = - dyn_cast_or_null<RecordDecl>(RetType->getAsTagDecl())) { - if (const auto *R = Ret->getAttr<WarnUnusedResultAttr>()) - return R; - } + if (const auto *Ret = RetType->getAsRecordDecl()) { + if (const auto *R = Ret->getAttr<WarnUnusedResultAttr>()) + return R; } else if (const auto *ET = RetType->getAs<EnumType>()) { if (const EnumDecl *ED = ET->getDecl()) { if (const auto *R = ED->getAttr<WarnUnusedResultAttr>()) @@ -3177,16 +3174,16 @@ const Attr *FunctionDecl::getUnusedResultAttr() const { /// inline definition becomes externally visible (C99 6.7.4p6). /// /// In GNU89 mode, or if the gnu_inline attribute is attached to the function -/// definition, we use the GNU semantics for inline, which are nearly the -/// opposite of C99 semantics. In particular, "inline" by itself will create -/// an externally visible symbol, but "extern inline" will not create an +/// definition, we use the GNU semantics for inline, which are nearly the +/// opposite of C99 semantics. In particular, "inline" by itself will create +/// an externally visible symbol, but "extern inline" will not create an /// externally visible symbol. bool FunctionDecl::isInlineDefinitionExternallyVisible() const { assert((doesThisDeclarationHaveABody() || willHaveBody()) && "Must be a function definition"); assert(isInlined() && "Function must be inline"); ASTContext &Context = getASTContext(); - + if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) { // Note: If you change the logic here, please change // doesDeclarationForceExternallyVisibleDefinition as well. @@ -3196,15 +3193,15 @@ bool FunctionDecl::isInlineDefinitionExternallyVisible() const { // externally visible. if (!(isInlineSpecified() && getStorageClass() == SC_Extern)) return true; - + // If any declaration is 'inline' but not 'extern', then this definition // is externally visible. for (auto Redecl : redecls()) { - if (Redecl->isInlineSpecified() && + if (Redecl->isInlineSpecified() && Redecl->getStorageClass() != SC_Extern) return true; - } - + } + return false; } @@ -3213,17 +3210,17 @@ bool FunctionDecl::isInlineDefinitionExternallyVisible() const { "should not use C inline rules in C++"); // C99 6.7.4p6: - // [...] If all of the file scope declarations for a function in a - // translation unit include the inline function specifier without extern, + // [...] If all of the file scope declarations for a function in a + // translation unit include the inline function specifier without extern, // then the definition in that translation unit is an inline definition. for (auto Redecl : redecls()) { if (RedeclForcesDefC99(Redecl)) return true; } - + // C99 6.7.4p6: - // An inline definition does not provide an external definition for the - // function, and does not forbid an external definition in another + // An inline definition does not provide an external definition for the + // function, and does not forbid an external definition in another // translation unit. return false; } @@ -3273,13 +3270,13 @@ MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const { return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>(); } -void +void FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C, FunctionDecl *FD, TemplateSpecializationKind TSK) { - assert(TemplateOrSpecialization.isNull() && + assert(TemplateOrSpecialization.isNull() && "Member function is already a specialization"); - MemberSpecializationInfo *Info + MemberSpecializationInfo *Info = new (C) MemberSpecializationInfo(FD, TSK); TemplateOrSpecialization = Info; } @@ -3296,12 +3293,12 @@ bool FunctionDecl::isImplicitlyInstantiable() const { // If the function is invalid, it can't be implicitly instantiated. if (isInvalidDecl()) return false; - + switch (getTemplateSpecializationKind()) { case TSK_Undeclared: case TSK_ExplicitInstantiationDefinition: return false; - + case TSK_ImplicitInstantiation: return true; @@ -3320,12 +3317,12 @@ bool FunctionDecl::isImplicitlyInstantiable() const { bool HasPattern = false; if (PatternDecl) HasPattern = PatternDecl->hasBody(PatternDecl); - + // C++0x [temp.explicit]p9: // Except for inline functions, other explicit instantiation declarations // have the effect of suppressing the implicit instantiation of the entity - // to which they refer. - if (!HasPattern || !PatternDecl) + // to which they refer. + if (!HasPattern || !PatternDecl) return true; return PatternDecl->isInlined(); @@ -3335,7 +3332,7 @@ bool FunctionDecl::isTemplateInstantiation() const { switch (getTemplateSpecializationKind()) { case TSK_Undeclared: case TSK_ExplicitSpecialization: - return false; + return false; case TSK_ImplicitInstantiation: case TSK_ExplicitInstantiationDeclaration: case TSK_ExplicitInstantiationDefinition: @@ -3343,7 +3340,7 @@ bool FunctionDecl::isTemplateInstantiation() const { } llvm_unreachable("All TSK values handled."); } - + FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const { // Handle class scope explicit specialization special case. if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization) { @@ -3352,13 +3349,13 @@ FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const { return nullptr; } - // If this is a generic lambda call operator specialization, its + // If this is a generic lambda call operator specialization, its // instantiation pattern is always its primary template's pattern - // even if its primary template was instantiated from another + // even if its primary template was instantiated from another // member template (which happens with nested generic lambdas). - // Since a lambda's call operator's body is transformed eagerly, - // we don't have to go hunting for a prototype definition template - // (i.e. instantiated-from-member-template) to use as an instantiation + // Since a lambda's call operator's body is transformed eagerly, + // we don't have to go hunting for a prototype definition template + // (i.e. instantiated-from-member-template) to use as an instantiation // pattern. if (isGenericLambdaCallOperatorSpecialization( @@ -3377,7 +3374,7 @@ FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const { } return getDefinitionOrSelf(Primary->getTemplatedDecl()); - } + } if (auto *MFD = getInstantiatedFromMemberFunction()) return getDefinitionOrSelf(MFD); @@ -3432,7 +3429,7 @@ FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C, TemplateSpecializationKind TSK, const TemplateArgumentListInfo *TemplateArgsAsWritten, SourceLocation PointOfInstantiation) { - assert(TSK != TSK_Undeclared && + assert(TSK != TSK_Undeclared && "Must specify the type of function template specialization"); FunctionTemplateSpecializationInfo *Info = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>(); @@ -3500,7 +3497,7 @@ TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const { = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>(); if (MSInfo) return MSInfo->getTemplateSpecializationKind(); - + return TSK_Undeclared; } @@ -3540,22 +3537,22 @@ SourceLocation FunctionDecl::getPointOfInstantiation() const { else if (MemberSpecializationInfo *MSInfo = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) return MSInfo->getPointOfInstantiation(); - + return SourceLocation(); } bool FunctionDecl::isOutOfLine() const { if (Decl::isOutOfLine()) return true; - - // If this function was instantiated from a member function of a + + // If this function was instantiated from a member function of a // class template, check whether that member function was defined out-of-line. if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) { const FunctionDecl *Definition; if (FD->hasBody(Definition)) return Definition->isOutOfLine(); } - + // If this function was instantiated from a function template, // check whether that function template was defined out-of-line. if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) { @@ -3563,7 +3560,7 @@ bool FunctionDecl::isOutOfLine() const { if (FunTmpl->getTemplatedDecl()->hasBody(Definition)) return Definition->isOutOfLine(); } - + return false; } @@ -3576,7 +3573,7 @@ unsigned FunctionDecl::getMemoryFunctionKind() const { if (!FnInfo) return 0; - + // Builtin handling. switch (getBuiltinID()) { case Builtin::BI__builtin_memset: @@ -4525,7 +4522,7 @@ static unsigned getNumModuleIdentifiers(Module *Mod) { return Result; } -ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc, +ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported, ArrayRef<SourceLocation> IdentifierLocs) : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true) { @@ -4535,7 +4532,7 @@ ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc, StoredLocs); } -ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc, +ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported, SourceLocation EndLoc) : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false) { *getTrailingObjects<SourceLocation>() = EndLoc; diff --git a/lib/AST/DeclBase.cpp b/lib/AST/DeclBase.cpp index e3817c0abc38..700ddd389ddd 100644 --- a/lib/AST/DeclBase.cpp +++ b/lib/AST/DeclBase.cpp @@ -139,7 +139,7 @@ void Decl::setInvalidDecl(bool Invalid) { if (!isa<ParmVarDecl>(this)) { // Defensive maneuver for ill-formed code: we're likely not to make it to // a point where we set the access specifier, so default it to "public" - // to avoid triggering asserts elsewhere in the front end. + // to avoid triggering asserts elsewhere in the front end. setAccess(AS_public); } @@ -211,7 +211,7 @@ bool Decl::isTemplateParameterPack() const { bool Decl::isParameterPack() const { if (const auto *Parm = dyn_cast<ParmVarDecl>(this)) return Parm->isParameterPack(); - + return isTemplateParameterPack(); } @@ -253,7 +253,7 @@ bool Decl::isTemplated() const { const DeclContext *Decl::getParentFunctionOrMethod() const { for (const DeclContext *DC = getDeclContext(); - DC && !DC->isTranslationUnit() && !DC->isNamespace(); + DC && !DC->isTranslationUnit() && !DC->isNamespace(); DC = DC->getParent()) if (DC->isFunctionOrMethod()) return DC; @@ -419,7 +419,7 @@ void Decl::markUsed(ASTContext &C) { setIsUsed(); } -bool Decl::isReferenced() const { +bool Decl::isReferenced() const { if (Referenced) return true; @@ -428,7 +428,7 @@ bool Decl::isReferenced() const { if (I->Referenced) return true; - return false; + return false; } bool Decl::isExported() const { @@ -530,13 +530,13 @@ static AvailabilityResult CheckAvailability(ASTContext &Context, HintMessage = " - "; HintMessage += A->getMessage(); } - + // Make sure that this declaration has not been marked 'unavailable'. if (A->getUnavailable()) { if (Message) { Message->clear(); llvm::raw_string_ostream Out(*Message); - Out << "not available on " << PrettyPlatformName + Out << "not available on " << PrettyPlatformName << HintMessage; } @@ -544,13 +544,13 @@ static AvailabilityResult CheckAvailability(ASTContext &Context, } // Make sure that this declaration has already been introduced. - if (!A->getIntroduced().empty() && + if (!A->getIntroduced().empty() && EnclosingVersion < A->getIntroduced()) { if (Message) { Message->clear(); llvm::raw_string_ostream Out(*Message); VersionTuple VTI(A->getIntroduced()); - Out << "introduced in " << PrettyPlatformName << ' ' + Out << "introduced in " << PrettyPlatformName << ' ' << VTI << HintMessage; } @@ -563,10 +563,10 @@ static AvailabilityResult CheckAvailability(ASTContext &Context, Message->clear(); llvm::raw_string_ostream Out(*Message); VersionTuple VTO(A->getObsoleted()); - Out << "obsoleted in " << PrettyPlatformName << ' ' + Out << "obsoleted in " << PrettyPlatformName << ' ' << VTO << HintMessage; } - + return AR_Unavailable; } @@ -579,7 +579,7 @@ static AvailabilityResult CheckAvailability(ASTContext &Context, Out << "first deprecated in " << PrettyPlatformName << ' ' << VTD << HintMessage; } - + return AR_Deprecated; } @@ -1012,7 +1012,7 @@ DeclContext *DeclContext::getLookupParent() { if (getParent()->getRedeclContext()->isFileContext() && getLexicalParent()->getRedeclContext()->isRecord()) return getLexicalParent(); - + return getParent(); } @@ -1047,11 +1047,11 @@ bool DeclContext::isDependentContext() const { if (const auto *Record = dyn_cast<CXXRecordDecl>(this)) { if (Record->getDescribedClassTemplate()) return true; - + if (Record->isDependentLambda()) return true; } - + if (const auto *Function = dyn_cast<FunctionDecl>(this)) { if (Function->getDescribedFunctionTemplate()) return true; @@ -1140,12 +1140,12 @@ DeclContext *DeclContext::getPrimaryContext() { if (auto *Def = cast<ObjCInterfaceDecl>(this)->getDefinition()) return Def; return this; - + case Decl::ObjCProtocol: if (auto *Def = cast<ObjCProtocolDecl>(this)->getDefinition()) return Def; return this; - + case Decl::ObjCCategory: return this; @@ -1180,20 +1180,20 @@ DeclContext *DeclContext::getPrimaryContext() { } } -void +void DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){ Contexts.clear(); - + if (DeclKind != Decl::Namespace) { Contexts.push_back(this); return; } - + auto *Self = static_cast<NamespaceDecl *>(this); for (NamespaceDecl *N = Self->getMostRecentDecl(); N; N = N->getPreviousDecl()) Contexts.push_back(N); - + std::reverse(Contexts.begin(), Contexts.end()); } @@ -1253,7 +1253,7 @@ DeclContext::LoadLexicalDeclsFromExternalStorage() const { bool FieldsAlreadyLoaded = false; if (const auto *RD = dyn_cast<RecordDecl>(this)) FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage; - + // Splice the newly-read declarations into the beginning of the list // of declarations. Decl *ExternalFirst, *ExternalLast; @@ -1638,7 +1638,7 @@ void DeclContext::loadLazyLocalLexicalLookups() { void DeclContext::localUncachedLookup(DeclarationName Name, SmallVectorImpl<NamedDecl *> &Results) { Results.clear(); - + // If there's no external storage, just perform a normal lookup and copy // the results. if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) { @@ -1661,7 +1661,7 @@ void DeclContext::localUncachedLookup(DeclarationName Name, } } - // Slow case: grovel through the declarations in our chain looking for + // Slow case: grovel through the declarations in our chain looking for // matches. // FIXME: If we have lazy external declarations, this will not find them! // FIXME: Should we CollectAllContexts and walk them all here? @@ -1892,7 +1892,7 @@ DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C, PartialDiagnostic::Storage *DiagStorage = nullptr; if (PDiag.hasStorage()) DiagStorage = new (C) PartialDiagnostic::Storage; - + auto *DD = new (C) DependentDiagnostic(PDiag, DiagStorage); // TODO: Maybe we shouldn't reverse the order during insertion. diff --git a/lib/AST/DeclCXX.cpp b/lib/AST/DeclCXX.cpp index 076e6376d157..51e8e14f804a 100644 --- a/lib/AST/DeclCXX.cpp +++ b/lib/AST/DeclCXX.cpp @@ -203,7 +203,7 @@ CXXRecordDecl::setBases(CXXBaseSpecifier const * const *Bases, // The set of seen virtual base types. llvm::SmallPtrSet<CanQualType, 8> SeenVBaseTypes; - + // The virtual bases of this class. SmallVector<const CXXBaseSpecifier *, 8> VBases; @@ -257,7 +257,7 @@ CXXRecordDecl::setBases(CXXBaseSpecifier const * const *Bases, data().Aggregate = false; // C++ [class.virtual]p1: - // A class that declares or inherits a virtual function is called a + // A class that declares or inherits a virtual function is called a // polymorphic class. if (BaseClassDecl->isPolymorphic()) { data().Polymorphic = true; @@ -277,7 +277,7 @@ CXXRecordDecl::setBases(CXXBaseSpecifier const * const *Bases, // Record if this base is the first non-literal field or base. if (!hasNonLiteralTypeFieldsOrBases() && !BaseType->isLiteralType(C)) data().HasNonLiteralTypeFieldsOrBases = true; - + // Now go through all virtual bases of this base and add them. for (const auto &VBase : BaseClassDecl->vbases()) { // Add this base if it's not already in the list. @@ -421,7 +421,7 @@ CXXRecordDecl::setBases(CXXBaseSpecifier const * const *Bases, // has an Objective-C object member. if (BaseClassDecl->hasObjectMember()) setHasObjectMember(true); - + if (BaseClassDecl->hasVolatileMember()) setHasVolatileMember(true); @@ -453,7 +453,7 @@ CXXRecordDecl::setBases(CXXBaseSpecifier const * const *Bases, // we know there are no repeated base classes. if (data().IsStandardLayout && NumBases > 1 && hasRepeatedBaseClass(this)) data().IsStandardLayout = false; - + if (VBases.empty()) { data().IsParsingBaseSpecifiers = false; return; @@ -548,7 +548,7 @@ bool CXXRecordDecl::isTriviallyCopyable() const { } void CXXRecordDecl::markedVirtualFunctionPure() { - // C++ [class.abstract]p2: + // C++ [class.abstract]p2: // A class is abstract if it has at least one pure virtual function. data().Abstract = true; } @@ -639,7 +639,7 @@ void CXXRecordDecl::addedMember(Decl *D) { // Ignore friends and invalid declarations. if (D->getFriendObjectKind() || D->isInvalidDecl()) return; - + auto *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); if (FunTmpl) D = FunTmpl->getTemplatedDecl(); @@ -651,23 +651,23 @@ void CXXRecordDecl::addedMember(Decl *D) { if (auto *UnderlyingFunTmpl = dyn_cast<FunctionTemplateDecl>(DUnderlying)) DUnderlying = UnderlyingFunTmpl->getTemplatedDecl(); } - + if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) { if (Method->isVirtual()) { // C++ [dcl.init.aggr]p1: // An aggregate is an array or a class with [...] no virtual functions. data().Aggregate = false; - + // C++ [class]p4: // A POD-struct is an aggregate class... data().PlainOldData = false; - + // C++14 [meta.unary.prop]p4: // T is a class type [...] with [...] no virtual member functions... data().Empty = false; // C++ [class.virtual]p1: - // A class that declares or inherits a virtual function is called a + // A class that declares or inherits a virtual function is called a // polymorphic class. data().Polymorphic = true; @@ -873,8 +873,8 @@ void CXXRecordDecl::addedMember(Decl *D) { data().IsStandardLayout = false; // C++ [class.bit]p2: - // A declaration for a bit-field that omits the identifier declares an - // unnamed bit-field. Unnamed bit-fields are not members and cannot be + // A declaration for a bit-field that omits the identifier declares an + // unnamed bit-field. Unnamed bit-fields are not members and cannot be // initialized. if (Field->isUnnamedBitfield()) { // C++ [meta.unary.prop]p4: [LWG2358] @@ -886,7 +886,7 @@ void CXXRecordDecl::addedMember(Decl *D) { data().Empty = false; return; } - + // C++11 [class]p7: // A standard-layout class is a class that: // -- either has no non-static data members in the most derived class @@ -898,7 +898,7 @@ void CXXRecordDecl::addedMember(Decl *D) { // An aggregate is an array or a class (clause 9) with [...] no // private or protected non-static data members (clause 11). // - // A POD must be an aggregate. + // A POD must be an aggregate. if (D->getAccess() == AS_private || D->getAccess() == AS_protected) { data().Aggregate = false; data().PlainOldData = false; @@ -938,8 +938,8 @@ void CXXRecordDecl::addedMember(Decl *D) { data().HasVariantMembers = true; // C++0x [class]p9: - // A POD struct is a class that is both a trivial class and a - // standard-layout class, and has no non-static data members of type + // A POD struct is a class that is both a trivial class and a + // standard-layout class, and has no non-static data members of type // non-POD struct, non-POD union (or array of such types). // // Automatic Reference Counting: the presence of a member of Objective-C pointer type @@ -974,7 +974,7 @@ void CXXRecordDecl::addedMember(Decl *D) { } } else if (!T.isCXX98PODType(Context)) data().PlainOldData = false; - + if (T->isReferenceType()) { if (!Field->hasInClassInitializer()) data().HasUninitializedReferenceMember = true; @@ -1235,7 +1235,7 @@ void CXXRecordDecl::addedMember(Decl *D) { // T is a class type [...] with [...] no non-static data members data().Empty = false; } - + // Handle using declarations of conversion functions. if (auto *Shadow = dyn_cast<UsingShadowDecl>(D)) { if (Shadow->getDeclName().getNameKind() @@ -1321,40 +1321,40 @@ bool CXXRecordDecl::isCLike() const { return isPOD() && data().HasOnlyCMembers; } - -bool CXXRecordDecl::isGenericLambda() const { + +bool CXXRecordDecl::isGenericLambda() const { if (!isLambda()) return false; return getLambdaData().IsGenericLambda; } CXXMethodDecl* CXXRecordDecl::getLambdaCallOperator() const { if (!isLambda()) return nullptr; - DeclarationName Name = + DeclarationName Name = getASTContext().DeclarationNames.getCXXOperatorName(OO_Call); DeclContext::lookup_result Calls = lookup(Name); assert(!Calls.empty() && "Missing lambda call operator!"); - assert(Calls.size() == 1 && "More than one lambda call operator!"); - + assert(Calls.size() == 1 && "More than one lambda call operator!"); + NamedDecl *CallOp = Calls.front(); if (const auto *CallOpTmpl = dyn_cast<FunctionTemplateDecl>(CallOp)) return cast<CXXMethodDecl>(CallOpTmpl->getTemplatedDecl()); - + return cast<CXXMethodDecl>(CallOp); } CXXMethodDecl* CXXRecordDecl::getLambdaStaticInvoker() const { if (!isLambda()) return nullptr; - DeclarationName Name = + DeclarationName Name = &getASTContext().Idents.get(getLambdaStaticInvokerName()); DeclContext::lookup_result Invoker = lookup(Name); if (Invoker.empty()) return nullptr; - assert(Invoker.size() == 1 && "More than one static invoker operator!"); + assert(Invoker.size() == 1 && "More than one static invoker operator!"); NamedDecl *InvokerFun = Invoker.front(); if (const auto *InvokerTemplate = dyn_cast<FunctionTemplateDecl>(InvokerFun)) return cast<CXXMethodDecl>(InvokerTemplate->getTemplatedDecl()); - - return cast<CXXMethodDecl>(InvokerFun); + + return cast<CXXMethodDecl>(InvokerFun); } void CXXRecordDecl::getCaptureFields( @@ -1375,10 +1375,10 @@ void CXXRecordDecl::getCaptureFields( assert(Field == field_end()); } -TemplateParameterList * +TemplateParameterList * CXXRecordDecl::getGenericLambdaTemplateParameterList() const { if (!isLambda()) return nullptr; - CXXMethodDecl *CallOp = getLambdaCallOperator(); + CXXMethodDecl *CallOp = getLambdaCallOperator(); if (FunctionTemplateDecl *Tmpl = CallOp->getDescribedFunctionTemplate()) return Tmpl->getTemplateParameters(); return nullptr; @@ -1481,7 +1481,7 @@ static void CollectVisibleConversions(ASTContext &Context, // found. These will be added to the output as long as they don't // appear in the hidden-conversions set. UnresolvedSet<8> VBaseCs; - + // The set of conversions in virtual bases that we've determined to // be hidden. llvm::SmallPtrSet<NamedDecl*, 8> HiddenVBaseCs; @@ -1572,13 +1572,13 @@ MemberSpecializationInfo *CXXRecordDecl::getMemberSpecializationInfo() const { return TemplateOrInstantiation.dyn_cast<MemberSpecializationInfo *>(); } -void +void CXXRecordDecl::setInstantiationOfMemberClass(CXXRecordDecl *RD, TemplateSpecializationKind TSK) { - assert(TemplateOrInstantiation.isNull() && + assert(TemplateOrInstantiation.isNull() && "Previous template or instantiation?"); assert(!isa<ClassTemplatePartialSpecializationDecl>(this)); - TemplateOrInstantiation + TemplateOrInstantiation = new (getASTContext()) MemberSpecializationInfo(RD, TSK); } @@ -1593,25 +1593,25 @@ void CXXRecordDecl::setDescribedClassTemplate(ClassTemplateDecl *Template) { TemplateSpecializationKind CXXRecordDecl::getTemplateSpecializationKind() const{ if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(this)) return Spec->getSpecializationKind(); - + if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) return MSInfo->getTemplateSpecializationKind(); - + return TSK_Undeclared; } -void +void CXXRecordDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK) { if (auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(this)) { Spec->setSpecializationKind(TSK); return; } - + if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) { MSInfo->setTemplateSpecializationKind(TSK); return; } - + llvm_unreachable("Not a class template or member class specialization"); } @@ -1771,17 +1771,17 @@ void CXXRecordDecl::completeDefinition(CXXFinalOverriderMap *FinalOverriders) { getFinalOverriders(MyFinalOverriders); FinalOverriders = &MyFinalOverriders; } - + bool Done = false; - for (CXXFinalOverriderMap::iterator M = FinalOverriders->begin(), + for (CXXFinalOverriderMap::iterator M = FinalOverriders->begin(), MEnd = FinalOverriders->end(); M != MEnd && !Done; ++M) { - for (OverridingMethods::iterator SO = M->second.begin(), + for (OverridingMethods::iterator SO = M->second.begin(), SOEnd = M->second.end(); SO != SOEnd && !Done; ++SO) { - assert(SO->second.size() > 0 && + assert(SO->second.size() > 0 && "All virtual functions have overriding virtual functions"); - + // C++ [class.abstract]p4: // A class is abstract if it contains or inherits at least one // pure virtual function for which the final overrider is pure @@ -1794,7 +1794,7 @@ void CXXRecordDecl::completeDefinition(CXXFinalOverriderMap *FinalOverriders) { } } } - + // Set access bits correctly on the directly-declared conversions. for (conversion_iterator I = conversion_begin(), E = conversion_end(); I != E; ++I) @@ -1805,14 +1805,14 @@ bool CXXRecordDecl::mayBeAbstract() const { if (data().Abstract || isInvalidDecl() || !data().Polymorphic || isDependentContext()) return false; - + for (const auto &B : bases()) { const auto *BaseDecl = cast<CXXRecordDecl>(B.getType()->getAs<RecordType>()->getDecl()); if (BaseDecl->isAbstract()) return true; } - + return false; } @@ -2006,7 +2006,7 @@ bool CXXMethodDecl::isUsualDeallocationFunction() const { return false; // C++ [basic.stc.dynamic.deallocation]p2: - // If a class T has a member deallocation function named operator delete + // If a class T has a member deallocation function named operator delete // with exactly one parameter, then that function is a usual (non-placement) // deallocation function. [...] if (getNumParams() == 1) @@ -2022,8 +2022,8 @@ bool CXXMethodDecl::isUsualDeallocationFunction() const { ++UsualParams; // C++ <=14 [basic.stc.dynamic.deallocation]p2: - // [...] If class T does not declare such an operator delete but does - // declare a member deallocation function named operator delete with + // [...] If class T does not declare such an operator delete but does + // declare a member deallocation function named operator delete with // exactly two parameters, the second of which has type std::size_t (18.1), // then this function is a usual deallocation function. // @@ -2048,8 +2048,8 @@ bool CXXMethodDecl::isUsualDeallocationFunction() const { // usual deallocation functions. if (Context.getLangOpts().AlignedAllocation) return true; - - // This function is a usual deallocation function if there are no + + // This function is a usual deallocation function if there are no // single-parameter deallocation functions of the same kind. DeclContext::lookup_result R = getDeclContext()->lookup(getDeclName()); for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); @@ -2058,25 +2058,25 @@ bool CXXMethodDecl::isUsualDeallocationFunction() const { if (FD->getNumParams() == 1) return false; } - + return true; } bool CXXMethodDecl::isCopyAssignmentOperator() const { // C++0x [class.copy]p17: - // A user-declared copy assignment operator X::operator= is a non-static - // non-template member function of class X with exactly one parameter of + // A user-declared copy assignment operator X::operator= is a non-static + // non-template member function of class X with exactly one parameter of // type X, X&, const X&, volatile X& or const volatile X&. if (/*operator=*/getOverloadedOperator() != OO_Equal || - /*non-static*/ isStatic() || + /*non-static*/ isStatic() || /*non-template*/getPrimaryTemplate() || getDescribedFunctionTemplate() || getNumParams() != 1) return false; - + QualType ParamType = getParamDecl(0)->getType(); if (const auto *Ref = ParamType->getAs<LValueReferenceType>()) ParamType = Ref->getPointeeType(); - + ASTContext &Context = getASTContext(); QualType ClassType = Context.getCanonicalType(Context.getTypeDeclType(getParent())); @@ -2151,7 +2151,7 @@ QualType CXXMethodDecl::getThisType(ASTContext &C) const { } bool CXXMethodDecl::hasInlineBody() const { - // If this function is a template instantiation, look at the template from + // If this function is a template instantiation, look at the template from // which it was instantiated. const FunctionDecl *CheckFn = getTemplateInstantiationPattern(); if (!CheckFn) @@ -2203,7 +2203,7 @@ CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context, CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context, TypeSourceInfo *TInfo, - SourceLocation L, Expr *Init, + SourceLocation L, Expr *Init, SourceLocation R) : Initializee(TInfo), Init(Init), LParenLoc(L), RParenLoc(R), IsDelegating(true), IsVirtual(false), IsWritten(false), SourceOrder(0) {} @@ -2225,13 +2225,13 @@ const Type *CXXCtorInitializer::getBaseClass() const { SourceLocation CXXCtorInitializer::getSourceLocation() const { if (isInClassMemberInitializer()) return getAnyMember()->getLocation(); - + if (isAnyMemberInitializer()) return getMemberLocation(); if (const auto *TSInfo = Initializee.get<TypeSourceInfo *>()) return TSInfo->getTypeLoc().getLocalSourceRange().getBegin(); - + return {}; } @@ -2318,37 +2318,37 @@ bool CXXConstructorDecl::isCopyOrMoveConstructor(unsigned &TypeQuals) const { // or else all other parameters have default arguments (8.3.6). // C++0x [class.copy]p3: // A non-template constructor for class X is a move constructor if its - // first parameter is of type X&&, const X&&, volatile X&&, or - // const volatile X&&, and either there are no other parameters or else + // first parameter is of type X&&, const X&&, volatile X&&, or + // const volatile X&&, and either there are no other parameters or else // all other parameters have default arguments. if ((getNumParams() < 1) || (getNumParams() > 1 && !getParamDecl(1)->hasDefaultArg()) || (getPrimaryTemplate() != nullptr) || (getDescribedFunctionTemplate() != nullptr)) return false; - + const ParmVarDecl *Param = getParamDecl(0); - - // Do we have a reference type? + + // Do we have a reference type? const auto *ParamRefType = Param->getType()->getAs<ReferenceType>(); if (!ParamRefType) return false; - + // Is it a reference to our class type? ASTContext &Context = getASTContext(); - + CanQualType PointeeType = Context.getCanonicalType(ParamRefType->getPointeeType()); - CanQualType ClassTy + CanQualType ClassTy = Context.getCanonicalType(Context.getTagDeclType(getParent())); if (PointeeType.getUnqualifiedType() != ClassTy) return false; - + // FIXME: other qualifiers? - + // We have a copy or move constructor. TypeQuals = PointeeType.getCVRQualifiers(); - return true; + return true; } bool CXXConstructorDecl::isConvertingConstructor(bool AllowExplicit) const { @@ -2379,14 +2379,14 @@ bool CXXConstructorDecl::isSpecializationCopyingObject() const { ASTContext &Context = getASTContext(); CanQualType ParamType = Context.getCanonicalType(Param->getType()); - + // Is it the same as our class type? - CanQualType ClassTy + CanQualType ClassTy = Context.getCanonicalType(Context.getTagDeclType(getParent())); if (ParamType.getUnqualifiedType() != ClassTy) return false; - - return true; + + return true; } void CXXDestructorDecl::anchor() {} diff --git a/lib/AST/DeclObjC.cpp b/lib/AST/DeclObjC.cpp index 5db045099997..01fd10429fc1 100644 --- a/lib/AST/DeclObjC.cpp +++ b/lib/AST/DeclObjC.cpp @@ -51,7 +51,7 @@ void ObjCListBase::set(void *const* InList, unsigned Elts, ASTContext &Ctx) { memcpy(List, InList, sizeof(void*)*Elts); } -void ObjCProtocolList::set(ObjCProtocolDecl* const* InList, unsigned Elts, +void ObjCProtocolList::set(ObjCProtocolDecl* const* InList, unsigned Elts, const SourceLocation *Locs, ASTContext &Ctx) { if (Elts == 0) return; @@ -145,7 +145,7 @@ bool ObjCContainerDecl::HasUserDeclaredSetterMethod( break; } } - + // Also look into protocols, for a user declared instance method. for (const auto *Proto : ID->all_referenced_protocols()) if (Proto->HasUserDeclaredSetterMethod(Property)) @@ -235,7 +235,7 @@ ObjCPropertyDecl *ObjCContainerDecl::FindPropertyDeclaration( if (Def->isHidden()) return nullptr; } - + // Search the extensions of a class first; they override what's in // the class itself. if (const auto *ClassDecl = dyn_cast<ObjCInterfaceDecl>(this)) { @@ -332,7 +332,7 @@ ObjCInterfaceDecl *ObjCInterfaceDecl::getSuperClass() const { // FIXME: Should make sure no callers ever do this. if (!hasDefinition()) return nullptr; - + if (data().ExternallyCompleted) LoadExternalDefinition(); @@ -351,7 +351,7 @@ ObjCInterfaceDecl *ObjCInterfaceDecl::getSuperClass() const { SourceLocation ObjCInterfaceDecl::getSuperClassLoc() const { if (TypeSourceInfo *superTInfo = getSuperClassTInfo()) return superTInfo->getTypeLoc().getLocStart(); - + return SourceLocation(); } @@ -429,12 +429,12 @@ void ObjCInterfaceDecl::mergeClassExtensionProtocolList( if (data().ExternallyCompleted) LoadExternalDefinition(); - if (data().AllReferencedProtocols.empty() && + if (data().AllReferencedProtocols.empty() && data().ReferencedProtocols.empty()) { data().AllReferencedProtocols.set(ExtList, ExtNum, C); return; } - + // Check for duplicate protocol in class's protocol list. // This is O(n*m). But it is extremely rare and number of protocols in // class or its extension are very few. @@ -446,7 +446,7 @@ void ObjCInterfaceDecl::mergeClassExtensionProtocolList( if (C.ProtocolCompatibleWithProtocol(ProtoInExtension, Proto)) { protocolExists = true; break; - } + } } // Do we want to warn on a protocol in extension class which // already exist in the class? Probably not. @@ -633,7 +633,7 @@ ObjCIvarDecl *ObjCInterfaceDecl::lookupInstanceVariable(IdentifierInfo *ID, return I; } } - + ClassDecl = ClassDecl->getSuperClass(); } return nullptr; @@ -673,7 +673,7 @@ ObjCInterfaceDecl::lookupNestedProtocol(IdentifierInfo *Name) { /// the class, its categories, and its super classes (using a linear search). /// When argument category "C" is specified, any implicit method found /// in this category is ignored. -ObjCMethodDecl *ObjCInterfaceDecl::lookupMethod(Selector Sel, +ObjCMethodDecl *ObjCInterfaceDecl::lookupMethod(Selector Sel, bool isInstance, bool shallowCategoryLookup, bool followSuper, @@ -693,7 +693,7 @@ ObjCMethodDecl *ObjCInterfaceDecl::lookupMethod(Selector Sel, // 1. Look through primary class. if ((MethodDecl = ClassDecl->getMethod(Sel, isInstance))) return MethodDecl; - + // 2. Didn't find one yet - now look through categories. for (const auto *Cat : ClassDecl->visible_categories()) if ((MethodDecl = Cat->getMethod(Sel, isInstance))) @@ -704,7 +704,7 @@ ObjCMethodDecl *ObjCInterfaceDecl::lookupMethod(Selector Sel, for (const auto *I : ClassDecl->protocols()) if ((MethodDecl = I->lookupMethod(Sel, isInstance))) return MethodDecl; - + // 4. Didn't find one yet - now look through categories' protocols if (!shallowCategoryLookup) for (const auto *Cat : ClassDecl->visible_categories()) { @@ -716,8 +716,8 @@ ObjCMethodDecl *ObjCInterfaceDecl::lookupMethod(Selector Sel, if (C != Cat || !MethodDecl->isImplicit()) return MethodDecl; } - - + + if (!followSuper) return nullptr; @@ -742,7 +742,7 @@ ObjCMethodDecl *ObjCInterfaceDecl::lookupPrivateMethod( ObjCMethodDecl *Method = nullptr; if (ObjCImplementationDecl *ImpDecl = getImplementation()) - Method = Instance ? ImpDecl->getInstanceMethod(Sel) + Method = Instance ? ImpDecl->getInstanceMethod(Sel) : ImpDecl->getClassMethod(Sel); // Look through local category implementations associated with the class. @@ -990,12 +990,12 @@ ObjCMethodFamily ObjCMethodDecl::getMethodFamily() const { if (!isInstanceMethod()) family = OMF_None; break; - + case OMF_initialize: if (isInstanceMethod() || !getReturnType()->isVoidType()) family = OMF_None; break; - + case OMF_performSelector: if (!isInstanceMethod() || !getReturnType()->isObjCIdType()) family = OMF_None; @@ -1021,7 +1021,7 @@ ObjCMethodFamily ObjCMethodDecl::getMethodFamily() const { } } break; - + } // Cache the result. @@ -1441,11 +1441,11 @@ ObjCInterfaceDecl::ObjCInterfaceDecl(const ASTContext &C, DeclContext *DC, : ObjCContainerDecl(ObjCInterface, DC, Id, CLoc, AtLoc), redeclarable_base(C) { setPreviousDecl(PrevDecl); - + // Copy the 'data' pointer over. if (PrevDecl) Data = PrevDecl->Data; - + setImplicit(IsInternal); setTypeParamList(typeParamList); @@ -1459,9 +1459,9 @@ void ObjCInterfaceDecl::LoadExternalDefinition() const { } void ObjCInterfaceDecl::setExternallyCompleted() { - assert(getASTContext().getExternalSource() && + assert(getASTContext().getExternalSource() && "Class can't be externally completed without an external source"); - assert(hasDefinition() && + assert(hasDefinition() && "Forward declarations can't be externally completed"); data().ExternallyCompleted = true; } @@ -1496,7 +1496,7 @@ ObjCImplementationDecl::getObjCRuntimeNameAsString() const { if (ObjCInterfaceDecl *ID = const_cast<ObjCImplementationDecl*>(this)->getClassInterface()) return ID->getObjCRuntimeNameAsString(); - + return getName(); } @@ -1504,11 +1504,11 @@ ObjCImplementationDecl *ObjCInterfaceDecl::getImplementation() const { if (const ObjCInterfaceDecl *Def = getDefinition()) { if (data().ExternallyCompleted) LoadExternalDefinition(); - + return getASTContext().getObjCImplementation( const_cast<ObjCInterfaceDecl*>(Def)); } - + // FIXME: Should make sure no callers ever do this. return nullptr; } @@ -1576,7 +1576,7 @@ ObjCIvarDecl *ObjCInterfaceDecl::all_declared_ivar_begin() { // cached and complete! if (!data().IvarListMissingImplementation) return data().IvarList; - + if (ObjCImplementationDecl *ImplDecl = getImplementation()) { data().IvarListMissingImplementation = false; if (!ImplDecl->ivar_empty()) { @@ -1593,7 +1593,7 @@ ObjCIvarDecl *ObjCInterfaceDecl::all_declared_ivar_begin() { curIvar->setNextIvar(IV); curIvar = IV; } - + if (!layout.empty()) { // Order synthesized ivars by their size. std::stable_sort(layout.begin(), layout.end()); @@ -1659,7 +1659,7 @@ bool ObjCInterfaceDecl::ClassImplementsProtocol(ObjCProtocolDecl *lProto, bool RHSIsQualifiedID) { if (!hasDefinition()) return false; - + ObjCInterfaceDecl *IDecl = this; // 1st, look up the class. for (auto *PI : IDecl->protocols()){ @@ -1869,7 +1869,7 @@ void ObjCProtocolDecl::allocateDefinitionData() { void ObjCProtocolDecl::startDefinition() { allocateDefinitionData(); - + // Update all of the declarations with a pointer to the definition. for (auto *RD : redecls()) RD->Data = this->Data; @@ -1926,7 +1926,7 @@ ObjCProtocolDecl::getObjCRuntimeNameAsString() const { void ObjCCategoryDecl::anchor() {} ObjCCategoryDecl::ObjCCategoryDecl(DeclContext *DC, SourceLocation AtLoc, - SourceLocation ClassNameLoc, + SourceLocation ClassNameLoc, SourceLocation CategoryNameLoc, IdentifierInfo *Id, ObjCInterfaceDecl *IDecl, ObjCTypeParamList *typeParamList, @@ -2008,7 +2008,7 @@ ObjCCategoryImplDecl::Create(ASTContext &C, DeclContext *DC, atStartLoc, CategoryNameLoc); } -ObjCCategoryImplDecl *ObjCCategoryImplDecl::CreateDeserialized(ASTContext &C, +ObjCCategoryImplDecl *ObjCCategoryImplDecl::CreateDeserialized(ASTContext &C, unsigned ID) { return new (C, ID) ObjCCategoryImplDecl(nullptr, nullptr, nullptr, SourceLocation(), SourceLocation(), diff --git a/lib/AST/DeclPrinter.cpp b/lib/AST/DeclPrinter.cpp index d3d9c23cca6e..09e22f19f87a 100644 --- a/lib/AST/DeclPrinter.cpp +++ b/lib/AST/DeclPrinter.cpp @@ -44,7 +44,7 @@ namespace { /// /// \param Quals The Objective-C declaration qualifiers. /// \param T The type to print. - void PrintObjCMethodType(ASTContext &Ctx, Decl::ObjCDeclQualifier Quals, + void PrintObjCMethodType(ASTContext &Ctx, Decl::ObjCDeclQualifier Quals, QualType T); void PrintObjCTypeParams(ObjCTypeParamList *Params); @@ -196,7 +196,7 @@ LLVM_DUMP_METHOD void DeclContext::dumpDeclContext() const { const DeclContext *DC = this; while (!DC->isTranslationUnit()) DC = DC->getParent(); - + ASTContext &Ctx = cast<TranslationUnitDecl>(DC)->getASTContext(); DeclPrinter Printer(llvm::errs(), Ctx.getPrintingPolicy(), Ctx, 0); Printer.VisitDeclContext(const_cast<DeclContext *>(this), /*Indent=*/false); @@ -482,7 +482,7 @@ void DeclPrinter::VisitTranslationUnitDecl(TranslationUnitDecl *D) { void DeclPrinter::VisitTypedefDecl(TypedefDecl *D) { if (!Policy.SuppressSpecifiers) { Out << "typedef "; - + if (D->isModulePrivate()) Out << "__module_private__ "; } @@ -641,7 +641,7 @@ void DeclPrinter::VisitFunctionDecl(FunctionDecl *D) { } Proto += ")"; - + if (FT) { if (FT->isConst()) Proto += " const"; @@ -666,7 +666,7 @@ void DeclPrinter::VisitFunctionDecl(FunctionDecl *D) { Proto += " throw("; if (FT->getExceptionSpecType() == EST_MSAny) Proto += "..."; - else + else for (unsigned I = 0, N = FT->getNumExceptions(); I != N; ++I) { if (I) Proto += ", "; @@ -1141,8 +1141,8 @@ void DeclPrinter::VisitClassTemplatePartialSpecializationDecl( // Objective-C declarations //---------------------------------------------------------------------------- -void DeclPrinter::PrintObjCMethodType(ASTContext &Ctx, - Decl::ObjCDeclQualifier Quals, +void DeclPrinter::PrintObjCMethodType(ASTContext &Ctx, + Decl::ObjCDeclQualifier Quals, QualType T) { Out << '('; if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_In) @@ -1161,7 +1161,7 @@ void DeclPrinter::PrintObjCMethodType(ASTContext &Ctx, if (auto nullability = AttributedType::stripOuterNullability(T)) Out << getNullabilitySpelling(*nullability, true) << ' '; } - + Out << Ctx.getUnqualifiedObjCPointerType(T).getAsString(Policy); Out << ')'; } @@ -1216,7 +1216,7 @@ void DeclPrinter::VisitObjCMethodDecl(ObjCMethodDecl *OMD) { if (lastPos != 0) Out << " "; Out << name.substr(lastPos, pos - lastPos) << ':'; - PrintObjCMethodType(OMD->getASTContext(), + PrintObjCMethodType(OMD->getASTContext(), PI->getObjCDeclQualifier(), PI->getType()); Out << *PI; @@ -1228,7 +1228,7 @@ void DeclPrinter::VisitObjCMethodDecl(ObjCMethodDecl *OMD) { if (OMD->isVariadic()) Out << ", ..."; - + prettyPrintAttributes(OMD); if (OMD->getBody() && !Policy.TerseOutput) { @@ -1248,7 +1248,7 @@ void DeclPrinter::VisitObjCImplementationDecl(ObjCImplementationDecl *OID) { Out << "@implementation " << I << " : " << *SID; else Out << "@implementation " << I; - + if (OID->ivar_size() > 0) { Out << "{\n"; eolnOut = true; @@ -1290,7 +1290,7 @@ void DeclPrinter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *OID) { if (auto TypeParams = OID->getTypeParamListAsWritten()) { PrintObjCTypeParams(TypeParams); } - + if (SID) Out << " : " << QualType(OID->getSuperClassType(), 0).getAsString(Policy); @@ -1369,7 +1369,7 @@ void DeclPrinter::VisitObjCCategoryDecl(ObjCCategoryDecl *PID) { Indentation -= Policy.Indentation; Out << "}\n"; } - + VisitDeclContext(PID, false); Out << "@end"; @@ -1448,7 +1448,7 @@ void DeclPrinter::VisitObjCPropertyDecl(ObjCPropertyDecl *PDecl) { Out << (first ? ' ' : ',') << "atomic"; first = false; } - + if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nullability) { if (auto nullability = AttributedType::stripOuterNullability(T)) { diff --git a/lib/AST/DeclTemplate.cpp b/lib/AST/DeclTemplate.cpp index 8854f7879ac6..848427e7f9d9 100644 --- a/lib/AST/DeclTemplate.cpp +++ b/lib/AST/DeclTemplate.cpp @@ -117,7 +117,7 @@ unsigned TemplateParameterList::getMinRequiredArguments() const { unsigned TemplateParameterList::getDepth() const { if (size() == 0) return 0; - + const NamedDecl *FirstParm = getParam(0); if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(FirstParm)) return TTP->getDepth(); @@ -338,13 +338,13 @@ llvm::FoldingSetVector<ClassTemplateSpecializationDecl> & ClassTemplateDecl::getSpecializations() const { LoadLazySpecializations(); return getCommonPtr()->Specializations; -} +} llvm::FoldingSetVector<ClassTemplatePartialSpecializationDecl> & ClassTemplateDecl::getPartialSpecializations() { LoadLazySpecializations(); return getCommonPtr()->PartialSpecializations; -} +} RedeclarableTemplateDecl::CommonBase * ClassTemplateDecl::newCommon(ASTContext &C) const { @@ -427,11 +427,11 @@ ClassTemplateDecl::getInjectedClassNameSpecialization() { return CommonPtr->InjectedClassNameType; // C++0x [temp.dep.type]p2: - // The template argument list of a primary template is a template argument + // The template argument list of a primary template is a template argument // list in which the nth template argument has the value of the nth template - // parameter of the class template. If the nth template parameter is a - // template parameter pack (14.5.3), the nth template argument is a pack - // expansion (14.5.3) whose pattern is the name of the template parameter + // parameter of the class template. If the nth template parameter is a + // template parameter pack (14.5.3), the nth template argument is a pack + // expansion (14.5.3) whose pattern is the name of the template parameter // pack. ASTContext &Context = getASTContext(); TemplateParameterList *Params = getTemplateParameters(); diff --git a/lib/AST/DeclarationName.cpp b/lib/AST/DeclarationName.cpp index 31bae93c3cb5..9866d92f61eb 100644 --- a/lib/AST/DeclarationName.cpp +++ b/lib/AST/DeclarationName.cpp @@ -114,14 +114,14 @@ static int compareInt(unsigned A, unsigned B) { int DeclarationName::compare(DeclarationName LHS, DeclarationName RHS) { if (LHS.getNameKind() != RHS.getNameKind()) return (LHS.getNameKind() < RHS.getNameKind() ? -1 : 1); - + switch (LHS.getNameKind()) { case DeclarationName::Identifier: { IdentifierInfo *LII = LHS.getAsIdentifierInfo(); IdentifierInfo *RII = RHS.getAsIdentifierInfo(); if (!LII) return RII ? -1 : 0; if (!RII) return 1; - + return LII->getName().compare(RII->getName()); } @@ -148,7 +148,7 @@ int DeclarationName::compare(DeclarationName LHS, DeclarationName RHS) { return compareInt(LN, RN); } - + case DeclarationName::CXXConstructorName: case DeclarationName::CXXDestructorName: case DeclarationName::CXXConversionFunctionName: @@ -171,7 +171,7 @@ int DeclarationName::compare(DeclarationName LHS, DeclarationName RHS) { case DeclarationName::CXXLiteralOperatorName: return LHS.getCXXLiteralIdentifier()->getName().compare( RHS.getCXXLiteralIdentifier()->getName()); - + case DeclarationName::CXXUsingDirective: return 0; } @@ -565,7 +565,7 @@ DeclarationNameTable::getCXXLiteralOperatorName(IdentifierInfo *II) { if (CXXLiteralOperatorIdName *Name = LiteralNames->FindNodeOrInsertPos(ID, InsertPos)) return DeclarationName (Name); - + CXXLiteralOperatorIdName *LiteralName = new (Ctx) CXXLiteralOperatorIdName; LiteralName->ExtraKindOrNumArgs = DeclarationNameExtra::CXXLiteralOperator; LiteralName->ID = II; @@ -636,13 +636,13 @@ bool DeclarationNameInfo::isInstantiationDependent() const { case DeclarationName::CXXUsingDirective: case DeclarationName::CXXDeductionGuideName: return false; - + case DeclarationName::CXXConstructorName: case DeclarationName::CXXDestructorName: case DeclarationName::CXXConversionFunctionName: if (TypeSourceInfo *TInfo = LocInfo.NamedType.TInfo) return TInfo->getType()->isInstantiationDependentType(); - + return Name.getCXXNameType()->isInstantiationDependentType(); } llvm_unreachable("All name kinds handled."); @@ -689,7 +689,7 @@ void DeclarationNameInfo::printName(raw_ostream &OS) const { llvm_unreachable("Unexpected declaration name kind"); } -SourceLocation DeclarationNameInfo::getEndLoc() const { +SourceLocation DeclarationNameInfo::getEndLocPrivate() const { switch (Name.getNameKind()) { case DeclarationName::Identifier: case DeclarationName::CXXDeductionGuideName: diff --git a/lib/AST/Expr.cpp b/lib/AST/Expr.cpp index 193efa4e097d..7556c76c38bd 100644 --- a/lib/AST/Expr.cpp +++ b/lib/AST/Expr.cpp @@ -137,9 +137,9 @@ bool Expr::isKnownToHaveBooleanValue() const { // If this value has _Bool type, it is obvious 0/1. if (E->getType()->isBooleanType()) return true; - // If this is a non-scalar-integer type, we don't care enough to try. + // If this is a non-scalar-integer type, we don't care enough to try. if (!E->getType()->isIntegralOrEnumerationType()) return false; - + if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { switch (UO->getOpcode()) { case UO_Plus: @@ -150,12 +150,12 @@ bool Expr::isKnownToHaveBooleanValue() const { return false; } } - + // Only look through implicit casts. If the user writes // '(int) (a && b)' treat it as an arbitrary int. if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) return CE->getSubExpr()->isKnownToHaveBooleanValue(); - + if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { switch (BO->getOpcode()) { default: return false; @@ -168,24 +168,24 @@ bool Expr::isKnownToHaveBooleanValue() const { case BO_LAnd: // AND operator. case BO_LOr: // Logical OR operator. return true; - + case BO_And: // Bitwise AND operator. case BO_Xor: // Bitwise XOR operator. case BO_Or: // Bitwise OR operator. // Handle things like (x==2)|(y==12). return BO->getLHS()->isKnownToHaveBooleanValue() && BO->getRHS()->isKnownToHaveBooleanValue(); - + case BO_Comma: case BO_Assign: return BO->getRHS()->isKnownToHaveBooleanValue(); } } - + if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) return CO->getTrueExpr()->isKnownToHaveBooleanValue() && CO->getFalseExpr()->isKnownToHaveBooleanValue(); - + return false; } @@ -230,7 +230,7 @@ SourceLocation Expr::getExprLoc() const { // Primary Expressions. //===----------------------------------------------------------------------===// -/// Compute the type-, value-, and instantiation-dependence of a +/// Compute the type-, value-, and instantiation-dependence of a /// declaration reference /// based on the declaration being referenced. static void computeDeclRefDependence(const ASTContext &Ctx, NamedDecl *D, @@ -259,9 +259,9 @@ static void computeDeclRefDependence(const ASTContext &Ctx, NamedDecl *D, } else if (T->isInstantiationDependentType()) { InstantiationDependent = true; } - + // (TD) - a conversion-function-id that specifies a dependent type - if (D->getDeclName().getNameKind() + if (D->getDeclName().getNameKind() == DeclarationName::CXXConversionFunctionName) { QualType T = D->getDeclName().getCXXNameType(); if (T->isDependentType()) { @@ -270,18 +270,18 @@ static void computeDeclRefDependence(const ASTContext &Ctx, NamedDecl *D, InstantiationDependent = true; return; } - + if (T->isInstantiationDependentType()) InstantiationDependent = true; } - + // (VD) - the name of a non-type template parameter, if (isa<NonTypeTemplateParmDecl>(D)) { ValueDependent = true; InstantiationDependent = true; return; } - + // (VD) - a constant with integral or enumeration type and is // initialized with an expression that is value-dependent. // (VD) - a constant with literal type and is initialized with an @@ -302,10 +302,10 @@ static void computeDeclRefDependence(const ASTContext &Ctx, NamedDecl *D, } } - // (VD) - FIXME: Missing from the standard: - // - a member function or a static data member of the current + // (VD) - FIXME: Missing from the standard: + // - a member function or a static data member of the current // instantiation - if (Var->isStaticDataMember() && + if (Var->isStaticDataMember() && Var->getDeclContext()->isDependentContext()) { ValueDependent = true; InstantiationDependent = true; @@ -313,12 +313,12 @@ static void computeDeclRefDependence(const ASTContext &Ctx, NamedDecl *D, if (TInfo->getType()->isIncompleteArrayType()) TypeDependent = true; } - + return; } - - // (VD) - FIXME: Missing from the standard: - // - a member function or a static data member of the current + + // (VD) - FIXME: Missing from the standard: + // - a member function or a static data member of the current // instantiation if (isa<CXXMethodDecl>(D) && D->getDeclContext()->isDependentContext()) { ValueDependent = true; @@ -625,7 +625,7 @@ std::string PredefinedExpr::ComputeName(IdentType IT, const Decl *CurrentDecl) { llvm::raw_string_ostream TOut(TemplateParams); for (SpecsTy::reverse_iterator I = Specs.rbegin(), E = Specs.rend(); I != E; ++I) { - const TemplateParameterList *Params + const TemplateParameterList *Params = (*I)->getSpecializedTemplate()->getTemplateParameters(); const TemplateArgumentList &Args = (*I)->getTemplateArgs(); assert(Params->size() == Args.size()); @@ -638,10 +638,10 @@ std::string PredefinedExpr::ComputeName(IdentType IT, const Decl *CurrentDecl) { } } - FunctionTemplateSpecializationInfo *FSI + FunctionTemplateSpecializationInfo *FSI = FD->getTemplateSpecializationInfo(); if (FSI && !FSI->isExplicitSpecialization()) { - const TemplateParameterList* Params + const TemplateParameterList* Params = FSI->getTemplate()->getTemplateParameters(); const TemplateArgumentList* Args = FSI->TemplateArguments; assert(Params->size() == Args->size()); @@ -942,7 +942,7 @@ void StringLiteral::outputString(raw_ostream &OS) const { // Convert UTF-16 surrogate pairs back to codepoints before rendering. // Leave invalid surrogates alone; we'll use \x for those. - if (getKind() == UTF16 && I != N - 1 && Char >= 0xd800 && + if (getKind() == UTF16 && I != N - 1 && Char >= 0xd800 && Char <= 0xdbff) { uint32_t Trail = getCodeUnit(I + 1); if (Trail >= 0xdc00 && Trail <= 0xdfff) { @@ -1025,7 +1025,7 @@ void StringLiteral::setString(const ASTContext &C, StringRef Str, // code unit size and endianness for the type of string. this->Kind = Kind; this->IsPascal = IsPascal; - + CharByteWidth = mapCharByteWidth(C.getTargetInfo(),Kind); assert((Str.size()%CharByteWidth == 0) && "size of data must be multiple of CharByteWidth"); @@ -1092,7 +1092,7 @@ StringLiteral::getLocationOfByte(unsigned ByteNo, const SourceManager &SM, while (1) { assert(TokNo < getNumConcatenated() && "Invalid byte number!"); SourceLocation StrTokLoc = getStrTokenLoc(TokNo); - + // Get the spelling of the string so that we can get the data that makes up // the string literal, not the identifier for the macro it is potentially // expanded through. @@ -1112,17 +1112,17 @@ StringLiteral::getLocationOfByte(unsigned ByteNo, const SourceManager &SM, } const char *StrData = Buffer.data()+LocInfo.second; - + // Create a lexer starting at the beginning of this token. Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), Features, Buffer.begin(), StrData, Buffer.end()); Token TheTok; TheLexer.LexFromRawLexer(TheTok); - + // Use the StringLiteralParser to compute the length of the string in bytes. StringLiteralParser SLP(TheTok, SM, Features, Target); unsigned TokNumBytes = SLP.GetStringLength(); - + // If the byte is in this token, return the location of the byte. if (ByteNo < TokNumBytes || (ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) { @@ -1258,12 +1258,12 @@ Decl *CallExpr::getCalleeDecl() { Decl *Expr::getReferencedDeclOfCallee() { Expr *CEE = IgnoreParenImpCasts(); - + while (SubstNonTypeTemplateParmExpr *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(CEE)) { CEE = NTTP->getReplacement()->IgnoreParenCasts(); } - + // If we're calling a dereference, look at the pointer instead. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CEE)) { if (BO->isPtrMemOp()) @@ -1379,7 +1379,7 @@ SourceLocation CallExpr::getLocEnd() const { OffsetOfExpr *OffsetOfExpr::Create(const ASTContext &C, QualType type, SourceLocation OperatorLoc, - TypeSourceInfo *tsi, + TypeSourceInfo *tsi, ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs, SourceLocation RParenLoc) { @@ -1402,17 +1402,17 @@ OffsetOfExpr::OffsetOfExpr(const ASTContext &C, QualType type, ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs, SourceLocation RParenLoc) : Expr(OffsetOfExprClass, type, VK_RValue, OK_Ordinary, - /*TypeDependent=*/false, + /*TypeDependent=*/false, /*ValueDependent=*/tsi->getType()->isDependentType(), tsi->getType()->isInstantiationDependentType(), tsi->getType()->containsUnexpandedParameterPack()), - OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi), + OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi), NumComps(comps.size()), NumExprs(exprs.size()) { for (unsigned i = 0; i != comps.size(); ++i) { setComponent(i, comps[i]); } - + for (unsigned i = 0; i != exprs.size(); ++i) { if (exprs[i]->isTypeDependent() || exprs[i]->isValueDependent()) ExprBits.ValueDependent = true; @@ -1427,7 +1427,7 @@ IdentifierInfo *OffsetOfNode::getFieldName() const { assert(getKind() == Field || getKind() == Identifier); if (getKind() == Field) return getField()->getIdentifier(); - + return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask); } @@ -1497,11 +1497,11 @@ MemberExpr *MemberExpr::Create( E->setValueDependent(true); E->setTypeDependent(true); E->setInstantiationDependent(true); - } - else if (QualifierLoc && - QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent()) + } + else if (QualifierLoc && + QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent()) E->setInstantiationDependent(true); - + E->HasQualifierOrFoundDecl = true; MemberExprNameQualifier *NQ = @@ -1582,9 +1582,9 @@ bool CastExpr::CastConsistency() const { // Otherwise, we should only have block and ObjC pointer casts // here if they stay within the type kind. if (!getType()->isPointerType()) { - assert(getType()->isObjCObjectPointerType() == + assert(getType()->isObjCObjectPointerType() == getSubExpr()->getType()->isObjCObjectPointerType()); - assert(getType()->isBlockPointerType() == + assert(getType()->isBlockPointerType() == getSubExpr()->getType()->isBlockPointerType()); } goto CheckNoBasePath; @@ -1708,11 +1708,11 @@ Expr *CastExpr::getSubExprAsWritten() { if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr)) SubExpr = MCE->getImplicitObjectArgument(); } - + // If the subexpression we're left with is an implicit cast, look // through that, too. - } while ((E = dyn_cast<ImplicitCastExpr>(SubExpr))); - + } while ((E = dyn_cast<ImplicitCastExpr>(SubExpr))); + return const_cast<Expr*>(SubExpr); } @@ -1734,6 +1734,21 @@ NamedDecl *CastExpr::getConversionFunction() const { return nullptr; } +CastExpr::BasePathSizeTy *CastExpr::BasePathSize() { + assert(!path_empty()); + switch (getStmtClass()) { +#define ABSTRACT_STMT(x) +#define CASTEXPR(Type, Base) \ + case Stmt::Type##Class: \ + return static_cast<Type *>(this) \ + ->getTrailingObjects<CastExpr::BasePathSizeTy>(); +#define STMT(Type, Base) +#include "clang/AST/StmtNodes.inc" + default: + llvm_unreachable("non-cast expressions not possible here"); + } +} + CXXBaseSpecifier **CastExpr::path_buffer() { switch (getStmtClass()) { #define ABSTRACT_STMT(x) @@ -1772,7 +1787,9 @@ ImplicitCastExpr *ImplicitCastExpr::Create(const ASTContext &C, QualType T, const CXXCastPath *BasePath, ExprValueKind VK) { unsigned PathSize = (BasePath ? BasePath->size() : 0); - void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize)); + void *Buffer = + C.Allocate(totalSizeToAlloc<CastExpr::BasePathSizeTy, CXXBaseSpecifier *>( + PathSize ? 1 : 0, PathSize)); ImplicitCastExpr *E = new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, VK); if (PathSize) @@ -1783,7 +1800,9 @@ ImplicitCastExpr *ImplicitCastExpr::Create(const ASTContext &C, QualType T, ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(const ASTContext &C, unsigned PathSize) { - void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize)); + void *Buffer = + C.Allocate(totalSizeToAlloc<CastExpr::BasePathSizeTy, CXXBaseSpecifier *>( + PathSize ? 1 : 0, PathSize)); return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize); } @@ -1794,7 +1813,9 @@ CStyleCastExpr *CStyleCastExpr::Create(const ASTContext &C, QualType T, TypeSourceInfo *WrittenTy, SourceLocation L, SourceLocation R) { unsigned PathSize = (BasePath ? BasePath->size() : 0); - void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize)); + void *Buffer = + C.Allocate(totalSizeToAlloc<CastExpr::BasePathSizeTy, CXXBaseSpecifier *>( + PathSize ? 1 : 0, PathSize)); CStyleCastExpr *E = new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, R); if (PathSize) @@ -1805,7 +1826,9 @@ CStyleCastExpr *CStyleCastExpr::Create(const ASTContext &C, QualType T, CStyleCastExpr *CStyleCastExpr::CreateEmpty(const ASTContext &C, unsigned PathSize) { - void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize)); + void *Buffer = + C.Allocate(totalSizeToAlloc<CastExpr::BasePathSizeTy, CXXBaseSpecifier *>( + PathSize ? 1 : 0, PathSize)); return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize); } @@ -1933,7 +1956,7 @@ InitListExpr::InitListExpr(const ASTContext &C, SourceLocation lbraceloc, if (initExprs[I]->containsUnexpandedParameterPack()) ExprBits.ContainsUnexpandedParameterPack = true; } - + InitExprs.insert(C, InitExprs.end(), initExprs.begin(), initExprs.end()); } @@ -2023,12 +2046,12 @@ SourceLocation InitListExpr::getLocStart() const { if (Beg.isInvalid()) { // Find the first non-null initializer. for (InitExprsTy::const_iterator I = InitExprs.begin(), - E = InitExprs.end(); + E = InitExprs.end(); I != E; ++I) { if (Stmt *S = *I) { Beg = S->getLocStart(); break; - } + } } } return Beg; @@ -2079,7 +2102,7 @@ Stmt *BlockExpr::getBody() { /// be warned about if the result is unused. If so, fill in Loc and Ranges /// with location to warn on and the source range[s] to report with the /// warning. -bool Expr::isUnusedResultAWarning(const Expr *&WarnE, SourceLocation &Loc, +bool Expr::isUnusedResultAWarning(const Expr *&WarnE, SourceLocation &Loc, SourceRange &R1, SourceRange &R2, ASTContext &Ctx) const { // Don't warn if the expr is type dependent. The type could end up @@ -2436,7 +2459,7 @@ bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const { return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx); case DeclRefExprClass: { const Decl *D = cast<DeclRefExpr>(E)->getDecl(); - + if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { if (VD->hasGlobalStorage()) return true; @@ -2526,7 +2549,7 @@ Expr *Expr::IgnoreParenCasts() { E = P->getSubExpr(); continue; } - if (MaterializeTemporaryExpr *Materialize + if (MaterializeTemporaryExpr *Materialize = dyn_cast<MaterializeTemporaryExpr>(E)) { E = Materialize->GetTemporaryExpr(); continue; @@ -2535,7 +2558,7 @@ Expr *Expr::IgnoreParenCasts() { = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) { E = NTTP->getReplacement(); continue; - } + } return E; } } @@ -2574,7 +2597,7 @@ Expr *Expr::IgnoreParenLValueCasts() { E = P->getSubExpr(); continue; } - } else if (MaterializeTemporaryExpr *Materialize + } else if (MaterializeTemporaryExpr *Materialize = dyn_cast<MaterializeTemporaryExpr>(E)) { E = Materialize->GetTemporaryExpr(); continue; @@ -2613,7 +2636,7 @@ Expr *Expr::IgnoreParenImpCasts() { E = P->getSubExpr(); continue; } - if (MaterializeTemporaryExpr *Materialize + if (MaterializeTemporaryExpr *Materialize = dyn_cast<MaterializeTemporaryExpr>(E)) { E = Materialize->GetTemporaryExpr(); continue; @@ -2668,7 +2691,7 @@ Expr *Expr::IgnoreParenNoopCasts(ASTContext &Ctx) { E = NTTP->getReplacement(); continue; } - + return E; } } @@ -2680,7 +2703,7 @@ bool Expr::isDefaultArgument() const { while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) E = ICE->getSubExprAsWritten(); - + return isa<CXXDefaultArgExpr>(E); } @@ -2756,43 +2779,43 @@ bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const { bool Expr::isImplicitCXXThis() const { const Expr *E = this; - + // Strip away parentheses and casts we don't care about. while (true) { if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) { E = Paren->getSubExpr(); continue; } - + if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { if (ICE->getCastKind() == CK_NoOp || ICE->getCastKind() == CK_LValueToRValue || - ICE->getCastKind() == CK_DerivedToBase || + ICE->getCastKind() == CK_DerivedToBase || ICE->getCastKind() == CK_UncheckedDerivedToBase) { E = ICE->getSubExpr(); continue; } } - + if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) { if (UnOp->getOpcode() == UO_Extension) { E = UnOp->getSubExpr(); continue; } } - + if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E)) { E = M->GetTemporaryExpr(); continue; } - + break; } - + if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E)) return This->isImplicit(); - + return false; } @@ -2978,7 +3001,7 @@ bool CallExpr::isBuiltinAssumeFalse(const ASTContext &Ctx) const { if (!FD || (FD->getBuiltinID() != Builtin::BI__assume && FD->getBuiltinID() != Builtin::BI__builtin_assume)) return false; - + const Expr* Arg = getArg(0); bool ArgVal; return !Arg->isValueDependent() && @@ -3289,11 +3312,11 @@ namespace { typedef ConstEvaluatedExprVisitor<NonTrivialCallFinder> Inherited; bool NonTrivial; - + public: explicit NonTrivialCallFinder(const ASTContext &Context) : Inherited(Context), NonTrivial(false) { } - + bool hasNonTrivialCall() const { return NonTrivial; } void VisitCallExpr(const CallExpr *E) { @@ -3305,7 +3328,7 @@ namespace { return; } } - + NonTrivial = true; } @@ -3315,7 +3338,7 @@ namespace { Inherited::VisitStmt(E); return; } - + NonTrivial = true; } @@ -3324,7 +3347,7 @@ namespace { Inherited::VisitStmt(E); return; } - + NonTrivial = true; } }; @@ -3333,10 +3356,10 @@ namespace { bool Expr::hasNonTrivialCall(const ASTContext &Ctx) const { NonTrivialCallFinder Finder(Ctx); Finder.Visit(this); - return Finder.hasNonTrivialCall(); + return Finder.hasNonTrivialCall(); } -/// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null +/// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null /// pointer constant or not, as well as the specific kind of constant detected. /// Null pointer constants can be integer constant expressions with the /// value zero, casts of zero to void*, nullptr (C++0X), or __null @@ -3354,7 +3377,7 @@ Expr::isNullPointerConstant(ASTContext &Ctx, return NPCK_ZeroExpression; else return NPCK_NotNull; - + case NPC_ValueDependentIsNotNull: return NPCK_NotNull; } @@ -3410,7 +3433,7 @@ Expr::isNullPointerConstant(ASTContext &Ctx, } else if (isa<GNUNullExpr>(this)) { // The GNU __null extension is always a null pointer constant. return NPCK_GNUNull; - } else if (const MaterializeTemporaryExpr *M + } else if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(this)) { return M->GetTemporaryExpr()->isNullPointerConstant(Ctx, NPC); } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) { @@ -3431,7 +3454,7 @@ Expr::isNullPointerConstant(ASTContext &Ctx, return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC); } // This expression must be an integer type. - if (!getType()->isIntegerType() || + if (!getType()->isIntegerType() || (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType())) return NPCK_NotNull; @@ -3549,7 +3572,7 @@ FieldDecl *Expr::getSourceBitField() { bool Expr::refersToVectorElement() const { // FIXME: Why do we not just look at the ObjectKind here? const Expr *E = this->IgnoreParens(); - + while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { if (ICE->getValueKind() != VK_RValue && ICE->getCastKind() == CK_NoOp) @@ -3557,7 +3580,7 @@ bool Expr::refersToVectorElement() const { else break; } - + if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E)) return ASE->getBase()->getType()->isVectorType(); @@ -3652,7 +3675,7 @@ void ExtVectorElementExpr::getEncodedElementAccess( ShuffleVectorExpr::ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args, QualType Type, SourceLocation BLoc, - SourceLocation RP) + SourceLocation RP) : Expr(ShuffleVectorExprClass, Type, VK_RValue, OK_Ordinary, Type->isDependentType(), Type->isDependentType(), Type->isInstantiationDependentType(), @@ -3791,11 +3814,11 @@ DesignatedInitExpr::DesignatedInitExpr(const ASTContext &C, QualType Ty, End->isTypeDependent() || End->isValueDependent()) { ExprBits.TypeDependent = ExprBits.ValueDependent = true; ExprBits.InstantiationDependent = true; - } else if (Start->isInstantiationDependent() || + } else if (Start->isInstantiationDependent() || End->isInstantiationDependent()) { ExprBits.InstantiationDependent = true; } - + // Propagate unexpanded parameter packs. if (Start->containsUnexpandedParameterPack() || End->containsUnexpandedParameterPack()) diff --git a/lib/AST/ExprCXX.cpp b/lib/AST/ExprCXX.cpp index 3a204c244f68..93d68ec8e0b2 100644 --- a/lib/AST/ExprCXX.cpp +++ b/lib/AST/ExprCXX.cpp @@ -120,7 +120,7 @@ CXXNewExpr::CXXNewExpr(const ASTContext &C, bool globalNew, if (Array) { if (arraySize->isInstantiationDependent()) ExprBits.InstantiationDependent = true; - + if (arraySize->containsUnexpandedParameterPack()) ExprBits.ContainsUnexpandedParameterPack = true; @@ -210,8 +210,8 @@ PseudoDestructorTypeStorage::PseudoDestructorTypeStorage(TypeSourceInfo *Info) CXXPseudoDestructorExpr::CXXPseudoDestructorExpr(const ASTContext &Context, Expr *Base, bool isArrow, SourceLocation OperatorLoc, - NestedNameSpecifierLoc QualifierLoc, TypeSourceInfo *ScopeType, - SourceLocation ColonColonLoc, SourceLocation TildeLoc, + NestedNameSpecifierLoc QualifierLoc, TypeSourceInfo *ScopeType, + SourceLocation ColonColonLoc, SourceLocation TildeLoc, PseudoDestructorTypeStorage DestroyedType) : Expr(CXXPseudoDestructorExprClass, Context.BoundMemberTy, @@ -230,10 +230,10 @@ CXXPseudoDestructorExpr::CXXPseudoDestructorExpr(const ASTContext &Context, ->isInstantiationDependentType())), // ContainsUnexpandedParameterPack (Base->containsUnexpandedParameterPack() || - (QualifierLoc && + (QualifierLoc && QualifierLoc.getNestedNameSpecifier() ->containsUnexpandedParameterPack()) || - (ScopeType && + (ScopeType && ScopeType->getType()->containsUnexpandedParameterPack()) || (DestroyedType.getTypeSourceInfo() && DestroyedType.getTypeSourceInfo()->getType() @@ -246,7 +246,7 @@ CXXPseudoDestructorExpr::CXXPseudoDestructorExpr(const ASTContext &Context, QualType CXXPseudoDestructorExpr::getDestroyedType() const { if (TypeSourceInfo *TInfo = DestroyedType.getTypeSourceInfo()) return TInfo->getType(); - + return QualType(); } @@ -300,7 +300,7 @@ OverloadExpr::OverloadExpr(StmtClass K, const ASTContext &C, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, - UnresolvedSetIterator Begin, + UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent, bool KnownInstantiationDependent, @@ -393,13 +393,13 @@ DependentScopeDeclRefExpr::DependentScopeDeclRefExpr(QualType T, : Expr(DependentScopeDeclRefExprClass, T, VK_LValue, OK_Ordinary, true, true, (NameInfo.isInstantiationDependent() || - (QualifierLoc && + (QualifierLoc && QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent())), (NameInfo.containsUnexpandedParameterPack() || - (QualifierLoc && + (QualifierLoc && QualifierLoc.getNestedNameSpecifier() ->containsUnexpandedParameterPack()))), - QualifierLoc(QualifierLoc), NameInfo(NameInfo), + QualifierLoc(QualifierLoc), NameInfo(NameInfo), HasTemplateKWAndArgsInfo(Args != nullptr || TemplateKWLoc.isValid()) { if (Args) { @@ -555,11 +555,13 @@ CXXStaticCastExpr *CXXStaticCastExpr::Create(const ASTContext &C, QualType T, CastKind K, Expr *Op, const CXXCastPath *BasePath, TypeSourceInfo *WrittenTy, - SourceLocation L, + SourceLocation L, SourceLocation RParenLoc, SourceRange AngleBrackets) { unsigned PathSize = (BasePath ? BasePath->size() : 0); - void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize)); + void *Buffer = + C.Allocate(totalSizeToAlloc<CastExpr::BasePathSizeTy, CXXBaseSpecifier *>( + PathSize ? 1 : 0, PathSize)); auto *E = new (Buffer) CXXStaticCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, RParenLoc, AngleBrackets); @@ -571,7 +573,9 @@ CXXStaticCastExpr *CXXStaticCastExpr::Create(const ASTContext &C, QualType T, CXXStaticCastExpr *CXXStaticCastExpr::CreateEmpty(const ASTContext &C, unsigned PathSize) { - void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize)); + void *Buffer = + C.Allocate(totalSizeToAlloc<CastExpr::BasePathSizeTy, CXXBaseSpecifier *>( + PathSize ? 1 : 0, PathSize)); return new (Buffer) CXXStaticCastExpr(EmptyShell(), PathSize); } @@ -580,11 +584,13 @@ CXXDynamicCastExpr *CXXDynamicCastExpr::Create(const ASTContext &C, QualType T, CastKind K, Expr *Op, const CXXCastPath *BasePath, TypeSourceInfo *WrittenTy, - SourceLocation L, + SourceLocation L, SourceLocation RParenLoc, SourceRange AngleBrackets) { unsigned PathSize = (BasePath ? BasePath->size() : 0); - void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize)); + void *Buffer = + C.Allocate(totalSizeToAlloc<CastExpr::BasePathSizeTy, CXXBaseSpecifier *>( + PathSize ? 1 : 0, PathSize)); auto *E = new (Buffer) CXXDynamicCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, RParenLoc, AngleBrackets); @@ -596,7 +602,9 @@ CXXDynamicCastExpr *CXXDynamicCastExpr::Create(const ASTContext &C, QualType T, CXXDynamicCastExpr *CXXDynamicCastExpr::CreateEmpty(const ASTContext &C, unsigned PathSize) { - void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize)); + void *Buffer = + C.Allocate(totalSizeToAlloc<CastExpr::BasePathSizeTy, CXXBaseSpecifier *>( + PathSize ? 1 : 0, PathSize)); return new (Buffer) CXXDynamicCastExpr(EmptyShell(), PathSize); } @@ -637,11 +645,13 @@ CXXReinterpretCastExpr * CXXReinterpretCastExpr::Create(const ASTContext &C, QualType T, ExprValueKind VK, CastKind K, Expr *Op, const CXXCastPath *BasePath, - TypeSourceInfo *WrittenTy, SourceLocation L, + TypeSourceInfo *WrittenTy, SourceLocation L, SourceLocation RParenLoc, SourceRange AngleBrackets) { unsigned PathSize = (BasePath ? BasePath->size() : 0); - void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize)); + void *Buffer = + C.Allocate(totalSizeToAlloc<CastExpr::BasePathSizeTy, CXXBaseSpecifier *>( + PathSize ? 1 : 0, PathSize)); auto *E = new (Buffer) CXXReinterpretCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, RParenLoc, AngleBrackets); @@ -653,14 +663,16 @@ CXXReinterpretCastExpr::Create(const ASTContext &C, QualType T, CXXReinterpretCastExpr * CXXReinterpretCastExpr::CreateEmpty(const ASTContext &C, unsigned PathSize) { - void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize)); + void *Buffer = + C.Allocate(totalSizeToAlloc<CastExpr::BasePathSizeTy, CXXBaseSpecifier *>( + PathSize ? 1 : 0, PathSize)); return new (Buffer) CXXReinterpretCastExpr(EmptyShell(), PathSize); } CXXConstCastExpr *CXXConstCastExpr::Create(const ASTContext &C, QualType T, ExprValueKind VK, Expr *Op, TypeSourceInfo *WrittenTy, - SourceLocation L, + SourceLocation L, SourceLocation RParenLoc, SourceRange AngleBrackets) { return new (C) CXXConstCastExpr(T, VK, Op, WrittenTy, L, RParenLoc, AngleBrackets); @@ -676,7 +688,9 @@ CXXFunctionalCastExpr::Create(const ASTContext &C, QualType T, ExprValueKind VK, const CXXCastPath *BasePath, SourceLocation L, SourceLocation R) { unsigned PathSize = (BasePath ? BasePath->size() : 0); - void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize)); + void *Buffer = + C.Allocate(totalSizeToAlloc<CastExpr::BasePathSizeTy, CXXBaseSpecifier *>( + PathSize ? 1 : 0, PathSize)); auto *E = new (Buffer) CXXFunctionalCastExpr(T, VK, Written, K, Op, PathSize, L, R); if (PathSize) @@ -687,7 +701,9 @@ CXXFunctionalCastExpr::Create(const ASTContext &C, QualType T, ExprValueKind VK, CXXFunctionalCastExpr * CXXFunctionalCastExpr::CreateEmpty(const ASTContext &C, unsigned PathSize) { - void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize)); + void *Buffer = + C.Allocate(totalSizeToAlloc<CastExpr::BasePathSizeTy, CXXBaseSpecifier *>( + PathSize ? 1 : 0, PathSize)); return new (Buffer) CXXFunctionalCastExpr(EmptyShell(), PathSize); } @@ -829,7 +845,7 @@ CXXConstructExpr::CXXConstructExpr(const ASTContext &C, StmtClass SC, ZeroInitialization(ZeroInitialization), ConstructKind(ConstructKind) { if (NumArgs) { this->Args = new (C) Stmt*[Args.size()]; - + for (unsigned i = 0; i != Args.size(); ++i) { assert(Args[i] && "NULL argument in CXXConstructExpr"); @@ -839,7 +855,7 @@ CXXConstructExpr::CXXConstructExpr(const ASTContext &C, StmtClass SC, ExprBits.InstantiationDependent = true; if (Args[i]->containsUnexpandedParameterPack()) ExprBits.ContainsUnexpandedParameterPack = true; - + this->Args[i] = Args[i]; } } @@ -852,7 +868,7 @@ LambdaCapture::LambdaCapture(SourceLocation Loc, bool Implicit, unsigned Bits = 0; if (Implicit) Bits |= Capture_Implicit; - + switch (Kind) { case LCK_StarThis: Bits |= Capture_ByCopy; @@ -901,9 +917,9 @@ LambdaExpr::LambdaExpr(QualType T, SourceRange IntroducerRange, assert(CaptureInits.size() == Captures.size() && "Wrong number of arguments"); CXXRecordDecl *Class = getLambdaClass(); CXXRecordDecl::LambdaDefinitionData &Data = Class->getLambdaData(); - + // FIXME: Propagate "has unexpanded parameter pack" bit. - + // Copy captures. const ASTContext &Context = Class->getASTContext(); Data.NumCaptures = NumCaptures; @@ -914,15 +930,15 @@ LambdaExpr::LambdaExpr(QualType T, SourceRange IntroducerRange, for (unsigned I = 0, N = Captures.size(); I != N; ++I) { if (Captures[I].isExplicit()) ++Data.NumExplicitCaptures; - + *ToCapture++ = Captures[I]; } - + // Copy initialization expressions for the non-static data members. Stmt **Stored = getStoredStmts(); for (unsigned I = 0, N = CaptureInits.size(); I != N; ++I) *Stored++ = CaptureInits[I]; - + // Copy the body of the lambda. *Stored++ = getCallOperator()->getBody(); } @@ -1001,7 +1017,7 @@ CXXRecordDecl *LambdaExpr::getLambdaClass() const { CXXMethodDecl *LambdaExpr::getCallOperator() const { CXXRecordDecl *Record = getLambdaClass(); - return Record->getLambdaCallOperator(); + return Record->getLambdaCallOperator(); } TemplateParameterList *LambdaExpr::getTemplateParameterList() const { @@ -1188,7 +1204,7 @@ CXXDependentScopeMemberExpr::CreateEmpty(const ASTContext &C, bool CXXDependentScopeMemberExpr::isImplicitAccess() const { if (!Base) return true; - + return cast<Expr>(Base)->isImplicitCXXThis(); } @@ -1218,7 +1234,7 @@ UnresolvedMemberExpr::UnresolvedMemberExpr(const ASTContext &C, SourceLocation TemplateKWLoc, const DeclarationNameInfo &MemberNameInfo, const TemplateArgumentListInfo *TemplateArgs, - UnresolvedSetIterator Begin, + UnresolvedSetIterator Begin, UnresolvedSetIterator End) : OverloadExpr( UnresolvedMemberExprClass, C, QualifierLoc, TemplateKWLoc, @@ -1241,7 +1257,7 @@ UnresolvedMemberExpr::UnresolvedMemberExpr(const ASTContext &C, bool UnresolvedMemberExpr::isImplicitAccess() const { if (!Base) return true; - + return cast<Expr>(Base)->isImplicitCXXThis(); } @@ -1300,11 +1316,11 @@ CXXRecordDecl *UnresolvedMemberExpr::getNamingClass() const { assert(PT && "base of arrow member access is not pointer"); BaseType = PT->getPointeeType(); } - + Record = BaseType->getAsCXXRecordDecl(); assert(Record && "base of member expression does not name record"); } - + return Record; } @@ -1328,7 +1344,7 @@ SizeOfPackExpr *SizeOfPackExpr::CreateDeserialized(ASTContext &Context, } SubstNonTypeTemplateParmPackExpr:: -SubstNonTypeTemplateParmPackExpr(QualType T, +SubstNonTypeTemplateParmPackExpr(QualType T, ExprValueKind ValueKind, NonTypeTemplateParmDecl *Param, SourceLocation NameLoc, @@ -1411,13 +1427,13 @@ TypeTraitExpr::TypeTraitExpr(QualType T, SourceLocation Loc, TypeTrait Kind, setInstantiationDependent(true); if (Args[I]->getType()->containsUnexpandedParameterPack()) setContainsUnexpandedParameterPack(true); - + ToArgs[I] = Args[I]; } } TypeTraitExpr *TypeTraitExpr::Create(const ASTContext &C, QualType T, - SourceLocation Loc, + SourceLocation Loc, TypeTrait Kind, ArrayRef<TypeSourceInfo *> Args, SourceLocation RParenLoc, diff --git a/lib/AST/ExprClassification.cpp b/lib/AST/ExprClassification.cpp index c5b3b361a0a5..e50dd9c79d11 100644 --- a/lib/AST/ExprClassification.cpp +++ b/lib/AST/ExprClassification.cpp @@ -345,9 +345,9 @@ static Cl::Kinds ClassifyInternal(ASTContext &Ctx, const Expr *E) { return ClassifyUnnamed(Ctx, cast<ExplicitCastExpr>(E)->getTypeAsWritten()); case Expr::CXXUnresolvedConstructExprClass: - return ClassifyUnnamed(Ctx, + return ClassifyUnnamed(Ctx, cast<CXXUnresolvedConstructExpr>(E)->getTypeAsWritten()); - + case Expr::BinaryConditionalOperatorClass: { if (!Lang.CPlusPlus) return Cl::CL_PRValue; const auto *co = cast<BinaryConditionalOperator>(E); @@ -370,7 +370,7 @@ static Cl::Kinds ClassifyInternal(ASTContext &Ctx, const Expr *E) { return (kind == Cl::CL_PRValue) ? Cl::CL_ObjCMessageRValue : kind; } return Cl::CL_PRValue; - + // Some C++ expressions are always class temporaries. case Expr::CXXConstructExprClass: case Expr::CXXInheritedCtorInitExprClass: @@ -400,7 +400,7 @@ static Cl::Kinds ClassifyInternal(ASTContext &Ctx, const Expr *E) { case Expr::MaterializeTemporaryExprClass: return cast<MaterializeTemporaryExpr>(E)->isBoundToLvalueReference() - ? Cl::CL_LValue + ? Cl::CL_LValue : Cl::CL_XValue; case Expr::InitListExprClass: @@ -546,7 +546,7 @@ static Cl::Kinds ClassifyBinaryOp(ASTContext &Ctx, const BinaryOperator *E) { if (E->getOpcode() == BO_PtrMemD) return (E->getType()->isFunctionType() || E->hasPlaceholderType(BuiltinType::BoundMember)) - ? Cl::CL_MemberFunction + ? Cl::CL_MemberFunction : ClassifyInternal(Ctx, E->getLHS()); // C++ [expr.mptr.oper]p6: The result of an ->* expression is an lvalue if its @@ -554,7 +554,7 @@ static Cl::Kinds ClassifyBinaryOp(ASTContext &Ctx, const BinaryOperator *E) { if (E->getOpcode() == BO_PtrMemI) return (E->getType()->isFunctionType() || E->hasPlaceholderType(BuiltinType::BoundMember)) - ? Cl::CL_MemberFunction + ? Cl::CL_MemberFunction : Cl::CL_LValue; // All other binary operations are prvalues. diff --git a/lib/AST/ExprConstant.cpp b/lib/AST/ExprConstant.cpp index e69914f25da2..44cf75dbd25b 100644 --- a/lib/AST/ExprConstant.cpp +++ b/lib/AST/ExprConstant.cpp @@ -319,6 +319,25 @@ namespace { return false; } + /// Get the range of valid index adjustments in the form + /// {maximum value that can be subtracted from this pointer, + /// maximum value that can be added to this pointer} + std::pair<uint64_t, uint64_t> validIndexAdjustments() { + if (Invalid || isMostDerivedAnUnsizedArray()) + return {0, 0}; + + // [expr.add]p4: For the purposes of these operators, a pointer to a + // nonarray object behaves the same as a pointer to the first element of + // an array of length one with the type of the object as its element type. + bool IsArray = MostDerivedPathLength == Entries.size() && + MostDerivedIsArrayElement; + uint64_t ArrayIndex = + IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd; + uint64_t ArraySize = + IsArray ? getMostDerivedArraySize() : (uint64_t)1; + return {ArrayIndex, ArraySize - ArrayIndex}; + } + /// Check that this refers to a valid subobject. bool isValidSubobject() const { if (Invalid) @@ -329,6 +348,13 @@ namespace { /// relevant diagnostic and set the designator as invalid. bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK); + /// Get the type of the designated object. + QualType getType(ASTContext &Ctx) const { + return MostDerivedPathLength == Entries.size() + ? MostDerivedType + : Ctx.getRecordType(getAsBaseClass(Entries.back())); + } + /// Update this designator to refer to the first element within this array. void addArrayUnchecked(const ConstantArrayType *CAT) { PathEntry Entry; @@ -572,7 +598,7 @@ namespace { // FIXME: Force the precision of the source value down so we don't // print digits which are usually useless (we don't really care here if // we truncate a digit by accident in edge cases). Ideally, - // APFloat::toString would automatically print the shortest + // APFloat::toString would automatically print the shortest // representation which rounds to the correct value, but it's a bit // tricky to implement. unsigned precision = @@ -826,7 +852,7 @@ namespace { private: OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId, unsigned ExtraNotes, bool IsCCEDiag) { - + if (EvalStatus.Diag) { // If we have a prior diagnostic, it will be noting that the expression // isn't a constant expression. This diagnostic is more important, @@ -880,7 +906,7 @@ namespace { unsigned ExtraNotes = 0) { return Diag(Loc, DiagId, ExtraNotes, false); } - + OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr, unsigned ExtraNotes = 0) { @@ -1706,6 +1732,54 @@ static bool IsGlobalLValue(APValue::LValueBase B) { } } +static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { + return LVal.Base.dyn_cast<const ValueDecl*>(); +} + +static bool IsLiteralLValue(const LValue &Value) { + if (Value.getLValueCallIndex()) + return false; + const Expr *E = Value.Base.dyn_cast<const Expr*>(); + return E && !isa<MaterializeTemporaryExpr>(E); +} + +static bool IsWeakLValue(const LValue &Value) { + const ValueDecl *Decl = GetLValueBaseDecl(Value); + return Decl && Decl->isWeak(); +} + +static bool isZeroSized(const LValue &Value) { + const ValueDecl *Decl = GetLValueBaseDecl(Value); + if (Decl && isa<VarDecl>(Decl)) { + QualType Ty = Decl->getType(); + if (Ty->isArrayType()) + return Ty->isIncompleteType() || + Decl->getASTContext().getTypeSize(Ty) == 0; + } + return false; +} + +static bool HasSameBase(const LValue &A, const LValue &B) { + if (!A.getLValueBase()) + return !B.getLValueBase(); + if (!B.getLValueBase()) + return false; + + if (A.getLValueBase().getOpaqueValue() != + B.getLValueBase().getOpaqueValue()) { + const Decl *ADecl = GetLValueBaseDecl(A); + if (!ADecl) + return false; + const Decl *BDecl = GetLValueBaseDecl(B); + if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl()) + return false; + } + + return IsGlobalLValue(A.getLValueBase()) || + (A.getLValueCallIndex() == B.getLValueCallIndex() && + A.getLValueVersion() == B.getLValueVersion()); +} + static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { assert(Base && "no location for a null lvalue"); const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); @@ -1917,33 +1991,6 @@ CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, return true; } -static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { - return LVal.Base.dyn_cast<const ValueDecl*>(); -} - -static bool IsLiteralLValue(const LValue &Value) { - if (Value.getLValueCallIndex()) - return false; - const Expr *E = Value.Base.dyn_cast<const Expr*>(); - return E && !isa<MaterializeTemporaryExpr>(E); -} - -static bool IsWeakLValue(const LValue &Value) { - const ValueDecl *Decl = GetLValueBaseDecl(Value); - return Decl && Decl->isWeak(); -} - -static bool isZeroSized(const LValue &Value) { - const ValueDecl *Decl = GetLValueBaseDecl(Value); - if (Decl && isa<VarDecl>(Decl)) { - QualType Ty = Decl->getType(); - if (Ty->isArrayType()) - return Ty->isIncompleteType() || - Decl->getASTContext().getTypeSize(Ty) == 0; - } - return false; -} - static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { // A null base expression indicates a null pointer. These are always // evaluatable, and they are false unless the offset is zero. @@ -4286,13 +4333,13 @@ static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, if (Info.getLangOpts().CPlusPlus11) { const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; - + // If this function is not constexpr because it is an inherited // non-constexpr constructor, diagnose that directly. auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl); if (CD && CD->isInheritingConstructor()) { auto *Inherited = CD->getInheritedConstructor().getConstructor(); - if (!Inherited->isConstexpr()) + if (!Inherited->isConstexpr()) DiagDecl = CD = Inherited; } @@ -4853,7 +4900,7 @@ public: return false; This = &ThisVal; Args = Args.slice(1); - } else if (MD && MD->isLambdaStaticInvoker()) { + } else if (MD && MD->isLambdaStaticInvoker()) { // Map the static invoker for the lambda back to the call operator. // Conveniently, we don't have to slice out the 'this' argument (as is // being done for the non-static case), since a static member function @@ -4888,7 +4935,7 @@ public: FD = LambdaCallOp; } - + } else return Error(E); @@ -5732,7 +5779,7 @@ public: // Update 'Result' to refer to the data member/field of the closure object // that represents the '*this' capture. if (!HandleLValueMember(Info, E, Result, - Info.CurrentCall->LambdaThisCaptureField)) + Info.CurrentCall->LambdaThisCaptureField)) return false; // If we captured '*this' by reference, replace the field with its referent. if (Info.CurrentCall->LambdaThisCaptureField->getType() @@ -6117,6 +6164,130 @@ bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, return ZeroInitialization(E); } + case Builtin::BImemcpy: + case Builtin::BImemmove: + case Builtin::BIwmemcpy: + case Builtin::BIwmemmove: + if (Info.getLangOpts().CPlusPlus11) + Info.CCEDiag(E, diag::note_constexpr_invalid_function) + << /*isConstexpr*/0 << /*isConstructor*/0 + << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); + else + Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); + LLVM_FALLTHROUGH; + case Builtin::BI__builtin_memcpy: + case Builtin::BI__builtin_memmove: + case Builtin::BI__builtin_wmemcpy: + case Builtin::BI__builtin_wmemmove: { + bool WChar = BuiltinOp == Builtin::BIwmemcpy || + BuiltinOp == Builtin::BIwmemmove || + BuiltinOp == Builtin::BI__builtin_wmemcpy || + BuiltinOp == Builtin::BI__builtin_wmemmove; + bool Move = BuiltinOp == Builtin::BImemmove || + BuiltinOp == Builtin::BIwmemmove || + BuiltinOp == Builtin::BI__builtin_memmove || + BuiltinOp == Builtin::BI__builtin_wmemmove; + + // The result of mem* is the first argument. + if (!Visit(E->getArg(0))) + return false; + LValue Dest = Result; + + LValue Src; + if (!EvaluatePointer(E->getArg(1), Src, Info)) + return false; + + APSInt N; + if (!EvaluateInteger(E->getArg(2), N, Info)) + return false; + assert(!N.isSigned() && "memcpy and friends take an unsigned size"); + + // If the size is zero, we treat this as always being a valid no-op. + // (Even if one of the src and dest pointers is null.) + if (!N) + return true; + + // We require that Src and Dest are both pointers to arrays of + // trivially-copyable type. (For the wide version, the designator will be + // invalid if the designated object is not a wchar_t.) + QualType T = Dest.Designator.getType(Info.Ctx); + QualType SrcT = Src.Designator.getType(Info.Ctx); + if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) { + Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T; + return false; + } + if (!T.isTriviallyCopyableType(Info.Ctx)) { + Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T; + return false; + } + + // Figure out how many T's we're copying. + uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity(); + if (!WChar) { + uint64_t Remainder; + llvm::APInt OrigN = N; + llvm::APInt::udivrem(OrigN, TSize, N, Remainder); + if (Remainder) { + Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) + << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false) + << (unsigned)TSize; + return false; + } + } + + // Check that the copying will remain within the arrays, just so that we + // can give a more meaningful diagnostic. This implicitly also checks that + // N fits into 64 bits. + uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second; + uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second; + if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) { + Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) + << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T + << N.toString(10, /*Signed*/false); + return false; + } + uint64_t NElems = N.getZExtValue(); + uint64_t NBytes = NElems * TSize; + + // Check for overlap. + int Direction = 1; + if (HasSameBase(Src, Dest)) { + uint64_t SrcOffset = Src.getLValueOffset().getQuantity(); + uint64_t DestOffset = Dest.getLValueOffset().getQuantity(); + if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) { + // Dest is inside the source region. + if (!Move) { + Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; + return false; + } + // For memmove and friends, copy backwards. + if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) || + !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1)) + return false; + Direction = -1; + } else if (!Move && SrcOffset >= DestOffset && + SrcOffset - DestOffset < NBytes) { + // Src is inside the destination region for memcpy: invalid. + Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; + return false; + } + } + + while (true) { + APValue Val; + if (!handleLValueToRValueConversion(Info, E, T, Src, Val) || + !handleAssignment(Info, E, Dest, T, Val)) + return false; + // Do not iterate past the last element; if we're copying backwards, that + // might take us off the start of the array. + if (--NElems == 0) + return true; + if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) || + !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction)) + return false; + } + } + default: return visitNonBuiltinCallExpr(E); } @@ -6583,7 +6754,7 @@ bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { if (ClosureClass->isInvalidDecl()) return false; if (Info.checkingPotentialConstantExpression()) return true; - + const size_t NumFields = std::distance(ClosureClass->field_begin(), ClosureClass->field_end()); @@ -6602,7 +6773,7 @@ bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { assert(CaptureInitIt != E->capture_init_end()); // Get the initializer for this field Expr *const CurFieldInit = *CaptureInitIt++; - + // If there is no initializer, either this is a VLA or an error has // occurred. if (!CurFieldInit) @@ -6802,18 +6973,18 @@ VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { // The number of initializers can be less than the number of // vector elements. For OpenCL, this can be due to nested vector - // initialization. For GCC compatibility, missing trailing elements + // initialization. For GCC compatibility, missing trailing elements // should be initialized with zeroes. unsigned CountInits = 0, CountElts = 0; while (CountElts < NumElements) { // Handle nested vector initialization. - if (CountInits < NumInits + if (CountInits < NumInits && E->getInit(CountInits)->getType()->isVectorType()) { APValue v; if (!EvaluateVector(E->getInit(CountInits), v, Info)) return Error(E); unsigned vlen = v.getVectorLength(); - for (unsigned j = 0; j < vlen; j++) + for (unsigned j = 0; j < vlen; j++) Elements.push_back(v.getVectorElt(j)); CountElts += vlen; } else if (EltTy->isIntegerType()) { @@ -7108,7 +7279,7 @@ public: } bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { - assert(E->getType()->isIntegralOrEnumerationType() && + assert(E->getType()->isIntegralOrEnumerationType() && "Invalid evaluation result."); assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && "Invalid evaluation result."); @@ -7198,7 +7369,7 @@ public: } return Success(Info.ArrayInitIndex, E); } - + // Note, GNU defines __null as an integer, not a pointer. bool VisitGNUNullExpr(const GNUNullExpr *E) { return ZeroInitialization(E); @@ -8357,27 +8528,6 @@ bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, } } -static bool HasSameBase(const LValue &A, const LValue &B) { - if (!A.getLValueBase()) - return !B.getLValueBase(); - if (!B.getLValueBase()) - return false; - - if (A.getLValueBase().getOpaqueValue() != - B.getLValueBase().getOpaqueValue()) { - const Decl *ADecl = GetLValueBaseDecl(A); - if (!ADecl) - return false; - const Decl *BDecl = GetLValueBaseDecl(B); - if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl()) - return false; - } - - return IsGlobalLValue(A.getLValueBase()) || - (A.getLValueCallIndex() == B.getLValueCallIndex() && - A.getLValueVersion() == B.getLValueVersion()); -} - /// Determine whether this is a pointer past the end of the complete /// object referred to by the lvalue. static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, @@ -8585,12 +8735,12 @@ bool DataRecursiveIntBinOpEvaluator:: Result = RHSResult.Val; return true; } - + if (E->isLogicalOp()) { bool lhsResult, rhsResult; bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); - + if (LHSIsOK) { if (RHSIsOK) { if (E->getOpcode() == BO_LOr) @@ -8606,26 +8756,26 @@ bool DataRecursiveIntBinOpEvaluator:: return Success(rhsResult, E, Result); } } - + return false; } - + assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && E->getRHS()->getType()->isIntegralOrEnumerationType()); - + if (LHSResult.Failed || RHSResult.Failed) return false; - + const APValue &LHSVal = LHSResult.Val; const APValue &RHSVal = RHSResult.Val; - + // Handle cases like (unsigned long)&a + 4. if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { Result = LHSVal; addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub); return true; } - + // Handle cases like 4 + (unsigned long)&a if (E->getOpcode() == BO_Add && RHSVal.isLValue() && LHSVal.isInt()) { @@ -8633,7 +8783,7 @@ bool DataRecursiveIntBinOpEvaluator:: addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false); return true; } - + if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { // Handle (intptr_t)&&A - (intptr_t)&&B. if (!LHSVal.getLValueOffset().isZero() || @@ -8672,7 +8822,7 @@ bool DataRecursiveIntBinOpEvaluator:: void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { Job &job = Queue.back(); - + switch (job.Kind) { case Job::AnyExprKind: { if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { @@ -8682,12 +8832,12 @@ void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { return; } } - + EvaluateExpr(job.E, Result); Queue.pop_back(); return; } - + case Job::BinOpKind: { const BinaryOperator *Bop = cast<BinaryOperator>(job.E); bool SuppressRHSDiags = false; @@ -8702,7 +8852,7 @@ void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { enqueue(Bop->getRHS()); return; } - + case Job::BinOpVisitedLHSKind: { const BinaryOperator *Bop = cast<BinaryOperator>(job.E); EvalResult RHS; @@ -8712,7 +8862,7 @@ void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { return; } } - + llvm_unreachable("Invalid Job::Kind!"); } @@ -9299,7 +9449,7 @@ bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { const RecordType *BaseRT = CurrentType->getAs<RecordType>(); if (!BaseRT) return Error(OOE); - + // Add the offset to the base. Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); break; @@ -10531,7 +10681,7 @@ static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, IsConst = false; return true; } - + // FIXME: Evaluating values of large array and record types can cause // performance problems. Only do so in C++11 for now. if (Exp->isRValue() && (Exp->getType()->isArrayType() || @@ -10553,7 +10703,7 @@ bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const { bool IsConst; if (FastEvaluateAsRValue(this, Result, Ctx, IsConst)) return IsConst; - + EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); return ::EvaluateAsRValue(Info, this, Result.Val); } diff --git a/lib/AST/ExternalASTSource.cpp b/lib/AST/ExternalASTSource.cpp index 198ba9d4fbdb..40829c2e249d 100644 --- a/lib/AST/ExternalASTSource.cpp +++ b/lib/AST/ExternalASTSource.cpp @@ -7,7 +7,7 @@ // //===----------------------------------------------------------------------===// // -// This file provides the default implementation of the ExternalASTSource +// This file provides the default implementation of the ExternalASTSource // interface, which enables construction of AST nodes from some external // source. // diff --git a/lib/AST/ItaniumCXXABI.cpp b/lib/AST/ItaniumCXXABI.cpp index a75ae14f9015..64580edf004b 100644 --- a/lib/AST/ItaniumCXXABI.cpp +++ b/lib/AST/ItaniumCXXABI.cpp @@ -190,7 +190,7 @@ public: return false; const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); - CharUnits PointerSize = + CharUnits PointerSize = Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0)); return Layout.getNonVirtualSize() == PointerSize; } diff --git a/lib/AST/ItaniumMangle.cpp b/lib/AST/ItaniumMangle.cpp index 3b99a3d9afda..2dc04f2f3d86 100644 --- a/lib/AST/ItaniumMangle.cpp +++ b/lib/AST/ItaniumMangle.cpp @@ -46,10 +46,10 @@ namespace { /// Retrieve the declaration context that should be used when mangling the given /// declaration. static const DeclContext *getEffectiveDeclContext(const Decl *D) { - // The ABI assumes that lambda closure types that occur within + // The ABI assumes that lambda closure types that occur within // default arguments live in the context of the function. However, due to // the way in which Clang parses and creates function declarations, this is - // not the case: the lambda closure type ends up living in the context + // not the case: the lambda closure type ends up living in the context // where the function itself resides, because the function declaration itself // had not yet been created. Fix the context here. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) { @@ -65,7 +65,7 @@ static const DeclContext *getEffectiveDeclContext(const Decl *D) { = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) return ContextParam->getDeclContext(); } - + const DeclContext *DC = D->getDeclContext(); if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC)) { return getEffectiveDeclContext(cast<Decl>(DC)); @@ -441,7 +441,7 @@ public: void mangleName(const NamedDecl *ND); void mangleType(QualType T); void mangleNameOrStandardSubstitution(const NamedDecl *ND); - + private: bool mangleSubstitution(const NamedDecl *ND); @@ -786,7 +786,7 @@ static bool isStd(const NamespaceDecl *NS) { if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS)) ->isTranslationUnit()) return false; - + const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier(); return II && II->isStr("std"); } @@ -998,7 +998,7 @@ void CXXNameMangler::mangleUnscopedTemplateName( // ::= <substitution> if (TemplateDecl *TD = Template.getAsTemplateDecl()) return mangleUnscopedTemplateName(TD, AdditionalAbiTags); - + if (mangleSubstitution(Template)) return; @@ -1100,7 +1100,7 @@ void CXXNameMangler::manglePrefix(QualType type) { if (const auto *TST = type->getAs<TemplateSpecializationType>()) { if (!mangleSubstitution(QualType(TST, 0))) { mangleTemplatePrefix(TST->getTemplateName()); - + // FIXME: GCC does not appear to mangle the template arguments when // the template in question is a dependent template name. Should we // emulate that badness? @@ -1372,7 +1372,7 @@ void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND, // safety, just handle all ObjC containers here. if (isa<ObjCContainerDecl>(ND)) break; - + // We must have an anonymous struct. const TagDecl *TD = cast<TagDecl>(ND); if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) { @@ -1389,7 +1389,7 @@ void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND, } // <unnamed-type-name> ::= <closure-type-name> - // + // // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _ // <lambda-sig> ::= <parameter-type>+ # Parameter types or 'v' for 'void'. if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) { @@ -1515,9 +1515,9 @@ void CXXNameMangler::mangleNestedName(const NamedDecl *ND, const DeclContext *DC, const AbiTagList *AdditionalAbiTags, bool NoFunction) { - // <nested-name> + // <nested-name> // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E - // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix> + // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix> // <template-args> E Out << 'N'; @@ -1530,7 +1530,7 @@ void CXXNameMangler::mangleNestedName(const NamedDecl *ND, mangleQualifiers(MethodQuals); mangleRefQualifier(Method->getRefQualifier()); } - + // Check if we have a template. const TemplateArgumentList *TemplateArgs = nullptr; if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) { @@ -1561,7 +1561,7 @@ void CXXNameMangler::mangleLocalName(const Decl *D, const AbiTagList *AdditionalAbiTags) { // <local-name> := Z <function encoding> E <entity name> [<discriminator>] // := Z <function encoding> E s [<discriminator>] - // <local-name> := Z <function encoding> E d [ <parameter number> ] + // <local-name> := Z <function encoding> E d [ <parameter number> ] // _ <entity name> // <discriminator> := _ <non-negative number> assert(isa<NamedDecl>(D) || isa<BlockDecl>(D)); @@ -1591,9 +1591,9 @@ void CXXNameMangler::mangleLocalName(const Decl *D, // be a bug that is fixed in trunk. if (RD) { - // The parameter number is omitted for the last parameter, 0 for the - // second-to-last parameter, 1 for the third-to-last parameter, etc. The - // <entity name> will of course contain a <closure-type-name>: Its + // The parameter number is omitted for the last parameter, 0 for the + // second-to-last parameter, 1 for the third-to-last parameter, etc. The + // <entity name> will of course contain a <closure-type-name>: Its // numbering will be local to the particular argument in which it appears // -- other default arguments do not affect its encoding. const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD); @@ -1610,7 +1610,7 @@ void CXXNameMangler::mangleLocalName(const Decl *D, } } } - + // Mangle the name relative to the closest enclosing function. // equality ok because RD derived from ND above if (D == RD) { @@ -1699,8 +1699,8 @@ void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) { } void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) { - // If the context of a closure type is an initializer for a class member - // (static or nonstatic), it is encoded in a qualified name with a final + // If the context of a closure type is an initializer for a class member + // (static or nonstatic), it is encoded in a qualified name with a final // <prefix> of the form: // // <data-member-prefix> := <member source-name> M @@ -1730,9 +1730,9 @@ void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) { mangleBareFunctionType(Proto, /*MangleReturnType=*/false, Lambda->getLambdaStaticInvoker()); Out << "E"; - - // The number is omitted for the first closure type with a given - // <lambda-sig> in a given context; it is n-2 for the nth closure type + + // The number is omitted for the first closure type with a given + // <lambda-sig> in a given context; it is n-2 for the nth closure type // (in lexical order) with that same <lambda-sig> and context. // // The AST keeps track of the number for us. @@ -1740,7 +1740,7 @@ void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) { assert(Number > 0 && "Lambda should be mangled as an unnamed class"); if (Number > 1) mangleNumber(Number - 2); - Out << '_'; + Out << '_'; } void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) { @@ -1795,10 +1795,10 @@ void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) { assert(!isLocalContainerContext(DC)); - const NamedDecl *ND = cast<NamedDecl>(DC); + const NamedDecl *ND = cast<NamedDecl>(DC); if (mangleSubstitution(ND)) return; - + // Check if we have a template. const TemplateArgumentList *TemplateArgs = nullptr; if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) { @@ -2286,19 +2286,19 @@ void CXXNameMangler::mangleQualifiers(Qualifiers Quals, const DependentAddressSp switch (Quals.getObjCLifetime()) { case Qualifiers::OCL_None: break; - + case Qualifiers::OCL_Weak: // Do nothing as we already handled this case above. break; - + case Qualifiers::OCL_Strong: mangleVendorQualifier("__strong"); break; - + case Qualifiers::OCL_Autoreleasing: mangleVendorQualifier("__autoreleasing"); break; - + case Qualifiers::OCL_ExplicitNone: // The __unsafe_unretained qualifier is *not* mangled, so that // __unsafe_unretained types in ARC produce the same manglings as the @@ -2329,11 +2329,11 @@ void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) { switch (RefQualifier) { case RQ_None: break; - + case RQ_LValue: Out << 'R'; break; - + case RQ_RValue: Out << 'O'; break; @@ -2364,15 +2364,15 @@ static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty, void CXXNameMangler::mangleType(QualType T) { // If our type is instantiation-dependent but not dependent, we mangle - // it as it was written in the source, removing any top-level sugar. + // it as it was written in the source, removing any top-level sugar. // Otherwise, use the canonical type. // - // FIXME: This is an approximation of the instantiation-dependent name + // FIXME: This is an approximation of the instantiation-dependent name // mangling rules, since we should really be using the type as written and // augmented via semantic analysis (i.e., with implicit conversions and - // default template arguments) for any instantiation-dependent type. + // default template arguments) for any instantiation-dependent type. // Unfortunately, that requires several changes to our AST: - // - Instantiation-dependent TemplateSpecializationTypes will need to be + // - Instantiation-dependent TemplateSpecializationTypes will need to be // uniqued, so that we can handle substitutions properly // - Default template arguments will need to be represented in the // TemplateSpecializationType, since they need to be mangled even though @@ -2402,16 +2402,16 @@ void CXXNameMangler::mangleType(QualType T) { do { // Don't desugar through template specialization types that aren't // type aliases. We need to mangle the template arguments as written. - if (const TemplateSpecializationType *TST + if (const TemplateSpecializationType *TST = dyn_cast<TemplateSpecializationType>(T)) if (!TST->isTypeAlias()) break; - QualType Desugared + QualType Desugared = T.getSingleStepDesugaredType(Context.getASTContext()); if (Desugared == T) break; - + T = Desugared; } while (true); } @@ -2435,7 +2435,7 @@ void CXXNameMangler::mangleType(QualType T) { } if (quals || ty->isDependentAddressSpaceType()) { - if (const DependentAddressSpaceType *DAST = + if (const DependentAddressSpaceType *DAST = dyn_cast<DependentAddressSpaceType>(ty)) { SplitQualType splitDAST = DAST->getPointeeType().split(); mangleQualifiers(splitDAST.Quals, DAST); @@ -2899,7 +2899,7 @@ void CXXNameMangler::mangleType(const MemberPointerType *T) { QualType PointeeType = T->getPointeeType(); if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) { mangleType(FPT); - + // Itanium C++ ABI 5.1.8: // // The type of a non-static member function is considered to be different, @@ -2907,8 +2907,8 @@ void CXXNameMangler::mangleType(const MemberPointerType *T) { // static member function whose type appears similar. The types of two // non-static member functions are considered to be different, for the // purposes of substitution, if the functions are members of different - // classes. In other words, for the purposes of substitution, the class of - // which the function is a member is considered part of the type of + // classes. In other words, for the purposes of substitution, the class of + // which the function is a member is considered part of the type of // function. // Given that we already substitute member function pointers as a @@ -3225,9 +3225,9 @@ void CXXNameMangler::mangleType(const TemplateSpecializationType *T) { } else { if (mangleSubstitution(QualType(T, 0))) return; - + mangleTemplatePrefix(T->getTemplateName()); - + // FIXME: GCC does not appear to mangle the template arguments when // the template in question is a dependent template name. Should we // emulate that badness? @@ -3283,7 +3283,7 @@ void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) { // FIXME: GCC does not appear to mangle the template arguments when // the template in question is a dependent template name. Should we // emulate that badness? - mangleTemplateArgs(T->getArgs(), T->getNumArgs()); + mangleTemplateArgs(T->getArgs(), T->getNumArgs()); Out << 'E'; } @@ -3328,7 +3328,7 @@ void CXXNameMangler::mangleType(const UnaryTransformType *T) { // mangle it as the underlying type since they are equivalent. if (T->isDependentType()) { Out << 'U'; - + switch (T->getUTTKind()) { case UnaryTransformType::EnumUnderlyingType: Out << "3eut"; @@ -3498,7 +3498,7 @@ void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) { // ::= L <mangled-name> E # external name // ::= fpT # 'this' expression QualType ImplicitlyConvertedToType; - + recurse: switch (E->getStmtClass()) { case Expr::NoStmtClass: @@ -3861,24 +3861,24 @@ recurse: case Expr::UnaryExprOrTypeTraitExprClass: { const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E); - + if (!SAE->isInstantiationDependent()) { // Itanium C++ ABI: - // If the operand of a sizeof or alignof operator is not - // instantiation-dependent it is encoded as an integer literal + // If the operand of a sizeof or alignof operator is not + // instantiation-dependent it is encoded as an integer literal // reflecting the result of the operator. // - // If the result of the operator is implicitly converted to a known - // integer type, that type is used for the literal; otherwise, the type + // If the result of the operator is implicitly converted to a known + // integer type, that type is used for the literal; otherwise, the type // of std::size_t or std::ptrdiff_t is used. - QualType T = (ImplicitlyConvertedToType.isNull() || + QualType T = (ImplicitlyConvertedToType.isNull() || !ImplicitlyConvertedToType->isIntegerType())? SAE->getType() : ImplicitlyConvertedToType; llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext()); mangleIntegerLiteral(T, V); break; } - + switch(SAE->getKind()) { case UETT_SizeOf: Out << 's'; @@ -3994,16 +3994,16 @@ recurse: E = cast<ImplicitCastExpr>(E)->getSubExpr(); goto recurse; } - + case Expr::ObjCBridgedCastExprClass: { - // Mangle ownership casts as a vendor extended operator __bridge, + // Mangle ownership casts as a vendor extended operator __bridge, // __bridge_transfer, or __bridge_retain. StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName(); Out << "v1U" << Kind.size() << Kind; } // Fall through to mangle the cast itself. LLVM_FALLTHROUGH; - + case Expr::CStyleCastExprClass: mangleCastExpression(E, "cv"); break; @@ -4143,7 +4143,7 @@ recurse: Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0'); Out << 'E'; break; - + case Expr::CXXBoolLiteralExprClass: Out << "Lb"; Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0'); @@ -4198,12 +4198,12 @@ recurse: Out << "LDnE"; break; } - + case Expr::PackExpansionExprClass: Out << "sp"; mangleExpression(cast<PackExpansionExpr>(E)->getPattern()); break; - + case Expr::SizeOfPackExprClass: { auto *SPE = cast<SizeOfPackExpr>(E); if (SPE->isPartiallySubstituted()) { @@ -4430,11 +4430,11 @@ void CXXNameMangler::mangleTemplateArg(TemplateArgument A) { // ::= J <template-arg>* E # argument pack if (!A.isInstantiationDependent() || A.isDependent()) A = Context.getASTContext().getCanonicalTemplateArgument(A); - + switch (A.getKind()) { case TemplateArgument::Null: llvm_unreachable("Cannot mangle NULL template argument"); - + case TemplateArgument::Type: mangleType(A.getAsType()); break; @@ -4461,7 +4461,7 @@ void CXXNameMangler::mangleTemplateArg(TemplateArgument A) { break; } } - + Out << 'X'; mangleExpression(E); Out << 'E'; @@ -4578,7 +4578,7 @@ bool CXXNameMangler::mangleSubstitution(QualType T) { bool CXXNameMangler::mangleSubstitution(TemplateName Template) { if (TemplateDecl *TD = Template.getAsTemplateDecl()) return mangleSubstitution(TD); - + Template = Context.getASTContext().getCanonicalTemplateName(Template); return mangleSubstitution( reinterpret_cast<uintptr_t>(Template.getAsVoidPointer())); @@ -4743,7 +4743,7 @@ void CXXNameMangler::addSubstitution(QualType T) { void CXXNameMangler::addSubstitution(TemplateName Template) { if (TemplateDecl *TD = Template.getAsTemplateDecl()) return addSubstitution(TD); - + Template = Context.getASTContext().getCanonicalTemplateName(Template); addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer())); } @@ -4865,14 +4865,14 @@ void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD, // # base is the nominal target function of thunk // # first call-offset is 'this' adjustment // # second call-offset is result adjustment - + assert(!isa<CXXDestructorDecl>(MD) && "Use mangleCXXDtor for destructor decls!"); CXXNameMangler Mangler(*this, Out); Mangler.getStream() << "_ZT"; if (!Thunk.Return.isEmpty()) Mangler.getStream() << 'c'; - + // Mangle the 'this' pointer adjustment. Mangler.mangleCallOffset(Thunk.This.NonVirtual, Thunk.This.Virtual.Itanium.VCallOffsetOffset); @@ -4894,7 +4894,7 @@ void ItaniumMangleContextImpl::mangleCXXDtorThunk( Mangler.getStream() << "_ZT"; // Mangle the 'this' pointer adjustment. - Mangler.mangleCallOffset(ThisAdjustment.NonVirtual, + Mangler.mangleCallOffset(ThisAdjustment.NonVirtual, ThisAdjustment.Virtual.Itanium.VCallOffsetOffset); Mangler.mangleFunctionEncoding(DD); diff --git a/lib/AST/Mangle.cpp b/lib/AST/Mangle.cpp index 56a2500274a7..b0e5146e8194 100644 --- a/lib/AST/Mangle.cpp +++ b/lib/AST/Mangle.cpp @@ -44,7 +44,7 @@ static void mangleFunctionBlock(MangleContext &Context, if (discriminator == 0) Out << "__" << Outer << "_block_invoke"; else - Out << "__" << Outer << "_block_invoke_" << discriminator+1; + Out << "__" << Outer << "_block_invoke_" << discriminator+1; } void MangleContext::anchor() { } diff --git a/lib/AST/MicrosoftMangle.cpp b/lib/AST/MicrosoftMangle.cpp index e45f9f7902e2..5db51b5cb384 100644 --- a/lib/AST/MicrosoftMangle.cpp +++ b/lib/AST/MicrosoftMangle.cpp @@ -760,7 +760,7 @@ void MicrosoftCXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND, // type [ -> template-parameters] // \-> namespace[s] // What we do is we create a new mangler, mangle the same type (without - // a namespace suffix) to a string using the extra mangler and then use + // a namespace suffix) to a string using the extra mangler and then use // the mangled type name as a key to check the mangling of different types // for aliasing. @@ -1373,13 +1373,14 @@ void MicrosoftCXXNameMangler::mangleTemplateArg(const TemplateDecl *TD, case TemplateArgument::Declaration: { const NamedDecl *ND = TA.getAsDecl(); if (isa<FieldDecl>(ND) || isa<IndirectFieldDecl>(ND)) { - mangleMemberDataPointer( - cast<CXXRecordDecl>(ND->getDeclContext())->getMostRecentNonInjectedDecl(), - cast<ValueDecl>(ND)); + mangleMemberDataPointer(cast<CXXRecordDecl>(ND->getDeclContext()) + ->getMostRecentNonInjectedDecl(), + cast<ValueDecl>(ND)); } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); if (MD && MD->isInstance()) { - mangleMemberFunctionPointer(MD->getParent()->getMostRecentNonInjectedDecl(), MD); + mangleMemberFunctionPointer( + MD->getParent()->getMostRecentNonInjectedDecl(), MD); } else { Out << "$1?"; mangleName(FD); @@ -2285,7 +2286,8 @@ void MicrosoftCXXNameMangler::mangleType(const TagDecl *TD) { // If you add a call to this, consider updating isArtificialTagType() too. void MicrosoftCXXNameMangler::mangleArtificalTagType( - TagTypeKind TK, StringRef UnqualifiedName, ArrayRef<StringRef> NestedNames) { + TagTypeKind TK, StringRef UnqualifiedName, + ArrayRef<StringRef> NestedNames) { // <name> ::= <unscoped-name> {[<named-scope>]+ | [<nested-name>]}? @ mangleTagTypeKind(TK); @@ -2372,8 +2374,8 @@ void MicrosoftCXXNameMangler::mangleArrayType(const ArrayType *T) { // <type> ::= <pointer-to-member-type> // <pointer-to-member-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers> // <class name> <type> -void MicrosoftCXXNameMangler::mangleType(const MemberPointerType *T, Qualifiers Quals, - SourceRange Range) { +void MicrosoftCXXNameMangler::mangleType(const MemberPointerType *T, + Qualifiers Quals, SourceRange Range) { QualType PointeeType = T->getPointeeType(); manglePointerCVQualifiers(Quals); manglePointerExtQualifiers(Quals, PointeeType); diff --git a/lib/AST/NSAPI.cpp b/lib/AST/NSAPI.cpp index 536bf2c378fa..94ad87b6e337 100644 --- a/lib/AST/NSAPI.cpp +++ b/lib/AST/NSAPI.cpp @@ -432,7 +432,7 @@ NSAPI::getNSNumberFactoryMethodKind(QualType T) const { return NSAPI::NSNumberWithDouble; case BuiltinType::Bool: return NSAPI::NSNumberWithBool; - + case BuiltinType::Void: case BuiltinType::WChar_U: case BuiltinType::WChar_S: @@ -491,7 +491,7 @@ NSAPI::getNSNumberFactoryMethodKind(QualType T) const { case BuiltinType::OMPArraySection: break; } - + return None; } @@ -511,7 +511,7 @@ bool NSAPI::isObjCNSUIntegerType(QualType T) const { StringRef NSAPI::GetNSIntegralKind(QualType T) const { if (!Ctx.getLangOpts().ObjC1 || T.isNull()) return StringRef(); - + while (const TypedefType *TDT = T->getAs<TypedefType>()) { StringRef NSIntegralResust = llvm::StringSwitch<StringRef>( diff --git a/lib/AST/NestedNameSpecifier.cpp b/lib/AST/NestedNameSpecifier.cpp index 503d0eb65e1e..a514d57b6b6b 100644 --- a/lib/AST/NestedNameSpecifier.cpp +++ b/lib/AST/NestedNameSpecifier.cpp @@ -85,7 +85,7 @@ NestedNameSpecifier::Create(const ASTContext &Context, NestedNameSpecifier * NestedNameSpecifier::Create(const ASTContext &Context, - NestedNameSpecifier *Prefix, + NestedNameSpecifier *Prefix, NamespaceAliasDecl *Alias) { assert(Alias && "Namespace alias cannot be NULL"); assert((!Prefix || @@ -234,7 +234,7 @@ bool NestedNameSpecifier::isInstantiationDependent() const { case Identifier: // Identifier specifiers always represent dependent types return true; - + case Namespace: case NamespaceAlias: case Global: @@ -284,7 +284,7 @@ NestedNameSpecifier::print(raw_ostream &OS, case Namespace: if (getAsNamespace()->isAnonymousNamespace()) return; - + OS << getAsNamespace()->getName(); break; @@ -348,7 +348,7 @@ LLVM_DUMP_METHOD void NestedNameSpecifier::dump() const { print(llvm::errs(), PrintingPolicy(LO)); } -unsigned +unsigned NestedNameSpecifierLoc::getLocalDataLength(NestedNameSpecifier *Qualifier) { assert(Qualifier && "Expected a non-NULL qualifier"); @@ -379,7 +379,7 @@ NestedNameSpecifierLoc::getLocalDataLength(NestedNameSpecifier *Qualifier) { return Length; } -unsigned +unsigned NestedNameSpecifierLoc::getDataLength(NestedNameSpecifier *Qualifier) { unsigned Length = 0; for (; Qualifier; Qualifier = Qualifier->getPrefix()) @@ -394,7 +394,7 @@ static SourceLocation LoadSourceLocation(void *Data, unsigned Offset) { memcpy(&Raw, static_cast<char *>(Data) + Offset, sizeof(unsigned)); return SourceLocation::getFromRawEncoding(Raw); } - + /// Load a (possibly unaligned) pointer from a given address and /// offset. static void *LoadPointer(void *Data, unsigned Offset) { @@ -406,19 +406,19 @@ static void *LoadPointer(void *Data, unsigned Offset) { SourceRange NestedNameSpecifierLoc::getSourceRange() const { if (!Qualifier) return SourceRange(); - + NestedNameSpecifierLoc First = *this; while (NestedNameSpecifierLoc Prefix = First.getPrefix()) First = Prefix; - - return SourceRange(First.getLocalSourceRange().getBegin(), + + return SourceRange(First.getLocalSourceRange().getBegin(), getLocalSourceRange().getEnd()); } SourceRange NestedNameSpecifierLoc::getLocalSourceRange() const { if (!Qualifier) return SourceRange(); - + unsigned Offset = getDataLength(Qualifier->getPrefix()); switch (Qualifier->getKind()) { case NestedNameSpecifier::Global: @@ -478,7 +478,7 @@ static void Append(char *Start, char *End, char *&Buffer, unsigned &BufferSize, memcpy(Buffer + BufferSize, Start, End - Start); BufferSize += End-Start; } - + /// Save a source location to the given buffer. static void SaveSourceLocation(SourceLocation Loc, char *&Buffer, unsigned &BufferSize, unsigned &BufferCapacity) { @@ -487,7 +487,7 @@ static void SaveSourceLocation(SourceLocation Loc, char *&Buffer, reinterpret_cast<char *>(&Raw) + sizeof(unsigned), Buffer, BufferSize, BufferCapacity); } - + /// Save a pointer to the given buffer. static void SavePointer(void *Ptr, char *&Buffer, unsigned &BufferSize, unsigned &BufferCapacity) { @@ -497,18 +497,18 @@ static void SavePointer(void *Ptr, char *&Buffer, unsigned &BufferSize, } NestedNameSpecifierLocBuilder:: -NestedNameSpecifierLocBuilder(const NestedNameSpecifierLocBuilder &Other) +NestedNameSpecifierLocBuilder(const NestedNameSpecifierLocBuilder &Other) : Representation(Other.Representation) { if (!Other.Buffer) return; - + if (Other.BufferCapacity == 0) { // Shallow copy is okay. Buffer = Other.Buffer; BufferSize = Other.BufferSize; return; } - + // Deep copy Append(Other.Buffer, Other.Buffer + Other.BufferSize, Buffer, BufferSize, BufferCapacity); @@ -518,72 +518,72 @@ NestedNameSpecifierLocBuilder & NestedNameSpecifierLocBuilder:: operator=(const NestedNameSpecifierLocBuilder &Other) { Representation = Other.Representation; - + if (Buffer && Other.Buffer && BufferCapacity >= Other.BufferSize) { // Re-use our storage. BufferSize = Other.BufferSize; memcpy(Buffer, Other.Buffer, BufferSize); return *this; } - + // Free our storage, if we have any. if (BufferCapacity) { free(Buffer); BufferCapacity = 0; } - + if (!Other.Buffer) { // Empty. Buffer = nullptr; BufferSize = 0; return *this; } - + if (Other.BufferCapacity == 0) { // Shallow copy is okay. Buffer = Other.Buffer; BufferSize = Other.BufferSize; return *this; } - + // Deep copy. Append(Other.Buffer, Other.Buffer + Other.BufferSize, Buffer, BufferSize, BufferCapacity); return *this; } -void NestedNameSpecifierLocBuilder::Extend(ASTContext &Context, - SourceLocation TemplateKWLoc, - TypeLoc TL, +void NestedNameSpecifierLocBuilder::Extend(ASTContext &Context, + SourceLocation TemplateKWLoc, + TypeLoc TL, SourceLocation ColonColonLoc) { - Representation = NestedNameSpecifier::Create(Context, Representation, - TemplateKWLoc.isValid(), + Representation = NestedNameSpecifier::Create(Context, Representation, + TemplateKWLoc.isValid(), TL.getTypePtr()); - + // Push source-location info into the buffer. SavePointer(TL.getOpaqueData(), Buffer, BufferSize, BufferCapacity); SaveSourceLocation(ColonColonLoc, Buffer, BufferSize, BufferCapacity); } -void NestedNameSpecifierLocBuilder::Extend(ASTContext &Context, +void NestedNameSpecifierLocBuilder::Extend(ASTContext &Context, IdentifierInfo *Identifier, - SourceLocation IdentifierLoc, + SourceLocation IdentifierLoc, SourceLocation ColonColonLoc) { - Representation = NestedNameSpecifier::Create(Context, Representation, + Representation = NestedNameSpecifier::Create(Context, Representation, Identifier); - + // Push source-location info into the buffer. SaveSourceLocation(IdentifierLoc, Buffer, BufferSize, BufferCapacity); SaveSourceLocation(ColonColonLoc, Buffer, BufferSize, BufferCapacity); } -void NestedNameSpecifierLocBuilder::Extend(ASTContext &Context, +void NestedNameSpecifierLocBuilder::Extend(ASTContext &Context, NamespaceDecl *Namespace, - SourceLocation NamespaceLoc, + SourceLocation NamespaceLoc, SourceLocation ColonColonLoc) { - Representation = NestedNameSpecifier::Create(Context, Representation, + Representation = NestedNameSpecifier::Create(Context, Representation, Namespace); - + // Push source-location info into the buffer. SaveSourceLocation(NamespaceLoc, Buffer, BufferSize, BufferCapacity); SaveSourceLocation(ColonColonLoc, Buffer, BufferSize, BufferCapacity); @@ -591,20 +591,20 @@ void NestedNameSpecifierLocBuilder::Extend(ASTContext &Context, void NestedNameSpecifierLocBuilder::Extend(ASTContext &Context, NamespaceAliasDecl *Alias, - SourceLocation AliasLoc, + SourceLocation AliasLoc, SourceLocation ColonColonLoc) { Representation = NestedNameSpecifier::Create(Context, Representation, Alias); - + // Push source-location info into the buffer. SaveSourceLocation(AliasLoc, Buffer, BufferSize, BufferCapacity); SaveSourceLocation(ColonColonLoc, Buffer, BufferSize, BufferCapacity); } -void NestedNameSpecifierLocBuilder::MakeGlobal(ASTContext &Context, +void NestedNameSpecifierLocBuilder::MakeGlobal(ASTContext &Context, SourceLocation ColonColonLoc) { assert(!Representation && "Already have a nested-name-specifier!?"); Representation = NestedNameSpecifier::GlobalSpecifier(Context); - + // Push source-location info into the buffer. SaveSourceLocation(ColonColonLoc, Buffer, BufferSize, BufferCapacity); } @@ -620,12 +620,12 @@ void NestedNameSpecifierLocBuilder::MakeSuper(ASTContext &Context, SaveSourceLocation(ColonColonLoc, Buffer, BufferSize, BufferCapacity); } -void NestedNameSpecifierLocBuilder::MakeTrivial(ASTContext &Context, - NestedNameSpecifier *Qualifier, +void NestedNameSpecifierLocBuilder::MakeTrivial(ASTContext &Context, + NestedNameSpecifier *Qualifier, SourceRange R) { Representation = Qualifier; - - // Construct bogus (but well-formed) source information for the + + // Construct bogus (but well-formed) source information for the // nested-name-specifier. BufferSize = 0; SmallVector<NestedNameSpecifier *, 4> Stack; @@ -639,24 +639,24 @@ void NestedNameSpecifierLocBuilder::MakeTrivial(ASTContext &Context, case NestedNameSpecifier::NamespaceAlias: SaveSourceLocation(R.getBegin(), Buffer, BufferSize, BufferCapacity); break; - + case NestedNameSpecifier::TypeSpec: case NestedNameSpecifier::TypeSpecWithTemplate: { TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(QualType(NNS->getAsType(), 0), R.getBegin()); - SavePointer(TSInfo->getTypeLoc().getOpaqueData(), Buffer, BufferSize, + SavePointer(TSInfo->getTypeLoc().getOpaqueData(), Buffer, BufferSize, BufferCapacity); break; } - + case NestedNameSpecifier::Global: case NestedNameSpecifier::Super: break; } - + // Save the location of the '::'. - SaveSourceLocation(Stack.empty()? R.getEnd() : R.getBegin(), + SaveSourceLocation(Stack.empty()? R.getEnd() : R.getBegin(), Buffer, BufferSize, BufferCapacity); } } @@ -670,8 +670,8 @@ void NestedNameSpecifierLocBuilder::Adopt(NestedNameSpecifierLoc Other) { BufferSize = 0; return; } - - // Rather than copying the data (which is wasteful), "adopt" the + + // Rather than copying the data (which is wasteful), "adopt" the // pointer (which points into the ASTContext) but set the capacity to zero to // indicate that we don't own it. Representation = Other.getNestedNameSpecifier(); @@ -680,16 +680,16 @@ void NestedNameSpecifierLocBuilder::Adopt(NestedNameSpecifierLoc Other) { BufferCapacity = 0; } -NestedNameSpecifierLoc +NestedNameSpecifierLoc NestedNameSpecifierLocBuilder::getWithLocInContext(ASTContext &Context) const { if (!Representation) return NestedNameSpecifierLoc(); - + // If we adopted our data pointer from elsewhere in the AST context, there's // no need to copy the memory. if (BufferCapacity == 0) return NestedNameSpecifierLoc(Representation, Buffer); - + // FIXME: After copying the source-location information, should we free // our (temporary) buffer and adopt the ASTContext-allocated memory? // Doing so would optimize repeated calls to getWithLocInContext(). diff --git a/lib/AST/ParentMap.cpp b/lib/AST/ParentMap.cpp index bc57b20790d9..af2a480dc23f 100644 --- a/lib/AST/ParentMap.cpp +++ b/lib/AST/ParentMap.cpp @@ -137,7 +137,7 @@ Stmt *ParentMap::getParentIgnoreParenCasts(Stmt *S) const { } while (S && (isa<ParenExpr>(S) || isa<CastExpr>(S))); - return S; + return S; } Stmt *ParentMap::getParentIgnoreParenImpCasts(Stmt *S) const { diff --git a/lib/AST/RecordLayout.cpp b/lib/AST/RecordLayout.cpp index 37fe029f53bd..9db23d50d0af 100644 --- a/lib/AST/RecordLayout.cpp +++ b/lib/AST/RecordLayout.cpp @@ -30,10 +30,12 @@ void ASTRecordLayout::Destroy(ASTContext &Ctx) { ASTRecordLayout::ASTRecordLayout(const ASTContext &Ctx, CharUnits size, CharUnits alignment, + CharUnits unadjustedAlignment, CharUnits requiredAlignment, CharUnits datasize, ArrayRef<uint64_t> fieldoffsets) : Size(size), DataSize(datasize), Alignment(alignment), + UnadjustedAlignment(unadjustedAlignment), RequiredAlignment(requiredAlignment) { FieldOffsets.append(Ctx, fieldoffsets.begin(), fieldoffsets.end()); } @@ -41,6 +43,7 @@ ASTRecordLayout::ASTRecordLayout(const ASTContext &Ctx, CharUnits size, // Constructor for C++ records. ASTRecordLayout::ASTRecordLayout(const ASTContext &Ctx, CharUnits size, CharUnits alignment, + CharUnits unadjustedAlignment, CharUnits requiredAlignment, bool hasOwnVFPtr, bool hasExtendableVFPtr, CharUnits vbptroffset, @@ -57,6 +60,7 @@ ASTRecordLayout::ASTRecordLayout(const ASTContext &Ctx, const BaseOffsetsMapTy& BaseOffsets, const VBaseOffsetsMapTy& VBaseOffsets) : Size(size), DataSize(datasize), Alignment(alignment), + UnadjustedAlignment(unadjustedAlignment), RequiredAlignment(requiredAlignment), CXXInfo(new (Ctx) CXXRecordLayoutInfo) { FieldOffsets.append(Ctx, fieldoffsets.begin(), fieldoffsets.end()); @@ -87,5 +91,5 @@ ASTRecordLayout::ASTRecordLayout(const ASTContext &Ctx, "Primary base must be at offset 0!"); } } -#endif +#endif } diff --git a/lib/AST/RecordLayoutBuilder.cpp b/lib/AST/RecordLayoutBuilder.cpp index b4b09c7cecd7..6f71d5b83e62 100644 --- a/lib/AST/RecordLayoutBuilder.cpp +++ b/lib/AST/RecordLayoutBuilder.cpp @@ -105,7 +105,7 @@ struct ExternalLayout { class EmptySubobjectMap { const ASTContext &Context; uint64_t CharWidth; - + /// Class - The class whose empty entries we're keeping track of. const CXXRecordDecl *Class; @@ -113,35 +113,35 @@ class EmptySubobjectMap { typedef llvm::TinyPtrVector<const CXXRecordDecl *> ClassVectorTy; typedef llvm::DenseMap<CharUnits, ClassVectorTy> EmptyClassOffsetsMapTy; EmptyClassOffsetsMapTy EmptyClassOffsets; - + /// MaxEmptyClassOffset - The highest offset known to contain an empty /// base subobject. CharUnits MaxEmptyClassOffset; - + /// ComputeEmptySubobjectSizes - Compute the size of the largest base or /// member subobject that is empty. void ComputeEmptySubobjectSizes(); - + void AddSubobjectAtOffset(const CXXRecordDecl *RD, CharUnits Offset); - + void UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info, CharUnits Offset, bool PlacingEmptyBase); - - void UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD, + + void UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD, const CXXRecordDecl *Class, CharUnits Offset); void UpdateEmptyFieldSubobjects(const FieldDecl *FD, CharUnits Offset); - + /// AnyEmptySubobjectsBeyondOffset - Returns whether there are any empty /// subobjects beyond the given offset. bool AnyEmptySubobjectsBeyondOffset(CharUnits Offset) const { return Offset <= MaxEmptyClassOffset; } - CharUnits + CharUnits getFieldOffset(const ASTRecordLayout &Layout, unsigned FieldNo) const { uint64_t FieldOffset = Layout.getFieldOffset(FieldNo); - assert(FieldOffset % CharWidth == 0 && + assert(FieldOffset % CharWidth == 0 && "Field offset not at char boundary!"); return Context.toCharUnitsFromBits(FieldOffset); @@ -154,7 +154,7 @@ protected: bool CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info, CharUnits Offset); - bool CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD, + bool CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD, const CXXRecordDecl *Class, CharUnits Offset) const; bool CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD, @@ -228,7 +228,7 @@ void EmptySubobjectMap::ComputeEmptySubobjectSizes() { } bool -EmptySubobjectMap::CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD, +EmptySubobjectMap::CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD, CharUnits Offset) const { // We only need to check empty bases. if (!RD->isEmpty()) @@ -245,8 +245,8 @@ EmptySubobjectMap::CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD, // There is already an empty class of the same type at this offset. return false; } - -void EmptySubobjectMap::AddSubobjectAtOffset(const CXXRecordDecl *RD, + +void EmptySubobjectMap::AddSubobjectAtOffset(const CXXRecordDecl *RD, CharUnits Offset) { // We only care about empty bases. if (!RD->isEmpty()) @@ -257,9 +257,9 @@ void EmptySubobjectMap::AddSubobjectAtOffset(const CXXRecordDecl *RD, ClassVectorTy &Classes = EmptyClassOffsets[Offset]; if (std::find(Classes.begin(), Classes.end(), RD) != Classes.end()) return; - + Classes.push_back(RD); - + // Update the empty class offset. if (Offset > MaxEmptyClassOffset) MaxEmptyClassOffset = Offset; @@ -296,10 +296,10 @@ EmptySubobjectMap::CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info, return false; } } - + // Traverse all member variables. unsigned FieldNo = 0; - for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(), + for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(), E = Info->Class->field_end(); I != E; ++I, ++FieldNo) { if (I->isBitField()) continue; @@ -312,15 +312,15 @@ EmptySubobjectMap::CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info, return true; } -void EmptySubobjectMap::UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info, +void EmptySubobjectMap::UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info, CharUnits Offset, bool PlacingEmptyBase) { if (!PlacingEmptyBase && Offset >= SizeOfLargestEmptySubobject) { // We know that the only empty subobjects that can conflict with empty // subobject of non-empty bases, are empty bases that can be placed at - // offset zero. Because of this, we only need to keep track of empty base + // offset zero. Because of this, we only need to keep track of empty base // subobjects with offsets less than the size of the largest empty - // subobject for our class. + // subobject for our class. return; } @@ -338,7 +338,7 @@ void EmptySubobjectMap::UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info, if (Info->PrimaryVirtualBaseInfo) { BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo; - + if (Info == PrimaryVirtualBaseInfo->Derived) UpdateEmptyBaseSubobjects(PrimaryVirtualBaseInfo, Offset, PlacingEmptyBase); @@ -346,7 +346,7 @@ void EmptySubobjectMap::UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info, // Traverse all member variables. unsigned FieldNo = 0; - for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(), + for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(), E = Info->Class->field_end(); I != E; ++I, ++FieldNo) { if (I->isBitField()) continue; @@ -373,7 +373,7 @@ bool EmptySubobjectMap::CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info, } bool -EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD, +EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD, const CXXRecordDecl *Class, CharUnits Offset) const { // We don't have to keep looking past the maximum offset that's known to @@ -383,7 +383,7 @@ EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD, if (!CanPlaceSubobjectAtOffset(RD, Offset)) return false; - + const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); // Traverse all non-virtual bases. @@ -408,7 +408,7 @@ EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD, return false; } } - + // Traverse all member variables. unsigned FieldNo = 0; for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end(); @@ -417,7 +417,7 @@ EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD, continue; CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo); - + if (!CanPlaceFieldSubobjectAtOffset(*I, FieldOffset)) return false; } @@ -432,7 +432,7 @@ EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD, // contain an empty class. if (!AnyEmptySubobjectsBeyondOffset(Offset)) return true; - + QualType T = FD->getType(); if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) return CanPlaceFieldSubobjectAtOffset(RD, RD, Offset); @@ -454,7 +454,7 @@ EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD, // contain an empty class. if (!AnyEmptySubobjectsBeyondOffset(ElementOffset)) return true; - + if (!CanPlaceFieldSubobjectAtOffset(RD, RD, ElementOffset)) return false; @@ -466,23 +466,23 @@ EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD, } bool -EmptySubobjectMap::CanPlaceFieldAtOffset(const FieldDecl *FD, +EmptySubobjectMap::CanPlaceFieldAtOffset(const FieldDecl *FD, CharUnits Offset) { if (!CanPlaceFieldSubobjectAtOffset(FD, Offset)) return false; - + // We are able to place the member variable at this offset. // Make sure to update the empty base subobject map. UpdateEmptyFieldSubobjects(FD, Offset); return true; } -void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD, +void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD, const CXXRecordDecl *Class, CharUnits Offset) { // We know that the only empty subobjects that can conflict with empty // field subobjects are subobjects of empty bases that can be placed at offset - // zero. Because of this, we only need to keep track of empty field + // zero. Because of this, we only need to keep track of empty field // subobjects with offsets less than the size of the largest empty // subobject for our class. if (Offset >= SizeOfLargestEmptySubobject) @@ -512,7 +512,7 @@ void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD, UpdateEmptyFieldSubobjects(VBaseDecl, Class, VBaseOffset); } } - + // Traverse all member variables. unsigned FieldNo = 0; for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end(); @@ -525,7 +525,7 @@ void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD, UpdateEmptyFieldSubobjects(*I, FieldOffset); } } - + void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const FieldDecl *FD, CharUnits Offset) { QualType T = FD->getType(); @@ -543,13 +543,13 @@ void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const FieldDecl *FD, const CXXRecordDecl *RD = RT->getAsCXXRecordDecl(); const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); - + uint64_t NumElements = Context.getConstantArrayElementCount(AT); CharUnits ElementOffset = Offset; - + for (uint64_t I = 0; I != NumElements; ++I) { // We know that the only empty subobjects that can conflict with empty - // field subobjects are subobjects of empty bases that can be placed at + // field subobjects are subobjects of empty bases that can be placed at // offset zero. Because of this, we only need to keep track of empty field // subobjects with offsets less than the size of the largest empty // subobject for our class. @@ -582,23 +582,26 @@ protected: /// The alignment if attribute packed is not used. CharUnits UnpackedAlignment; + /// \brief The maximum of the alignments of top-level members. + CharUnits UnadjustedAlignment; + SmallVector<uint64_t, 16> FieldOffsets; /// Whether the external AST source has provided a layout for this /// record. unsigned UseExternalLayout : 1; - /// Whether we need to infer alignment, even when we have an + /// Whether we need to infer alignment, even when we have an /// externally-provided layout. unsigned InferAlignment : 1; - + /// Packed - Whether the record is packed or not. unsigned Packed : 1; unsigned IsUnion : 1; unsigned IsMac68kAlign : 1; - + unsigned IsMsStruct : 1; /// UnfilledBitsInLastUnit - If the last field laid out was a bitfield, @@ -662,6 +665,7 @@ protected: EmptySubobjectMap *EmptySubobjects) : Context(Context), EmptySubobjects(EmptySubobjects), Size(0), Alignment(CharUnits::One()), UnpackedAlignment(CharUnits::One()), + UnadjustedAlignment(CharUnits::One()), UseExternalLayout(false), InferAlignment(false), Packed(false), IsUnion(false), IsMac68kAlign(false), IsMsStruct(false), UnfilledBitsInLastUnit(0), LastBitfieldTypeSize(0), @@ -687,14 +691,14 @@ protected: /// BaseSubobjectInfoAllocator - Allocator for BaseSubobjectInfo objects. llvm::SpecificBumpPtrAllocator<BaseSubobjectInfo> BaseSubobjectInfoAllocator; - + typedef llvm::DenseMap<const CXXRecordDecl *, BaseSubobjectInfo *> BaseSubobjectInfoMapTy; /// VirtualBaseInfo - Map from all the (direct or indirect) virtual bases /// of the class we're laying out to their base subobject info. BaseSubobjectInfoMapTy VirtualBaseInfo; - + /// NonVirtualBaseInfo - Map from all the direct non-virtual bases of the /// class we're laying out to their base subobject info. BaseSubobjectInfoMapTy NonVirtualBaseInfo; @@ -705,7 +709,7 @@ protected: /// ComputeBaseSubobjectInfo - Compute the base subobject information for a /// single class and all of its base classes. - BaseSubobjectInfo *ComputeBaseSubobjectInfo(const CXXRecordDecl *RD, + BaseSubobjectInfo *ComputeBaseSubobjectInfo(const CXXRecordDecl *RD, bool IsVirtual, BaseSubobjectInfo *Derived); @@ -754,18 +758,18 @@ protected: /// /// \param Field The field whose offset is being queried. /// \param ComputedOffset The offset that we've computed for this field. - uint64_t updateExternalFieldOffset(const FieldDecl *Field, + uint64_t updateExternalFieldOffset(const FieldDecl *Field, uint64_t ComputedOffset); - + void CheckFieldPadding(uint64_t Offset, uint64_t UnpaddedOffset, uint64_t UnpackedOffset, unsigned UnpackedAlign, bool isPacked, const FieldDecl *D); DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID); - CharUnits getSize() const { + CharUnits getSize() const { assert(Size % Context.getCharWidth() == 0); - return Context.toCharUnitsFromBits(Size); + return Context.toCharUnitsFromBits(Size); } uint64_t getSizeInBits() const { return Size; } @@ -774,9 +778,9 @@ protected: CharUnits getAligment() const { return Alignment; } - CharUnits getDataSize() const { + CharUnits getDataSize() const { assert(DataSize % Context.getCharWidth() == 0); - return Context.toCharUnitsFromBits(DataSize); + return Context.toCharUnitsFromBits(DataSize); } uint64_t getDataSizeInBits() const { return DataSize; } @@ -867,7 +871,7 @@ void ItaniumRecordLayoutBuilder::DeterminePrimaryBase(const CXXRecordDecl *RD) { BaseSubobjectInfo *ItaniumRecordLayoutBuilder::ComputeBaseSubobjectInfo( const CXXRecordDecl *RD, bool IsVirtual, BaseSubobjectInfo *Derived) { BaseSubobjectInfo *Info; - + if (IsVirtual) { // Check if we already have info about this virtual base. BaseSubobjectInfo *&InfoSlot = VirtualBaseInfo[RD]; @@ -882,7 +886,7 @@ BaseSubobjectInfo *ItaniumRecordLayoutBuilder::ComputeBaseSubobjectInfo( } else { Info = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo; } - + Info->Class = RD; Info->IsVirtual = IsVirtual; Info->Derived = nullptr; @@ -898,10 +902,10 @@ BaseSubobjectInfo *ItaniumRecordLayoutBuilder::ComputeBaseSubobjectInfo( // This base does have a primary virtual base. PrimaryVirtualBase = Layout.getPrimaryBase(); assert(PrimaryVirtualBase && "Didn't have a primary virtual base!"); - + // Now check if we have base subobject info about this primary base. PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase); - + if (PrimaryVirtualBaseInfo) { if (PrimaryVirtualBaseInfo->Derived) { // We did have info about this primary base, and it turns out that it @@ -925,19 +929,19 @@ BaseSubobjectInfo *ItaniumRecordLayoutBuilder::ComputeBaseSubobjectInfo( Info->Bases.push_back(ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, Info)); } - + if (PrimaryVirtualBase && !PrimaryVirtualBaseInfo) { // Traversing the bases must have created the base info for our primary // virtual base. PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase); assert(PrimaryVirtualBaseInfo && "Did not create a primary virtual base!"); - + // Claim the primary virtual base as our primary virtual base. Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo; PrimaryVirtualBaseInfo->Derived = Info; } - + return Info; } @@ -990,7 +994,7 @@ void ItaniumRecordLayoutBuilder::LayoutNonVirtualBases( // Compute base subobject info. ComputeBaseSubobjectInfo(RD); - + // If we have a primary base class, lay it out. if (PrimaryBase) { if (PrimaryBaseIsVirtual) { @@ -1008,9 +1012,9 @@ void ItaniumRecordLayoutBuilder::LayoutNonVirtualBases( LayoutVirtualBase(PrimaryBaseInfo); } else { - BaseSubobjectInfo *PrimaryBaseInfo = + BaseSubobjectInfo *PrimaryBaseInfo = NonVirtualBaseInfo.lookup(PrimaryBase); - assert(PrimaryBaseInfo && + assert(PrimaryBaseInfo && "Did not find base info for non-virtual primary base!"); LayoutNonVirtualBase(PrimaryBaseInfo); @@ -1020,9 +1024,9 @@ void ItaniumRecordLayoutBuilder::LayoutNonVirtualBases( // primary base, add it in now. } else if (RD->isDynamicClass()) { assert(DataSize == 0 && "Vtable pointer must be at offset zero!"); - CharUnits PtrWidth = + CharUnits PtrWidth = Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0)); - CharUnits PtrAlign = + CharUnits PtrAlign = Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0)); EnsureVTablePointerAlignment(PtrAlign); HasOwnVFPtr = true; @@ -1070,14 +1074,14 @@ void ItaniumRecordLayoutBuilder::AddPrimaryVirtualBaseOffsets( // This base isn't interesting, it has no virtual bases. if (!Info->Class->getNumVBases()) return; - + // First, check if we have a virtual primary base to add offsets for. if (Info->PrimaryVirtualBaseInfo) { - assert(Info->PrimaryVirtualBaseInfo->IsVirtual && + assert(Info->PrimaryVirtualBaseInfo->IsVirtual && "Primary virtual base is not virtual!"); if (Info->PrimaryVirtualBaseInfo->Derived == Info) { // Add the offset. - assert(!VBases.count(Info->PrimaryVirtualBaseInfo->Class) && + assert(!VBases.count(Info->PrimaryVirtualBaseInfo->Class) && "primary vbase offset already exists!"); VBases.insert(std::make_pair(Info->PrimaryVirtualBaseInfo->Class, ASTRecordLayout::VBaseInfo(Offset, false))); @@ -1147,13 +1151,13 @@ void ItaniumRecordLayoutBuilder::LayoutVirtualBases( void ItaniumRecordLayoutBuilder::LayoutVirtualBase( const BaseSubobjectInfo *Base) { assert(!Base->Derived && "Trying to lay out a primary virtual base!"); - + // Layout the base. CharUnits Offset = LayoutBase(Base); // Add its base class offset. assert(!VBases.count(Base->Class) && "vbase offset already exists!"); - VBases.insert(std::make_pair(Base->Class, + VBases.insert(std::make_pair(Base->Class, ASTRecordLayout::VBaseInfo(Offset, false))); AddPrimaryVirtualBaseOffsets(Base, Offset); @@ -1163,9 +1167,9 @@ CharUnits ItaniumRecordLayoutBuilder::LayoutBase(const BaseSubobjectInfo *Base) { const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base->Class); - + CharUnits Offset; - + // Query the external layout to see if it provides an offset. bool HasExternalLayout = false; if (UseExternalLayout) { @@ -1174,7 +1178,7 @@ ItaniumRecordLayoutBuilder::LayoutBase(const BaseSubobjectInfo *Base) { else HasExternalLayout = External.getExternalVBaseOffset(Base->Class, Offset); } - + // Clang <= 6 incorrectly applied the 'packed' attribute to base classes. // Per GCC's documentation, it only applies to non-static data members. CharUnits UnpackedBaseAlign = Layout.getNonVirtualAlignment(); @@ -1220,7 +1224,7 @@ ItaniumRecordLayoutBuilder::LayoutBase(const BaseSubobjectInfo *Base) { InferAlignment = false; } } - + if (!Base->Class->isEmpty()) { // Update the data size. setDataSize(Offset + Layout.getNonVirtualSize()); @@ -1241,7 +1245,7 @@ void ItaniumRecordLayoutBuilder::InitializeLayout(const Decl *D) { IsMsStruct = RD->isMsStruct(Context); } - Packed = D->hasAttr<PackedAttr>(); + Packed = D->hasAttr<PackedAttr>(); // Honor the default struct packing maximum alignment flag. if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct) { @@ -1263,7 +1267,7 @@ void ItaniumRecordLayoutBuilder::InitializeLayout(const Decl *D) { if (unsigned MaxAlign = D->getMaxAlignment()) UpdateAlignment(Context.toCharUnitsFromBits(MaxAlign)); } - + // If there is an external AST source, ask it for the various offsets. if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) if (ExternalASTSource *Source = Context.getExternalSource()) { @@ -1417,7 +1421,7 @@ void ItaniumRecordLayoutBuilder::LayoutWideBitField(uint64_t FieldSize, setDataSize(std::max(getDataSizeInBits(), RoundedFieldSize)); FieldOffset = 0; } else { - // The bitfield is allocated starting at the next offset aligned + // The bitfield is allocated starting at the next offset aligned // appropriately for T', with length n bits. FieldOffset = llvm::alignTo(getDataSizeInBits(), Context.toBits(TypeAlign)); @@ -1609,7 +1613,7 @@ void ItaniumRecordLayoutBuilder::LayoutBitField(const FieldDecl *D) { bool AllowPadding = MaxFieldAlignment.isZero(); // Compute the real offset. - if (FieldSize == 0 || + if (FieldSize == 0 || (AllowPadding && (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize)) { FieldOffset = llvm::alignTo(FieldOffset, FieldAlign); @@ -1707,7 +1711,9 @@ void ItaniumRecordLayoutBuilder::LayoutBitField(const FieldDecl *D) { setSize(std::max(getSizeInBits(), getDataSizeInBits())); // Remember max struct/class alignment. - UpdateAlignment(Context.toCharUnitsFromBits(FieldAlign), + UnadjustedAlignment = + std::max(UnadjustedAlignment, Context.toCharUnitsFromBits(FieldAlign)); + UpdateAlignment(Context.toCharUnitsFromBits(FieldAlign), Context.toCharUnitsFromBits(UnpackedFieldAlign)); } @@ -1725,7 +1731,7 @@ void ItaniumRecordLayoutBuilder::LayoutField(const FieldDecl *D, LastBitfieldTypeSize = 0; bool FieldPacked = Packed || D->hasAttr<PackedAttr>(); - CharUnits FieldOffset = + CharUnits FieldOffset = IsUnion ? CharUnits::Zero() : getDataSize(); CharUnits FieldSize; CharUnits FieldAlign; @@ -1740,12 +1746,12 @@ void ItaniumRecordLayoutBuilder::LayoutField(const FieldDecl *D, FieldAlign = Context.getTypeAlignInChars(ATy->getElementType()); } else if (const ReferenceType *RT = D->getType()->getAs<ReferenceType>()) { unsigned AS = Context.getTargetAddressSpace(RT->getPointeeType()); - FieldSize = + FieldSize = Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(AS)); - FieldAlign = + FieldAlign = Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(AS)); } else { - std::pair<CharUnits, CharUnits> FieldInfo = + std::pair<CharUnits, CharUnits> FieldInfo = Context.getTypeInfoInChars(D->getType()); FieldSize = FieldInfo.first; FieldAlign = FieldInfo.second; @@ -1753,7 +1759,7 @@ void ItaniumRecordLayoutBuilder::LayoutField(const FieldDecl *D, if (IsMsStruct) { // If MS bitfield layout is required, figure out what type is being // laid out and align the field to the width of that type. - + // Resolve all typedefs down to their base type and round up the field // alignment if necessary. QualType T = Context.getBaseElementType(D->getType()); @@ -1799,7 +1805,7 @@ void ItaniumRecordLayoutBuilder::LayoutField(const FieldDecl *D, if (FieldPacked) FieldAlign = CharUnits::One(); - CharUnits MaxAlignmentInChars = + CharUnits MaxAlignmentInChars = Context.toCharUnitsFromBits(D->getMaxAlignment()); FieldAlign = std::max(FieldAlign, MaxAlignmentInChars); UnpackedFieldAlign = std::max(UnpackedFieldAlign, MaxAlignmentInChars); @@ -1817,12 +1823,12 @@ void ItaniumRecordLayoutBuilder::LayoutField(const FieldDecl *D, if (UseExternalLayout) { FieldOffset = Context.toCharUnitsFromBits( updateExternalFieldOffset(D, Context.toBits(FieldOffset))); - + if (!IsUnion && EmptySubobjects) { // Record the fact that we're placing a field at this offset. bool Allowed = EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset); (void)Allowed; - assert(Allowed && "Externally-placed field cannot be placed here"); + assert(Allowed && "Externally-placed field cannot be placed here"); } } else { if (!IsUnion && EmptySubobjects) { @@ -1833,12 +1839,12 @@ void ItaniumRecordLayoutBuilder::LayoutField(const FieldDecl *D, } } } - + // Place this field at the current location. FieldOffsets.push_back(Context.toBits(FieldOffset)); if (!UseExternalLayout) - CheckFieldPadding(Context.toBits(FieldOffset), UnpaddedFieldOffset, + CheckFieldPadding(Context.toBits(FieldOffset), UnpaddedFieldOffset, Context.toBits(UnpackedFieldOffset), Context.toBits(UnpackedFieldAlign), FieldPacked, D); @@ -1862,6 +1868,7 @@ void ItaniumRecordLayoutBuilder::LayoutField(const FieldDecl *D, setSize(std::max(getSizeInBits(), getDataSizeInBits())); // Remember max struct/class alignment. + UnadjustedAlignment = std::max(UnadjustedAlignment, FieldAlign); UpdateAlignment(FieldAlign, UnpackedFieldAlign); } @@ -1959,7 +1966,7 @@ ItaniumRecordLayoutBuilder::updateExternalFieldOffset(const FieldDecl *Field, Alignment = CharUnits::One(); InferAlignment = false; } - + // Use the externally-supplied field offset. return ExternalFieldOffset; } @@ -1990,7 +1997,7 @@ void ItaniumRecordLayoutBuilder::CheckFieldPadding( // be done by clients of the AST, such as codegen. if (D->getLocation().isInvalid()) return; - + unsigned CharBitNum = Context.getTargetInfo().getCharWidth(); // Warn if padding was introduced to the struct/class. @@ -2445,7 +2452,9 @@ void MicrosoftRecordLayoutBuilder::cxxLayout(const CXXRecordDecl *RD) { auto RoundingAlignment = Alignment; if (!MaxFieldAlignment.isZero()) RoundingAlignment = std::min(RoundingAlignment, MaxFieldAlignment); - NonVirtualSize = Size = Size.alignTo(RoundingAlignment); + if (!UseExternalLayout) + Size = Size.alignTo(RoundingAlignment); + NonVirtualSize = Size; RequiredAlignment = std::max( RequiredAlignment, Context.toCharUnitsFromBits(RD->getMaxAlignment())); layoutVirtualBases(RD); @@ -2646,21 +2655,16 @@ void MicrosoftRecordLayoutBuilder::layoutField(const FieldDecl *FD) { LastFieldIsNonZeroWidthBitfield = false; ElementInfo Info = getAdjustedElementInfo(FD); Alignment = std::max(Alignment, Info.Alignment); - if (IsUnion) { - placeFieldAtOffset(CharUnits::Zero()); - Size = std::max(Size, Info.Size); - } else { - CharUnits FieldOffset; - if (UseExternalLayout) { - FieldOffset = - Context.toCharUnitsFromBits(External.getExternalFieldOffset(FD)); - assert(FieldOffset >= Size && "field offset already allocated"); - } else { - FieldOffset = Size.alignTo(Info.Alignment); - } - placeFieldAtOffset(FieldOffset); - Size = FieldOffset + Info.Size; - } + CharUnits FieldOffset; + if (UseExternalLayout) + FieldOffset = + Context.toCharUnitsFromBits(External.getExternalFieldOffset(FD)); + else if (IsUnion) + FieldOffset = CharUnits::Zero(); + else + FieldOffset = Size.alignTo(Info.Alignment); + placeFieldAtOffset(FieldOffset); + Size = std::max(Size, FieldOffset + Info.Size); } void MicrosoftRecordLayoutBuilder::layoutBitField(const FieldDecl *FD) { @@ -2685,18 +2689,17 @@ void MicrosoftRecordLayoutBuilder::layoutBitField(const FieldDecl *FD) { } LastFieldIsNonZeroWidthBitfield = true; CurrentBitfieldSize = Info.Size; - if (IsUnion) { - placeFieldAtOffset(CharUnits::Zero()); - Size = std::max(Size, Info.Size); - // TODO: Add a Sema warning that MS ignores bitfield alignment in unions. - } else if (UseExternalLayout) { + if (UseExternalLayout) { auto FieldBitOffset = External.getExternalFieldOffset(FD); placeFieldAtBitOffset(FieldBitOffset); auto NewSize = Context.toCharUnitsFromBits( llvm::alignTo(FieldBitOffset + Width, Context.getCharWidth())); - assert(NewSize >= Size && "bit field offset already allocated"); - Size = NewSize; + Size = std::max(Size, NewSize); Alignment = std::max(Alignment, Info.Alignment); + } else if (IsUnion) { + placeFieldAtOffset(CharUnits::Zero()); + Size = std::max(Size, Info.Size); + // TODO: Add a Sema warning that MS ignores bitfield alignment in unions. } else { // Allocate a new block of memory and place the bitfield in it. CharUnits FieldOffset = Size.alignTo(Info.Alignment); @@ -2969,7 +2972,7 @@ ASTContext::getASTRecordLayout(const RecordDecl *D) const { if (D->hasExternalLexicalStorage() && !D->getDefinition()) getExternalSource()->CompleteType(const_cast<RecordDecl*>(D)); - + D = D->getDefinition(); assert(D && "Cannot get layout of forward declarations!"); assert(!D->isInvalidDecl() && "Cannot get layout of invalid decl!"); @@ -2988,7 +2991,8 @@ ASTContext::getASTRecordLayout(const RecordDecl *D) const { if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) { Builder.cxxLayout(RD); NewEntry = new (*this) ASTRecordLayout( - *this, Builder.Size, Builder.Alignment, Builder.RequiredAlignment, + *this, Builder.Size, Builder.Alignment, Builder.Alignment, + Builder.RequiredAlignment, Builder.HasOwnVFPtr, Builder.HasOwnVFPtr || Builder.PrimaryBase, Builder.VBPtrOffset, Builder.DataSize, Builder.FieldOffsets, Builder.NonVirtualSize, Builder.Alignment, CharUnits::Zero(), @@ -2998,7 +3002,8 @@ ASTContext::getASTRecordLayout(const RecordDecl *D) const { } else { Builder.layout(D); NewEntry = new (*this) ASTRecordLayout( - *this, Builder.Size, Builder.Alignment, Builder.RequiredAlignment, + *this, Builder.Size, Builder.Alignment, Builder.Alignment, + Builder.RequiredAlignment, Builder.Size, Builder.FieldOffsets); } } else { @@ -3019,7 +3024,7 @@ ASTContext::getASTRecordLayout(const RecordDecl *D) const { CharUnits NonVirtualSize = skipTailPadding ? DataSize : Builder.NonVirtualSize; NewEntry = new (*this) ASTRecordLayout( - *this, Builder.getSize(), Builder.Alignment, + *this, Builder.getSize(), Builder.Alignment, Builder.UnadjustedAlignment, /*RequiredAlignment : used by MS-ABI)*/ Builder.Alignment, Builder.HasOwnVFPtr, RD->isDynamicClass(), CharUnits::fromQuantity(-1), DataSize, Builder.FieldOffsets, @@ -3032,7 +3037,7 @@ ASTContext::getASTRecordLayout(const RecordDecl *D) const { Builder.Layout(D); NewEntry = new (*this) ASTRecordLayout( - *this, Builder.getSize(), Builder.Alignment, + *this, Builder.getSize(), Builder.Alignment, Builder.UnadjustedAlignment, /*RequiredAlignment : used by MS-ABI)*/ Builder.Alignment, Builder.getSize(), Builder.FieldOffsets); } @@ -3186,6 +3191,7 @@ ASTContext::getObjCLayout(const ObjCInterfaceDecl *D, const ASTRecordLayout *NewEntry = new (*this) ASTRecordLayout(*this, Builder.getSize(), Builder.Alignment, + Builder.UnadjustedAlignment, /*RequiredAlignment : used by MS-ABI)*/ Builder.Alignment, Builder.getDataSize(), @@ -3215,7 +3221,7 @@ static void PrintBitFieldOffset(raw_ostream &OS, CharUnits Offset, BufferOS << Begin << '-' << (Begin + Width - 1); } } - + OS << llvm::right_justify(Buffer, 10) << " | "; OS.indent(IndentLevel * 2); } @@ -3323,7 +3329,7 @@ static void DumpRecordLayout(raw_ostream &OS, const RecordDecl *RD, // Dump virtual bases. if (CXXRD && IncludeVirtualBases) { - const ASTRecordLayout::VBaseOffsetsMapTy &VtorDisps = + const ASTRecordLayout::VBaseOffsetsMapTy &VtorDisps = Layout.getVBaseOffsetsMap(); for (const CXXBaseSpecifier &Base : CXXRD->vbases()) { diff --git a/lib/AST/StmtOpenMP.cpp b/lib/AST/StmtOpenMP.cpp index 87bf5aaaa585..1258af7a2d37 100644 --- a/lib/AST/StmtOpenMP.cpp +++ b/lib/AST/StmtOpenMP.cpp @@ -1222,9 +1222,9 @@ OMPTargetParallelForSimdDirective *OMPTargetParallelForSimdDirective::Create( alignof(OMPClause *)); void *Mem = C.Allocate( Size + sizeof(OMPClause *) * Clauses.size() + - sizeof(Stmt *) * + sizeof(Stmt *) * numLoopChildren(CollapsedNum, OMPD_target_parallel_for_simd)); - OMPTargetParallelForSimdDirective *Dir = + OMPTargetParallelForSimdDirective *Dir = new (Mem) OMPTargetParallelForSimdDirective(StartLoc, EndLoc, CollapsedNum, Clauses.size()); Dir->setClauses(Clauses); @@ -1262,20 +1262,20 @@ OMPTargetParallelForSimdDirective::CreateEmpty(const ASTContext &C, alignof(OMPClause *)); void *Mem = C.Allocate( Size + sizeof(OMPClause *) * NumClauses + - sizeof(Stmt *) * + sizeof(Stmt *) * numLoopChildren(CollapsedNum, OMPD_target_parallel_for_simd)); return new (Mem) OMPTargetParallelForSimdDirective(CollapsedNum, NumClauses); } OMPTargetSimdDirective * -OMPTargetSimdDirective::Create(const ASTContext &C, SourceLocation StartLoc, +OMPTargetSimdDirective::Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs) { unsigned Size = llvm::alignTo(sizeof(OMPTargetSimdDirective), alignof(OMPClause *)); void *Mem = C.Allocate(Size + sizeof(OMPClause *) * Clauses.size() + - sizeof(Stmt *) * + sizeof(Stmt *) * numLoopChildren(CollapsedNum, OMPD_target_simd)); OMPTargetSimdDirective *Dir = new (Mem) OMPTargetSimdDirective(StartLoc, EndLoc, CollapsedNum, Clauses.size()); @@ -1303,7 +1303,7 @@ OMPTargetSimdDirective::CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned Size = llvm::alignTo(sizeof(OMPTargetSimdDirective), alignof(OMPClause *)); void *Mem = C.Allocate(Size + sizeof(OMPClause *) * NumClauses + - sizeof(Stmt *) * + sizeof(Stmt *) * numLoopChildren(CollapsedNum, OMPD_target_simd)); return new (Mem) OMPTargetSimdDirective(CollapsedNum, NumClauses); } diff --git a/lib/AST/StmtPrinter.cpp b/lib/AST/StmtPrinter.cpp index dad57de8940b..cbf26c036058 100644 --- a/lib/AST/StmtPrinter.cpp +++ b/lib/AST/StmtPrinter.cpp @@ -366,13 +366,13 @@ void StmtPrinter::VisitMSDependentExistsStmt(MSDependentExistsStmt *Node) { OS << "__if_exists ("; else OS << "__if_not_exists ("; - + if (NestedNameSpecifier *Qualifier = Node->getQualifierLoc().getNestedNameSpecifier()) Qualifier->print(OS, Policy); - + OS << Node->getNameInfo() << ") "; - + PrintRawCompoundStmt(Node->getSubStmt()); } @@ -990,7 +990,7 @@ void OMPClausePrinter::VisitOMPMapClause(OMPMapClause *Node) { OS << "map("; if (Node->getMapType() != OMPC_MAP_unknown) { if (Node->getMapTypeModifier() != OMPC_MAP_unknown) { - OS << getOpenMPSimpleClauseTypeName(OMPC_map, + OS << getOpenMPSimpleClauseTypeName(OMPC_map, Node->getMapTypeModifier()); OS << ','; } @@ -1645,12 +1645,12 @@ void StmtPrinter::VisitOffsetOfExpr(OffsetOfExpr *Node) { IdentifierInfo *Id = ON.getFieldName(); if (!Id) continue; - + if (PrintedSomething) OS << "."; else PrintedSomething = true; - OS << Id->getName(); + OS << Id->getName(); } OS << ")"; } @@ -2672,7 +2672,7 @@ void StmtPrinter::VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) { for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) { if (I > 0) OS << ", "; - + ObjCDictionaryElement Element = E->getKeyValueElement(I); Visit(Element.Key); OS << " : "; @@ -2781,7 +2781,7 @@ void StmtPrinter::VisitBlockExpr(BlockExpr *Node) { OS << "{ }"; } -void StmtPrinter::VisitOpaqueValueExpr(OpaqueValueExpr *Node) { +void StmtPrinter::VisitOpaqueValueExpr(OpaqueValueExpr *Node) { PrintExpr(Node->getSourceExpr()); } diff --git a/lib/AST/StmtProfile.cpp b/lib/AST/StmtProfile.cpp index 791ec569cc41..15653c4fd838 100644 --- a/lib/AST/StmtProfile.cpp +++ b/lib/AST/StmtProfile.cpp @@ -1277,25 +1277,24 @@ static Stmt::StmtClass DecodeOperatorCall(const CXXOperatorCallExpr *S, case OO_Arrow: case OO_Call: case OO_Conditional: - case OO_Coawait: case NUM_OVERLOADED_OPERATORS: llvm_unreachable("Invalid operator call kind"); - + case OO_Plus: if (S->getNumArgs() == 1) { UnaryOp = UO_Plus; return Stmt::UnaryOperatorClass; } - + BinaryOp = BO_Add; return Stmt::BinaryOperatorClass; - + case OO_Minus: if (S->getNumArgs() == 1) { UnaryOp = UO_Minus; return Stmt::UnaryOperatorClass; } - + BinaryOp = BO_Sub; return Stmt::BinaryOperatorClass; @@ -1304,14 +1303,14 @@ static Stmt::StmtClass DecodeOperatorCall(const CXXOperatorCallExpr *S, UnaryOp = UO_Deref; return Stmt::UnaryOperatorClass; } - + BinaryOp = BO_Mul; return Stmt::BinaryOperatorClass; case OO_Slash: BinaryOp = BO_Div; return Stmt::BinaryOperatorClass; - + case OO_Percent: BinaryOp = BO_Rem; return Stmt::BinaryOperatorClass; @@ -1325,10 +1324,10 @@ static Stmt::StmtClass DecodeOperatorCall(const CXXOperatorCallExpr *S, UnaryOp = UO_AddrOf; return Stmt::UnaryOperatorClass; } - + BinaryOp = BO_And; return Stmt::BinaryOperatorClass; - + case OO_Pipe: BinaryOp = BO_Or; return Stmt::BinaryOperatorClass; @@ -1352,7 +1351,7 @@ static Stmt::StmtClass DecodeOperatorCall(const CXXOperatorCallExpr *S, case OO_Greater: BinaryOp = BO_GT; return Stmt::BinaryOperatorClass; - + case OO_PlusEqual: BinaryOp = BO_AddAssign; return Stmt::CompoundAssignOperatorClass; @@ -1376,19 +1375,19 @@ static Stmt::StmtClass DecodeOperatorCall(const CXXOperatorCallExpr *S, case OO_CaretEqual: BinaryOp = BO_XorAssign; return Stmt::CompoundAssignOperatorClass; - + case OO_AmpEqual: BinaryOp = BO_AndAssign; return Stmt::CompoundAssignOperatorClass; - + case OO_PipeEqual: BinaryOp = BO_OrAssign; return Stmt::CompoundAssignOperatorClass; - + case OO_LessLess: BinaryOp = BO_Shl; return Stmt::BinaryOperatorClass; - + case OO_GreaterGreater: BinaryOp = BO_Shr; return Stmt::BinaryOperatorClass; @@ -1396,7 +1395,7 @@ static Stmt::StmtClass DecodeOperatorCall(const CXXOperatorCallExpr *S, case OO_LessLessEqual: BinaryOp = BO_ShlAssign; return Stmt::CompoundAssignOperatorClass; - + case OO_GreaterGreaterEqual: BinaryOp = BO_ShrAssign; return Stmt::CompoundAssignOperatorClass; @@ -1404,15 +1403,15 @@ static Stmt::StmtClass DecodeOperatorCall(const CXXOperatorCallExpr *S, case OO_EqualEqual: BinaryOp = BO_EQ; return Stmt::BinaryOperatorClass; - + case OO_ExclaimEqual: BinaryOp = BO_NE; return Stmt::BinaryOperatorClass; - + case OO_LessEqual: BinaryOp = BO_LE; return Stmt::BinaryOperatorClass; - + case OO_GreaterEqual: BinaryOp = BO_GE; return Stmt::BinaryOperatorClass; @@ -1420,17 +1419,17 @@ static Stmt::StmtClass DecodeOperatorCall(const CXXOperatorCallExpr *S, case OO_Spaceship: // FIXME: Update this once we support <=> expressions. llvm_unreachable("<=> expressions not supported yet"); - + case OO_AmpAmp: BinaryOp = BO_LAnd; return Stmt::BinaryOperatorClass; - + case OO_PipePipe: BinaryOp = BO_LOr; return Stmt::BinaryOperatorClass; case OO_PlusPlus: - UnaryOp = S->getNumArgs() == 1? UO_PreInc + UnaryOp = S->getNumArgs() == 1? UO_PreInc : UO_PostInc; return Stmt::UnaryOperatorClass; @@ -1446,11 +1445,15 @@ static Stmt::StmtClass DecodeOperatorCall(const CXXOperatorCallExpr *S, case OO_ArrowStar: BinaryOp = BO_PtrMemI; return Stmt::BinaryOperatorClass; - + case OO_Subscript: return Stmt::ArraySubscriptExprClass; + + case OO_Coawait: + UnaryOp = UO_Coawait; + return Stmt::UnaryOperatorClass; } - + llvm_unreachable("Invalid overloaded operator expression"); } @@ -1482,7 +1485,7 @@ void StmtProfiler::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *S) { Visit(S->getArg(I)); if (SC == Stmt::UnaryOperatorClass) ID.AddInteger(UnaryOp); - else if (SC == Stmt::BinaryOperatorClass || + else if (SC == Stmt::BinaryOperatorClass || SC == Stmt::CompoundAssignOperatorClass) ID.AddInteger(BinaryOp); else @@ -1843,7 +1846,7 @@ void StmtProfiler::VisitCoyieldExpr(const CoyieldExpr *S) { } void StmtProfiler::VisitOpaqueValueExpr(const OpaqueValueExpr *E) { - VisitExpr(E); + VisitExpr(E); } void StmtProfiler::VisitTypoExpr(const TypoExpr *E) { @@ -1962,7 +1965,7 @@ void StmtProfiler::VisitTemplateArgument(const TemplateArgument &Arg) { case TemplateArgument::TemplateExpansion: VisitTemplateName(Arg.getAsTemplateOrTemplatePattern()); break; - + case TemplateArgument::Declaration: VisitDecl(Arg.getAsDecl()); break; diff --git a/lib/AST/TemplateBase.cpp b/lib/AST/TemplateBase.cpp index 394e9f38bcfd..a78927d229b9 100644 --- a/lib/AST/TemplateBase.cpp +++ b/lib/AST/TemplateBase.cpp @@ -157,16 +157,16 @@ bool TemplateArgument::isInstantiationDependent() const { switch (getKind()) { case Null: llvm_unreachable("Should not have a NULL template argument"); - + case Type: return getAsType()->isInstantiationDependentType(); - + case Template: return getAsTemplate().isInstantiationDependent(); - + case TemplateExpansion: return true; - + case Declaration: if (DeclContext *DC = dyn_cast<DeclContext>(getAsDecl())) return DC->isDependentContext(); @@ -174,14 +174,14 @@ bool TemplateArgument::isInstantiationDependent() const { case NullPtr: return false; - + case Integral: // Never dependent return false; - + case Expression: return getAsExpr()->isInstantiationDependent(); - + case Pack: for (const auto &P : pack_elements()) if (P.isInstantiationDependent()) @@ -197,17 +197,17 @@ bool TemplateArgument::isPackExpansion() const { case Null: case Declaration: case Integral: - case Pack: + case Pack: case Template: case NullPtr: return false; - + case TemplateExpansion: return true; - + case Type: return isa<PackExpansionType>(getAsType()); - + case Expression: return isa<PackExpansionExpr>(getAsExpr()); } @@ -233,7 +233,7 @@ bool TemplateArgument::containsUnexpandedParameterPack() const { if (getAsTemplate().containsUnexpandedParameterPack()) return true; break; - + case Expression: if (getAsExpr()->containsUnexpandedParameterPack()) return true; @@ -254,8 +254,8 @@ Optional<unsigned> TemplateArgument::getNumTemplateExpansions() const { assert(getKind() == TemplateExpansion); if (TemplateArg.NumExpansions) return TemplateArg.NumExpansions - 1; - - return None; + + return None; } QualType TemplateArgument::getNonTypeTemplateArgumentType() const { @@ -319,7 +319,7 @@ void TemplateArgument::Profile(llvm::FoldingSetNodeID &ID, } break; } - + case Integral: getAsIntegral().Profile(ID); getIntegralType().Profile(ID); @@ -342,7 +342,7 @@ bool TemplateArgument::structurallyEquals(const TemplateArgument &Other) const { switch (getKind()) { case Null: case Type: - case Expression: + case Expression: case Template: case TemplateExpansion: case NullPtr: @@ -368,14 +368,14 @@ bool TemplateArgument::structurallyEquals(const TemplateArgument &Other) const { TemplateArgument TemplateArgument::getPackExpansionPattern() const { assert(isPackExpansion()); - + switch (getKind()) { case Type: return getAsType()->getAs<PackExpansionType>()->getPattern(); - + case Expression: return cast<PackExpansionExpr>(getAsExpr())->getPattern(); - + case TemplateExpansion: return TemplateArgument(getAsTemplateOrTemplatePattern()); @@ -391,20 +391,20 @@ TemplateArgument TemplateArgument::getPackExpansionPattern() const { llvm_unreachable("Invalid TemplateArgument Kind!"); } -void TemplateArgument::print(const PrintingPolicy &Policy, +void TemplateArgument::print(const PrintingPolicy &Policy, raw_ostream &Out) const { switch (getKind()) { case Null: Out << "(no value)"; break; - + case Type: { PrintingPolicy SubPolicy(Policy); SubPolicy.SuppressStrongLifetime = true; getAsType().print(Out, SubPolicy); break; } - + case Declaration: { NamedDecl *ND = getAsDecl(); Out << '&'; @@ -429,15 +429,15 @@ void TemplateArgument::print(const PrintingPolicy &Policy, getAsTemplateOrTemplatePattern().print(Out, Policy); Out << "..."; break; - + case Integral: printIntegral(*this, Out, Policy); break; - + case Expression: getAsExpr()->printPretty(Out, nullptr, Policy); break; - + case Pack: Out << "<"; bool First = true; @@ -446,11 +446,11 @@ void TemplateArgument::print(const PrintingPolicy &Policy, First = false; else Out << ", "; - + P.print(Policy, Out); } Out << ">"; - break; + break; } } @@ -486,13 +486,13 @@ SourceRange TemplateArgumentLoc::getSourceRange() const { case TemplateArgument::Template: if (getTemplateQualifierLoc()) - return SourceRange(getTemplateQualifierLoc().getBeginLoc(), + return SourceRange(getTemplateQualifierLoc().getBeginLoc(), getTemplateNameLoc()); return SourceRange(getTemplateNameLoc()); case TemplateArgument::TemplateExpansion: if (getTemplateQualifierLoc()) - return SourceRange(getTemplateQualifierLoc().getBeginLoc(), + return SourceRange(getTemplateQualifierLoc().getBeginLoc(), getTemplateEllipsisLoc()); return SourceRange(getTemplateNameLoc(), getTemplateEllipsisLoc()); @@ -514,19 +514,19 @@ const DiagnosticBuilder &clang::operator<<(const DiagnosticBuilder &DB, // This is bad, but not as bad as crashing because of argument // count mismatches. return DB << "(null template argument)"; - + case TemplateArgument::Type: return DB << Arg.getAsType(); - + case TemplateArgument::Declaration: return DB << Arg.getAsDecl(); case TemplateArgument::NullPtr: return DB << "nullptr"; - + case TemplateArgument::Integral: return DB << Arg.getAsIntegral().toString(10); - + case TemplateArgument::Template: return DB << Arg.getAsTemplate(); @@ -545,7 +545,7 @@ const DiagnosticBuilder &clang::operator<<(const DiagnosticBuilder &DB, Arg.getAsExpr()->printPretty(OS, nullptr, Policy); return DB << OS.str(); } - + case TemplateArgument::Pack: { // FIXME: We're guessing at LangOptions! SmallString<32> Str; diff --git a/lib/AST/TemplateName.cpp b/lib/AST/TemplateName.cpp index 548468ed17cd..0a7a6bc3c6a7 100644 --- a/lib/AST/TemplateName.cpp +++ b/lib/AST/TemplateName.cpp @@ -31,7 +31,7 @@ using namespace clang; -TemplateArgument +TemplateArgument SubstTemplateTemplateParmPackStorage::getArgumentPack() const { return TemplateArgument(llvm::makeArrayRef(Arguments, size())); } @@ -40,7 +40,7 @@ void SubstTemplateTemplateParmStorage::Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, Parameter, Replacement); } -void SubstTemplateTemplateParmStorage::Profile(llvm::FoldingSetNodeID &ID, +void SubstTemplateTemplateParmStorage::Profile(llvm::FoldingSetNodeID &ID, TemplateTemplateParmDecl *parameter, TemplateName replacement) { ID.AddPointer(parameter); @@ -52,7 +52,7 @@ void SubstTemplateTemplateParmPackStorage::Profile(llvm::FoldingSetNodeID &ID, Profile(ID, Context, Parameter, getArgumentPack()); } -void SubstTemplateTemplateParmPackStorage::Profile(llvm::FoldingSetNodeID &ID, +void SubstTemplateTemplateParmPackStorage::Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context, TemplateTemplateParmDecl *Parameter, const TemplateArgument &ArgPack) { @@ -180,7 +180,7 @@ bool TemplateName::isInstantiationDependent() const { if (QTN->getQualifier()->isInstantiationDependent()) return true; } - + return isDependent(); } @@ -191,7 +191,7 @@ bool TemplateName::containsUnexpandedParameterPack() const { } if (TemplateDecl *Template = getAsTemplateDecl()) { - if (TemplateTemplateParmDecl *TTP + if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(Template)) return TTP->isParameterPack(); @@ -199,7 +199,7 @@ bool TemplateName::containsUnexpandedParameterPack() const { } if (DependentTemplateName *DTN = getAsDependentTemplateName()) - return DTN->getQualifier() && + return DTN->getQualifier() && DTN->getQualifier()->containsUnexpandedParameterPack(); return getAsSubstTemplateTemplateParmPack() != nullptr; @@ -220,7 +220,7 @@ TemplateName::print(raw_ostream &OS, const PrintingPolicy &Policy, if (!SuppressNNS && DTN->getQualifier()) DTN->getQualifier()->print(OS, Policy); OS << "template "; - + if (DTN->isIdentifier()) OS << DTN->getIdentifier()->getName(); else diff --git a/lib/AST/Type.cpp b/lib/AST/Type.cpp index fad8c0d1c6b2..f79a59712a41 100644 --- a/lib/AST/Type.cpp +++ b/lib/AST/Type.cpp @@ -138,14 +138,14 @@ unsigned ConstantArrayType::getNumAddressingBits(const ASTContext &Context, SizeExtended.getBitWidth()) * 2); llvm::APSInt TotalSize(llvm::APInt(SizeExtended.getBitWidth(), ElementSize)); - TotalSize *= SizeExtended; + TotalSize *= SizeExtended; return TotalSize.getActiveBits(); } unsigned ConstantArrayType::getMaxSizeBits(const ASTContext &Context) { unsigned Bits = Context.getTypeSize(Context.getSizeType()); - + // Limit the number of bits in size_t so that maximal bit size fits 64 bit // integer (see PR8256). We can do this as currently there is no hardware // that supports full 64-bit virtual space. @@ -155,7 +155,7 @@ unsigned ConstantArrayType::getMaxSizeBits(const ASTContext &Context) { return Bits; } -DependentSizedArrayType::DependentSizedArrayType(const ASTContext &Context, +DependentSizedArrayType::DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can, Expr *e, ArraySizeModifier sm, unsigned tq, @@ -201,8 +201,8 @@ void DependentVectorType::Profile(llvm::FoldingSetNodeID &ID, DependentSizedExtVectorType::DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType, - QualType can, - Expr *SizeExpr, + QualType can, + Expr *SizeExpr, SourceLocation loc) : Type(DependentSizedExtVector, can, /*Dependent=*/true, /*InstantiationDependent=*/true, @@ -249,7 +249,7 @@ VectorType::VectorType(TypeClass tc, QualType vecType, unsigned nElements, : Type(tc, canonType, vecType->isDependentType(), vecType->isInstantiationDependentType(), vecType->isVariablyModifiedType(), - vecType->containsUnexpandedParameterPack()), + vecType->containsUnexpandedParameterPack()), ElementType(vecType) { VectorTypeBits.VecKind = vecKind; VectorTypeBits.NumElements = nElements; @@ -629,9 +629,9 @@ ObjCObjectType::ObjCObjectType(QualType Canonical, QualType Base, ArrayRef<QualType> typeArgs, ArrayRef<ObjCProtocolDecl *> protocols, bool isKindOf) - : Type(ObjCObject, Canonical, Base->isDependentType(), - Base->isInstantiationDependentType(), - Base->isVariablyModifiedType(), + : Type(ObjCObject, Canonical, Base->isDependentType(), + Base->isInstantiationDependentType(), + Base->isVariablyModifiedType(), Base->containsUnexpandedParameterPack()), BaseType(Base) { ObjCObjectTypeBits.IsKindOf = isKindOf; @@ -657,7 +657,7 @@ ObjCObjectType::ObjCObjectType(QualType Canonical, QualType Base, initialize(protocols); } -bool ObjCObjectType::isSpecialized() const { +bool ObjCObjectType::isSpecialized() const { // If we have type arguments written here, the type is specialized. if (ObjCObjectTypeBits.NumTypeArgs > 0) return true; @@ -744,7 +744,7 @@ namespace { /// Visitor used by simpleTransform() to perform the transformation. template<typename F> -struct SimpleTransformVisitor +struct SimpleTransformVisitor : public TypeVisitor<SimpleTransformVisitor<F>, QualType> { ASTContext &Ctx; F &&TheFunc; @@ -769,7 +769,7 @@ public: TRIVIAL_TYPE_CLASS(Builtin) - QualType VisitComplexType(const ComplexType *T) { + QualType VisitComplexType(const ComplexType *T) { QualType elementType = recurse(T->getElementType()); if (elementType.isNull()) return {}; @@ -807,7 +807,7 @@ public: if (pointeeType.isNull()) return {}; - if (pointeeType.getAsOpaquePtr() + if (pointeeType.getAsOpaquePtr() == T->getPointeeTypeAsWritten().getAsOpaquePtr()) return QualType(T, 0); @@ -819,7 +819,7 @@ public: if (pointeeType.isNull()) return {}; - if (pointeeType.getAsOpaquePtr() + if (pointeeType.getAsOpaquePtr() == T->getPointeeTypeAsWritten().getAsOpaquePtr()) return QualType(T, 0); @@ -834,7 +834,7 @@ public: if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr()) return QualType(T, 0); - return Ctx.getMemberPointerType(pointeeType, T->getClass()); + return Ctx.getMemberPointerType(pointeeType, T->getClass()); } QualType VisitConstantArrayType(const ConstantArrayType *T) { @@ -876,7 +876,7 @@ public: T->getIndexTypeCVRQualifiers()); } - QualType VisitVectorType(const VectorType *T) { + QualType VisitVectorType(const VectorType *T) { QualType elementType = recurse(T->getElementType()); if (elementType.isNull()) return {}; @@ -884,11 +884,11 @@ public: if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr()) return QualType(T, 0); - return Ctx.getVectorType(elementType, T->getNumElements(), + return Ctx.getVectorType(elementType, T->getNumElements(), T->getVectorKind()); } - QualType VisitExtVectorType(const ExtVectorType *T) { + QualType VisitExtVectorType(const ExtVectorType *T) { QualType elementType = recurse(T->getElementType()); if (elementType.isNull()) return {}; @@ -899,7 +899,7 @@ public: return Ctx.getExtVectorType(elementType, T->getNumElements()); } - QualType VisitFunctionNoProtoType(const FunctionNoProtoType *T) { + QualType VisitFunctionNoProtoType(const FunctionNoProtoType *T) { QualType returnType = recurse(T->getReturnType()); if (returnType.isNull()) return {}; @@ -910,7 +910,7 @@ public: return Ctx.getFunctionNoProtoType(returnType, T->getExtInfo()); } - QualType VisitFunctionProtoType(const FunctionProtoType *T) { + QualType VisitFunctionProtoType(const FunctionProtoType *T) { QualType returnType = recurse(T->getReturnType()); if (returnType.isNull()) return {}; @@ -938,7 +938,7 @@ public: QualType newExceptionType = recurse(exceptionType); if (newExceptionType.isNull()) return {}; - + if (newExceptionType.getAsOpaquePtr() != exceptionType.getAsOpaquePtr()) exceptionChanged = true; @@ -958,7 +958,7 @@ public: return Ctx.getFunctionType(returnType, paramTypes, info); } - QualType VisitParenType(const ParenType *T) { + QualType VisitParenType(const ParenType *T) { QualType innerType = recurse(T->getInnerType()); if (innerType.isNull()) return {}; @@ -972,7 +972,7 @@ public: TRIVIAL_TYPE_CLASS(Typedef) TRIVIAL_TYPE_CLASS(ObjCTypeParam) - QualType VisitAdjustedType(const AdjustedType *T) { + QualType VisitAdjustedType(const AdjustedType *T) { QualType originalType = recurse(T->getOriginalType()); if (originalType.isNull()) return {}; @@ -981,20 +981,20 @@ public: if (adjustedType.isNull()) return {}; - if (originalType.getAsOpaquePtr() + if (originalType.getAsOpaquePtr() == T->getOriginalType().getAsOpaquePtr() && adjustedType.getAsOpaquePtr() == T->getAdjustedType().getAsOpaquePtr()) return QualType(T, 0); return Ctx.getAdjustedType(originalType, adjustedType); } - - QualType VisitDecayedType(const DecayedType *T) { + + QualType VisitDecayedType(const DecayedType *T) { QualType originalType = recurse(T->getOriginalType()); if (originalType.isNull()) return {}; - if (originalType.getAsOpaquePtr() + if (originalType.getAsOpaquePtr() == T->getOriginalType().getAsOpaquePtr()) return QualType(T, 0); @@ -1011,7 +1011,7 @@ public: // FIXME: Non-trivial to implement, but important for C++ TRIVIAL_TYPE_CLASS(Elaborated) - QualType VisitAttributedType(const AttributedType *T) { + QualType VisitAttributedType(const AttributedType *T) { QualType modifiedType = recurse(T->getModifiedType()); if (modifiedType.isNull()) return {}; @@ -1020,13 +1020,13 @@ public: if (equivalentType.isNull()) return {}; - if (modifiedType.getAsOpaquePtr() + if (modifiedType.getAsOpaquePtr() == T->getModifiedType().getAsOpaquePtr() && - equivalentType.getAsOpaquePtr() + equivalentType.getAsOpaquePtr() == T->getEquivalentType().getAsOpaquePtr()) return QualType(T, 0); - return Ctx.getAttributedType(T->getAttrKind(), modifiedType, + return Ctx.getAttributedType(T->getAttrKind(), modifiedType, equivalentType); } @@ -1035,7 +1035,7 @@ public: if (replacementType.isNull()) return {}; - if (replacementType.getAsOpaquePtr() + if (replacementType.getAsOpaquePtr() == T->getReplacementType().getAsOpaquePtr()) return QualType(T, 0); @@ -1054,7 +1054,7 @@ public: if (deducedType.isNull()) return {}; - if (deducedType.getAsOpaquePtr() + if (deducedType.getAsOpaquePtr() == T->getDeducedType().getAsOpaquePtr()) return QualType(T, 0); @@ -1088,7 +1088,7 @@ public: !typeArgChanged) return QualType(T, 0); - return Ctx.getObjCObjectType(baseType, typeArgs, + return Ctx.getObjCObjectType(baseType, typeArgs, llvm::makeArrayRef(T->qual_begin(), T->getNumProtocols()), T->isKindOfTypeAsWritten()); @@ -1101,7 +1101,7 @@ public: if (pointeeType.isNull()) return {}; - if (pointeeType.getAsOpaquePtr() + if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr()) return QualType(T, 0); @@ -1113,7 +1113,7 @@ public: if (valueType.isNull()) return {}; - if (valueType.getAsOpaquePtr() + if (valueType.getAsOpaquePtr() == T->getValueType().getAsOpaquePtr()) return QualType(T, 0); @@ -1628,6 +1628,10 @@ CXXRecordDecl *Type::getAsCXXRecordDecl() const { return dyn_cast_or_null<CXXRecordDecl>(getAsTagDecl()); } +RecordDecl *Type::getAsRecordDecl() const { + return dyn_cast_or_null<RecordDecl>(getAsTagDecl()); +} + TagDecl *Type::getAsTagDecl() const { if (const auto *TT = getAs<TagType>()) return TT->getDecl(); @@ -1739,10 +1743,10 @@ bool Type::hasIntegerRepresentation() const { /// Determine whether this type is an integral type. /// -/// This routine determines whether the given type is an integral type per +/// This routine determines whether the given type is an integral type per /// C++ [basic.fundamental]p7. Although the C standard does not define the /// term "integral type", it has a similar term "integer type", and in C++ -/// the two terms are equivalent. However, C's "integer type" includes +/// the two terms are equivalent. However, C's "integer type" includes /// enumeration types, while C++'s "integer type" does not. The \c ASTContext /// parameter is used to determine whether we should be following the C or /// C++ rules when determining whether this type is an integral/integer type. @@ -1751,7 +1755,7 @@ bool Type::hasIntegerRepresentation() const { /// type", use this routine. /// /// For cases where C permits "an integer type" and C++ permits "an integral -/// or enumeration type", use \c isIntegralOrEnumerationType() instead. +/// or enumeration type", use \c isIntegralOrEnumerationType() instead. /// /// \param Ctx The context in which this type occurs. /// @@ -1862,12 +1866,12 @@ bool Type::isSignedIntegerOrEnumerationType() const { return BT->getKind() >= BuiltinType::Char_S && BT->getKind() <= BuiltinType::Int128; } - + if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) { if (ET->getDecl()->isComplete()) return ET->getDecl()->getIntegerType()->isSignedIntegerType(); } - + return false; } @@ -1902,12 +1906,12 @@ bool Type::isUnsignedIntegerOrEnumerationType() const { return BT->getKind() >= BuiltinType::Bool && BT->getKind() <= BuiltinType::UInt128; } - + if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) { if (ET->getDecl()->isComplete()) return ET->getDecl()->getIntegerType()->isUnsignedIntegerType(); } - + return false; } @@ -2111,16 +2115,16 @@ bool QualType::isCXX98PODType(const ASTContext &Context) const { // are PODs according to the standard. if (isNull()) return false; - + if ((*this)->isIncompleteArrayType()) return Context.getBaseElementType(*this).isCXX98PODType(Context); - + if ((*this)->isIncompleteType()) return false; if (hasNonTrivialObjCLifetime()) return false; - + QualType CanonicalType = getTypePtr()->CanonicalType; switch (CanonicalType->getTypeClass()) { // Everything not explicitly mentioned is not POD. @@ -2129,7 +2133,7 @@ bool QualType::isCXX98PODType(const ASTContext &Context) const { case Type::ConstantArray: // IncompleteArray is handled above. return Context.getBaseElementType(*this).isCXX98PODType(Context); - + case Type::ObjCObjectPointer: case Type::BlockPointer: case Type::Builtin: @@ -2159,27 +2163,27 @@ bool QualType::isTrivialType(const ASTContext &Context) const { // are PODs according to the standard. if (isNull()) return false; - + if ((*this)->isArrayType()) return Context.getBaseElementType(*this).isTrivialType(Context); - + // Return false for incomplete types after skipping any incomplete array // types which are expressly allowed by the standard and thus our API. if ((*this)->isIncompleteType()) return false; - + if (hasNonTrivialObjCLifetime()) return false; - + QualType CanonicalType = getTypePtr()->CanonicalType; if (CanonicalType->isDependentType()) return false; - + // C++0x [basic.types]p9: // Scalar types, trivial class types, arrays of such types, and // cv-qualified versions of these types are collectively called trivial // types. - + // As an extension, Clang treats vector types as Scalar types. if (CanonicalType->isScalarType() || CanonicalType->isVectorType()) return true; @@ -2193,10 +2197,10 @@ bool QualType::isTrivialType(const ASTContext &Context) const { !ClassDecl->hasNonTrivialDefaultConstructor() && ClassDecl->isTriviallyCopyable(); } - + return true; } - + // No other types can match. return false; } @@ -2221,7 +2225,7 @@ bool QualType::isTriviallyCopyableType(const ASTContext &Context) const { // which are expressly allowed by the standard and thus our API. if (CanonicalType->isIncompleteType()) return false; - + // As an extension, Clang treats vector types as Scalar types. if (CanonicalType->isScalarType() || CanonicalType->isVectorType()) return true; @@ -2477,10 +2481,10 @@ bool Type::isPromotableIntegerType() const { if (this->isDependentType() || ET->getDecl()->getPromotionType().isNull() || ET->getDecl()->isScoped()) return false; - + return true; } - + return false; } @@ -2531,7 +2535,7 @@ TypeWithKeyword::getTagTypeKindForTypeSpec(unsigned TypeSpec) { case TST_union: return TTK_Union; case TST_enum: return TTK_Enum; } - + llvm_unreachable("Type specifier is not a tag type kind."); } @@ -2647,7 +2651,7 @@ const char *Type::getTypeClassName() const { #define TYPE(Derived, Base) case Derived: return #Derived; #include "clang/AST/TypeNodes.def" } - + llvm_unreachable("Invalid type class."); } @@ -2800,16 +2804,16 @@ StringRef BuiltinType::getName(const PrintingPolicy &Policy) const { QualType QualType::getNonLValueExprType(const ASTContext &Context) const { if (const auto *RefType = getTypePtr()->getAs<ReferenceType>()) return RefType->getPointeeType(); - + // C++0x [basic.lval]: - // Class prvalues can have cv-qualified types; non-class prvalues always + // Class prvalues can have cv-qualified types; non-class prvalues always // have cv-unqualified types. // // See also C99 6.3.2.1p2. if (!Context.getLangOpts().CPlusPlus || (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType())) return getUnqualifiedType(); - + return *this; } @@ -2993,7 +2997,7 @@ bool FunctionProtoType::isTemplateVariadic() const { for (unsigned ArgIdx = getNumParams(); ArgIdx; --ArgIdx) if (isa<PackExpansionType>(getParamType(ArgIdx - 1))) return true; - + return false; } @@ -3005,7 +3009,7 @@ void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result, // Note that valid type pointers are never ambiguous with anything else. // // The encoding grammar begins: - // type type* bool int bool + // type type* bool int bool // If that final bool is true, then there is a section for the EH spec: // bool type* // This is followed by an optional "consumed argument" section of the @@ -3013,7 +3017,7 @@ void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result, // bool* // Finally, we have the ext info and trailing return type flag: // int bool - // + // // There is no ambiguity between the consumed arguments and an empty EH // spec because of the leading 'bool' which unambiguously indicates // whether the following bool is the EH spec or part of the arguments. @@ -3074,7 +3078,7 @@ bool TypeOfExprType::isSugared() const { QualType TypeOfExprType::desugar() const { if (isSugared()) return getUnderlyingExpr()->getType(); - + return QualType(this, 0); } @@ -3098,7 +3102,7 @@ bool DecltypeType::isSugared() const { return !E->isInstantiationDependent(); } QualType DecltypeType::desugar() const { if (isSugared()) return getUnderlyingType(); - + return QualType(this, 0); } @@ -3174,6 +3178,7 @@ bool AttributedType::isQualifier() const { case AttributedType::attr_nonnull: case AttributedType::attr_nullable: case AttributedType::attr_null_unspecified: + case AttributedType::attr_lifetimebound: return true; // These aren't qualifiers; they rewrite the modified type to be a @@ -3243,6 +3248,7 @@ bool AttributedType::isCallingConv() const { case attr_null_unspecified: case attr_objc_kindof: case attr_nocf_check: + case attr_lifetimebound: return false; case attr_pcs: @@ -3274,7 +3280,7 @@ IdentifierInfo *TemplateTypeParmType::getIdentifier() const { } SubstTemplateTypeParmPackType:: -SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param, +SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param, QualType Canon, const TemplateArgument &ArgPack) : Type(SubstTemplateTypeParmPack, Canon, true, true, false, true), @@ -3331,7 +3337,7 @@ TemplateSpecializationType(TemplateName T, false, T.containsUnexpandedParameterPack()), Template(T), NumArgs(Args.size()), TypeAlias(!AliasedType.isNull()) { - assert(!T.getAsDependentTemplateName() && + assert(!T.getAsDependentTemplateName() && "Use DependentTemplateSpecializationType for dependent template-name"); assert((T.getKind() == TemplateName::Template || T.getKind() == TemplateName::SubstTemplateTemplateParm || @@ -3546,7 +3552,7 @@ static CachedProperties computeCachedProperties(const Type *T) { } // C++ [basic.link]p8: - // - it is a compound type (3.9.2) other than a class or enumeration, + // - it is a compound type (3.9.2) other than a class or enumeration, // compounded exclusively from types that have linkage; or case Type::Complex: return Cache::get(cast<ComplexType>(T)->getElementType()); @@ -3716,14 +3722,14 @@ Optional<NullabilityKind> Type::getNullability(const ASTContext &context) const QualType desugared = type.getSingleStepDesugaredType(context); if (desugared.getTypePtr() == type.getTypePtr()) return None; - + type = desugared; } while (true); } bool Type::canHaveNullability(bool ResultIfUnknown) const { QualType type = getCanonicalTypeInternal(); - + switch (type->getTypeClass()) { // We'll only see canonical types here. #define NON_CANONICAL_TYPE(Class, Parent) \ @@ -3957,7 +3963,7 @@ bool Type::isObjCLifetimeType() const { } /// Determine whether the given type T is a "bridgable" Objective-C type, -/// which is either an Objective-C object pointer type or an +/// which is either an Objective-C object pointer type or an bool Type::isObjCARCBridgableType() const { return isObjCObjectPointerType() || isBlockPointerType(); } @@ -3967,7 +3973,7 @@ bool Type::isCARCBridgableType() const { const auto *Pointer = getAs<PointerType>(); if (!Pointer) return false; - + QualType Pointee = Pointer->getPointeeType(); return Pointee->isVoidType() || Pointee->isRecordType(); } @@ -3980,7 +3986,7 @@ bool Type::hasSizedVLAType() const { if (const auto *ref = getAs<ReferenceType>()) return ref->getPointeeType()->hasSizedVLAType(); if (const ArrayType *arr = getAsArrayTypeUnsafe()) { - if (isa<VariableArrayType>(arr) && + if (isa<VariableArrayType>(arr) && cast<VariableArrayType>(arr)->getSizeExpr()) return true; diff --git a/lib/AST/TypeLoc.cpp b/lib/AST/TypeLoc.cpp index 6fa76e14a590..e4fd6f106e33 100644 --- a/lib/AST/TypeLoc.cpp +++ b/lib/AST/TypeLoc.cpp @@ -127,7 +127,7 @@ TypeLoc TypeLoc::getNextTypeLocImpl(TypeLoc TL) { /// Initializes a type location, and all of its children /// recursively, as if the entire tree had been written in the /// given location. -void TypeLoc::initializeImpl(ASTContext &Context, TypeLoc TL, +void TypeLoc::initializeImpl(ASTContext &Context, TypeLoc TL, SourceLocation Loc) { while (true) { switch (TL.getTypeLocClass()) { @@ -370,7 +370,7 @@ TypeSpecifierType BuiltinTypeLoc::getWrittenTypeSpec() const { case BuiltinType::SatULongFract: llvm_unreachable("Builtin type needs extra local data!"); // Fall through, if the impossible happens. - + case BuiltinType::NullPtr: case BuiltinType::Overload: case BuiltinType::Dependent: @@ -446,13 +446,13 @@ void ObjCTypeParamTypeLoc::initializeLocal(ASTContext &Context, setProtocolLoc(i, Loc); } -void ObjCObjectTypeLoc::initializeLocal(ASTContext &Context, +void ObjCObjectTypeLoc::initializeLocal(ASTContext &Context, SourceLocation Loc) { setHasBaseTypeAsWritten(true); setTypeArgsLAngleLoc(Loc); setTypeArgsRAngleLoc(Loc); for (unsigned i = 0, e = getNumTypeArgs(); i != e; ++i) { - setTypeArgTInfo(i, + setTypeArgTInfo(i, Context.getTrivialTypeSourceInfo( getTypePtr()->getTypeArgsAsWritten()[i], Loc)); } @@ -479,7 +479,7 @@ void UnaryTransformTypeLoc::initializeLocal(ASTContext &Context, Context.getTrivialTypeSourceInfo(getTypePtr()->getBaseType(), Loc)); } -void ElaboratedTypeLoc::initializeLocal(ASTContext &Context, +void ElaboratedTypeLoc::initializeLocal(ASTContext &Context, SourceLocation Loc) { setElaboratedKeywordLoc(Loc); NestedNameSpecifierLocBuilder Builder; @@ -487,7 +487,7 @@ void ElaboratedTypeLoc::initializeLocal(ASTContext &Context, setQualifierLoc(Builder.getWithLocInContext(Context)); } -void DependentNameTypeLoc::initializeLocal(ASTContext &Context, +void DependentNameTypeLoc::initializeLocal(ASTContext &Context, SourceLocation Loc) { setElaboratedKeywordLoc(Loc); NestedNameSpecifierLocBuilder Builder; @@ -516,14 +516,14 @@ DependentTemplateSpecializationTypeLoc::initializeLocal(ASTContext &Context, getArgInfos(), Loc); } -void TemplateSpecializationTypeLoc::initializeArgLocs(ASTContext &Context, +void TemplateSpecializationTypeLoc::initializeArgLocs(ASTContext &Context, unsigned NumArgs, const TemplateArgument *Args, TemplateArgumentLocInfo *ArgInfos, SourceLocation Loc) { for (unsigned i = 0, e = NumArgs; i != e; ++i) { switch (Args[i].getKind()) { - case TemplateArgument::Null: + case TemplateArgument::Null: llvm_unreachable("Impossible TemplateArgument"); case TemplateArgument::Integral: @@ -535,10 +535,10 @@ void TemplateSpecializationTypeLoc::initializeArgLocs(ASTContext &Context, case TemplateArgument::Expression: ArgInfos[i] = TemplateArgumentLocInfo(Args[i].getAsExpr()); break; - + case TemplateArgument::Type: ArgInfos[i] = TemplateArgumentLocInfo( - Context.getTrivialTypeSourceInfo(Args[i].getAsType(), + Context.getTrivialTypeSourceInfo(Args[i].getAsType(), Loc)); break; diff --git a/lib/AST/TypePrinter.cpp b/lib/AST/TypePrinter.cpp index c5e2244e26c5..e032c312aa12 100644 --- a/lib/AST/TypePrinter.cpp +++ b/lib/AST/TypePrinter.cpp @@ -52,14 +52,14 @@ namespace { class IncludeStrongLifetimeRAII { PrintingPolicy &Policy; bool Old; - + public: - explicit IncludeStrongLifetimeRAII(PrintingPolicy &Policy) + explicit IncludeStrongLifetimeRAII(PrintingPolicy &Policy) : Policy(Policy), Old(Policy.SuppressStrongLifetime) { if (!Policy.SuppressLifetimeQualifiers) Policy.SuppressStrongLifetime = false; } - + ~IncludeStrongLifetimeRAII() { Policy.SuppressStrongLifetime = Old; } @@ -68,13 +68,13 @@ namespace { class ParamPolicyRAII { PrintingPolicy &Policy; bool Old; - + public: - explicit ParamPolicyRAII(PrintingPolicy &Policy) + explicit ParamPolicyRAII(PrintingPolicy &Policy) : Policy(Policy), Old(Policy.SuppressSpecifiers) { Policy.SuppressSpecifiers = false; } - + ~ParamPolicyRAII() { Policy.SuppressSpecifiers = Old; } @@ -84,7 +84,7 @@ namespace { PrintingPolicy &Policy; bool SuppressTagKeyword; bool SuppressScope; - + public: explicit ElaboratedTypePolicyRAII(PrintingPolicy &Policy) : Policy(Policy) { SuppressTagKeyword = Policy.SuppressTagKeyword; @@ -92,13 +92,13 @@ namespace { Policy.SuppressTagKeyword = true; Policy.SuppressScope = true; } - + ~ElaboratedTypePolicyRAII() { Policy.SuppressTagKeyword = SuppressTagKeyword; Policy.SuppressScope = SuppressScope; } }; - + class TypePrinter { PrintingPolicy Policy; unsigned Indentation; @@ -193,7 +193,7 @@ bool TypePrinter::canPrefixQualifiers(const Type *T, TC = AT->desugar()->getTypeClass(); if (const auto *Subst = dyn_cast<SubstTemplateTypeParmType>(T)) TC = Subst->getReplacementType()->getTypeClass(); - + switch (TC) { case Type::Auto: case Type::Builtin: @@ -221,19 +221,19 @@ bool TypePrinter::canPrefixQualifiers(const Type *T, case Type::Pipe: CanPrefixQualifiers = true; break; - + case Type::ObjCObjectPointer: CanPrefixQualifiers = T->isObjCIdType() || T->isObjCClassType() || T->isObjCQualifiedIdType() || T->isObjCQualifiedClassType(); break; - + case Type::ConstantArray: case Type::IncompleteArray: case Type::VariableArray: case Type::DependentSizedArray: NeedARCStrongQualifier = true; LLVM_FALLTHROUGH; - + case Type::Adjusted: case Type::Decayed: case Type::Pointer: @@ -444,8 +444,8 @@ void TypePrinter::printRValueReferenceAfter(const RValueReferenceType *T, printAfter(Inner, OS); } -void TypePrinter::printMemberPointerBefore(const MemberPointerType *T, - raw_ostream &OS) { +void TypePrinter::printMemberPointerBefore(const MemberPointerType *T, + raw_ostream &OS) { IncludeStrongLifetimeRAII Strong(Policy); SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); printBefore(T->getPointeeType(), OS); @@ -461,8 +461,8 @@ void TypePrinter::printMemberPointerBefore(const MemberPointerType *T, OS << "::*"; } -void TypePrinter::printMemberPointerAfter(const MemberPointerType *T, - raw_ostream &OS) { +void TypePrinter::printMemberPointerAfter(const MemberPointerType *T, + raw_ostream &OS) { IncludeStrongLifetimeRAII Strong(Policy); SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); // Handle things like 'int (Cls::*A)[4];' correctly. @@ -472,14 +472,14 @@ void TypePrinter::printMemberPointerAfter(const MemberPointerType *T, printAfter(T->getPointeeType(), OS); } -void TypePrinter::printConstantArrayBefore(const ConstantArrayType *T, +void TypePrinter::printConstantArrayBefore(const ConstantArrayType *T, raw_ostream &OS) { IncludeStrongLifetimeRAII Strong(Policy); SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); printBefore(T->getElementType(), OS); } -void TypePrinter::printConstantArrayAfter(const ConstantArrayType *T, +void TypePrinter::printConstantArrayAfter(const ConstantArrayType *T, raw_ostream &OS) { OS << '['; if (T->getIndexTypeQualifiers().hasQualifiers()) { @@ -495,27 +495,27 @@ void TypePrinter::printConstantArrayAfter(const ConstantArrayType *T, printAfter(T->getElementType(), OS); } -void TypePrinter::printIncompleteArrayBefore(const IncompleteArrayType *T, +void TypePrinter::printIncompleteArrayBefore(const IncompleteArrayType *T, raw_ostream &OS) { IncludeStrongLifetimeRAII Strong(Policy); SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); printBefore(T->getElementType(), OS); } -void TypePrinter::printIncompleteArrayAfter(const IncompleteArrayType *T, +void TypePrinter::printIncompleteArrayAfter(const IncompleteArrayType *T, raw_ostream &OS) { OS << "[]"; printAfter(T->getElementType(), OS); } -void TypePrinter::printVariableArrayBefore(const VariableArrayType *T, +void TypePrinter::printVariableArrayBefore(const VariableArrayType *T, raw_ostream &OS) { IncludeStrongLifetimeRAII Strong(Policy); SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); printBefore(T->getElementType(), OS); } -void TypePrinter::printVariableArrayAfter(const VariableArrayType *T, +void TypePrinter::printVariableArrayAfter(const VariableArrayType *T, raw_ostream &OS) { OS << '['; if (T->getIndexTypeQualifiers().hasQualifiers()) { @@ -555,7 +555,7 @@ void TypePrinter::printDecayedAfter(const DecayedType *T, raw_ostream &OS) { } void TypePrinter::printDependentSizedArrayBefore( - const DependentSizedArrayType *T, + const DependentSizedArrayType *T, raw_ostream &OS) { IncludeStrongLifetimeRAII Strong(Policy); SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); @@ -563,7 +563,7 @@ void TypePrinter::printDependentSizedArrayBefore( } void TypePrinter::printDependentSizedArrayAfter( - const DependentSizedArrayType *T, + const DependentSizedArrayType *T, raw_ostream &OS) { OS << '['; if (T->getSizeExpr()) @@ -587,22 +587,22 @@ void TypePrinter::printDependentAddressSpaceAfter( } void TypePrinter::printDependentSizedExtVectorBefore( - const DependentSizedExtVectorType *T, - raw_ostream &OS) { + const DependentSizedExtVectorType *T, + raw_ostream &OS) { printBefore(T->getElementType(), OS); } void TypePrinter::printDependentSizedExtVectorAfter( - const DependentSizedExtVectorType *T, - raw_ostream &OS) { + const DependentSizedExtVectorType *T, + raw_ostream &OS) { OS << " __attribute__((ext_vector_type("; if (T->getSizeExpr()) T->getSizeExpr()->printPretty(OS, nullptr, Policy); - OS << ")))"; + OS << ")))"; printAfter(T->getElementType(), OS); } -void TypePrinter::printVectorBefore(const VectorType *T, raw_ostream &OS) { +void TypePrinter::printVectorBefore(const VectorType *T, raw_ostream &OS) { switch (T->getVectorKind()) { case VectorType::AltiVecPixel: OS << "__vector __pixel "; @@ -632,7 +632,7 @@ void TypePrinter::printVectorBefore(const VectorType *T, raw_ostream &OS) { << T->getNumElements() << " * sizeof("; print(T->getElementType(), OS, StringRef()); - OS << ")))) "; + OS << ")))) "; printBefore(T->getElementType(), OS); break; } @@ -692,19 +692,19 @@ void TypePrinter::printDependentVectorAfter( } void TypePrinter::printExtVectorBefore(const ExtVectorType *T, - raw_ostream &OS) { + raw_ostream &OS) { printBefore(T->getElementType(), OS); } -void TypePrinter::printExtVectorAfter(const ExtVectorType *T, raw_ostream &OS) { +void TypePrinter::printExtVectorAfter(const ExtVectorType *T, raw_ostream &OS) { printAfter(T->getElementType(), OS); OS << " __attribute__((ext_vector_type("; OS << T->getNumElements(); OS << ")))"; } -void -FunctionProtoType::printExceptionSpecification(raw_ostream &OS, +void +FunctionProtoType::printExceptionSpecification(raw_ostream &OS, const PrintingPolicy &Policy) const { if (hasDynamicExceptionSpec()) { @@ -715,7 +715,7 @@ FunctionProtoType::printExceptionSpecification(raw_ostream &OS, for (unsigned I = 0, N = getNumExceptions(); I != N; ++I) { if (I) OS << ", "; - + OS << getExceptionType(I).stream(Policy); } OS << ')'; @@ -732,7 +732,7 @@ FunctionProtoType::printExceptionSpecification(raw_ostream &OS, } } -void TypePrinter::printFunctionProtoBefore(const FunctionProtoType *T, +void TypePrinter::printFunctionProtoBefore(const FunctionProtoType *T, raw_ostream &OS) { if (T->hasTrailingReturn()) { OS << "auto "; @@ -761,8 +761,8 @@ StringRef clang::getParameterABISpelling(ParameterABI ABI) { llvm_unreachable("bad parameter ABI kind"); } -void TypePrinter::printFunctionProtoAfter(const FunctionProtoType *T, - raw_ostream &OS) { +void TypePrinter::printFunctionProtoAfter(const FunctionProtoType *T, + raw_ostream &OS) { // If needed for precedence reasons, wrap the inner part in grouping parens. if (!HasEmptyPlaceHolder) OS << ')'; @@ -785,7 +785,7 @@ void TypePrinter::printFunctionProtoAfter(const FunctionProtoType *T, print(T->getParamType(i), OS, StringRef()); } } - + if (T->isVariadic()) { if (T->getNumParams()) OS << ", "; @@ -794,7 +794,7 @@ void TypePrinter::printFunctionProtoAfter(const FunctionProtoType *T, // Do not emit int() if we have a proto, emit 'int(void)'. OS << "void"; } - + OS << ')'; FunctionType::ExtInfo Info = T->getExtInfo(); @@ -902,8 +902,8 @@ void TypePrinter::printFunctionAfter(const FunctionType::ExtInfo &Info, OS << " __attribute__((nocf_check))"; } -void TypePrinter::printFunctionNoProtoBefore(const FunctionNoProtoType *T, - raw_ostream &OS) { +void TypePrinter::printFunctionNoProtoBefore(const FunctionNoProtoType *T, + raw_ostream &OS) { // If needed for precedence reasons, wrap the inner part in grouping parens. SaveAndRestore<bool> PrevPHIsEmpty(HasEmptyPlaceHolder, false); printBefore(T->getReturnType(), OS); @@ -911,13 +911,13 @@ void TypePrinter::printFunctionNoProtoBefore(const FunctionNoProtoType *T, OS << '('; } -void TypePrinter::printFunctionNoProtoAfter(const FunctionNoProtoType *T, +void TypePrinter::printFunctionNoProtoAfter(const FunctionNoProtoType *T, raw_ostream &OS) { // If needed for precedence reasons, wrap the inner part in grouping parens. if (!HasEmptyPlaceHolder) OS << ')'; SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); - + OS << "()"; printFunctionAfter(T->getExtInfo(), OS); printAfter(T->getReturnType(), OS); @@ -944,7 +944,7 @@ void TypePrinter::printUnresolvedUsingBefore(const UnresolvedUsingType *T, void TypePrinter::printUnresolvedUsingAfter(const UnresolvedUsingType *T, raw_ostream &OS) {} -void TypePrinter::printTypedefBefore(const TypedefType *T, raw_ostream &OS) { +void TypePrinter::printTypedefBefore(const TypedefType *T, raw_ostream &OS) { printTypeSpec(T->getDecl(), OS); } @@ -961,7 +961,7 @@ void TypePrinter::printTypeOfExprBefore(const TypeOfExprType *T, void TypePrinter::printTypeOfExprAfter(const TypeOfExprType *T, raw_ostream &OS) {} -void TypePrinter::printTypeOfBefore(const TypeOfType *T, raw_ostream &OS) { +void TypePrinter::printTypeOfBefore(const TypeOfType *T, raw_ostream &OS) { OS << "typeof("; print(T->getUnderlyingType(), OS, StringRef()); OS << ')'; @@ -970,7 +970,7 @@ void TypePrinter::printTypeOfBefore(const TypeOfType *T, raw_ostream &OS) { void TypePrinter::printTypeOfAfter(const TypeOfType *T, raw_ostream &OS) {} -void TypePrinter::printDecltypeBefore(const DecltypeType *T, raw_ostream &OS) { +void TypePrinter::printDecltypeBefore(const DecltypeType *T, raw_ostream &OS) { OS << "decltype("; if (T->getUnderlyingExpr()) T->getUnderlyingExpr()->printPretty(OS, nullptr, Policy); @@ -1008,7 +1008,7 @@ void TypePrinter::printUnaryTransformAfter(const UnaryTransformType *T, printAfter(T->getBaseType(), OS); } -void TypePrinter::printAutoBefore(const AutoType *T, raw_ostream &OS) { +void TypePrinter::printAutoBefore(const AutoType *T, raw_ostream &OS) { // If the type has been deduced, do not print 'auto'. if (!T->getDeducedType().isNull()) { printBefore(T->getDeducedType(), OS); @@ -1022,7 +1022,7 @@ void TypePrinter::printAutoBefore(const AutoType *T, raw_ostream &OS) { } } -void TypePrinter::printAutoAfter(const AutoType *T, raw_ostream &OS) { +void TypePrinter::printAutoAfter(const AutoType *T, raw_ostream &OS) { // If the type has been deduced, do not print 'auto'. if (!T->getDeducedType().isNull()) printAfter(T->getDeducedType(), OS); @@ -1079,7 +1079,7 @@ void TypePrinter::AppendScope(DeclContext *DC, raw_ostream &OS) { AppendScope(DC->getParent(), OS); if (const auto *NS = dyn_cast<NamespaceDecl>(DC)) { - if (Policy.SuppressUnwrittenScope && + if (Policy.SuppressUnwrittenScope && (NS->isAnonymousNamespace() || NS->isInline())) return; if (NS->getIdentifier()) @@ -1143,7 +1143,7 @@ void TypePrinter::printTag(TagDecl *D, raw_ostream &OS) { } else { OS << "anonymous"; } - + if (Policy.AnonymousTagLocations) { // Suppress the redundant tag keyword if we just printed one. // We don't have to worry about ElaboratedTypes here because you can't @@ -1188,14 +1188,14 @@ void TypePrinter::printRecordBefore(const RecordType *T, raw_ostream &OS) { void TypePrinter::printRecordAfter(const RecordType *T, raw_ostream &OS) {} -void TypePrinter::printEnumBefore(const EnumType *T, raw_ostream &OS) { +void TypePrinter::printEnumBefore(const EnumType *T, raw_ostream &OS) { printTag(T->getDecl(), OS); } void TypePrinter::printEnumAfter(const EnumType *T, raw_ostream &OS) {} -void TypePrinter::printTemplateTypeParmBefore(const TemplateTypeParmType *T, - raw_ostream &OS) { +void TypePrinter::printTemplateTypeParmBefore(const TemplateTypeParmType *T, + raw_ostream &OS) { if (IdentifierInfo *Id = T->getIdentifier()) OS << Id->getName(); else @@ -1203,40 +1203,40 @@ void TypePrinter::printTemplateTypeParmBefore(const TemplateTypeParmType *T, spaceBeforePlaceHolder(OS); } -void TypePrinter::printTemplateTypeParmAfter(const TemplateTypeParmType *T, +void TypePrinter::printTemplateTypeParmAfter(const TemplateTypeParmType *T, raw_ostream &OS) {} void TypePrinter::printSubstTemplateTypeParmBefore( - const SubstTemplateTypeParmType *T, - raw_ostream &OS) { + const SubstTemplateTypeParmType *T, + raw_ostream &OS) { IncludeStrongLifetimeRAII Strong(Policy); printBefore(T->getReplacementType(), OS); } void TypePrinter::printSubstTemplateTypeParmAfter( - const SubstTemplateTypeParmType *T, - raw_ostream &OS) { + const SubstTemplateTypeParmType *T, + raw_ostream &OS) { IncludeStrongLifetimeRAII Strong(Policy); printAfter(T->getReplacementType(), OS); } void TypePrinter::printSubstTemplateTypeParmPackBefore( - const SubstTemplateTypeParmPackType *T, - raw_ostream &OS) { + const SubstTemplateTypeParmPackType *T, + raw_ostream &OS) { IncludeStrongLifetimeRAII Strong(Policy); printTemplateTypeParmBefore(T->getReplacedParameter(), OS); } void TypePrinter::printSubstTemplateTypeParmPackAfter( - const SubstTemplateTypeParmPackType *T, - raw_ostream &OS) { + const SubstTemplateTypeParmPackType *T, + raw_ostream &OS) { IncludeStrongLifetimeRAII Strong(Policy); printTemplateTypeParmAfter(T->getReplacedParameter(), OS); } void TypePrinter::printTemplateSpecializationBefore( - const TemplateSpecializationType *T, - raw_ostream &OS) { + const TemplateSpecializationType *T, + raw_ostream &OS) { IncludeStrongLifetimeRAII Strong(Policy); T->getTemplateName().print(OS, Policy); @@ -1245,7 +1245,7 @@ void TypePrinter::printTemplateSpecializationBefore( } void TypePrinter::printTemplateSpecializationAfter( - const TemplateSpecializationType *T, + const TemplateSpecializationType *T, raw_ostream &OS) {} void TypePrinter::printInjectedClassNameBefore(const InjectedClassNameType *T, @@ -1279,7 +1279,7 @@ void TypePrinter::printElaboratedBefore(const ElaboratedType *T, if (Qualifier) Qualifier->print(OS, Policy); } - + ElaboratedTypePolicyRAII PolicyRAII(Policy); printBefore(T->getNamedType(), OS); } @@ -1309,13 +1309,13 @@ void TypePrinter::printParenAfter(const ParenType *T, raw_ostream &OS) { } void TypePrinter::printDependentNameBefore(const DependentNameType *T, - raw_ostream &OS) { + raw_ostream &OS) { OS << TypeWithKeyword::getKeywordName(T->getKeyword()); if (T->getKeyword() != ETK_None) OS << " "; - + T->getQualifier()->print(OS, Policy); - + OS << T->getIdentifier()->getName(); spaceBeforePlaceHolder(OS); } @@ -1324,7 +1324,7 @@ void TypePrinter::printDependentNameAfter(const DependentNameType *T, raw_ostream &OS) {} void TypePrinter::printDependentTemplateSpecializationBefore( - const DependentTemplateSpecializationType *T, raw_ostream &OS) { + const DependentTemplateSpecializationType *T, raw_ostream &OS) { IncludeStrongLifetimeRAII Strong(Policy); OS << TypeWithKeyword::getKeywordName(T->getKeyword()); @@ -1341,12 +1341,12 @@ void TypePrinter::printDependentTemplateSpecializationBefore( void TypePrinter::printDependentTemplateSpecializationAfter( const DependentTemplateSpecializationType *T, raw_ostream &OS) {} -void TypePrinter::printPackExpansionBefore(const PackExpansionType *T, +void TypePrinter::printPackExpansionBefore(const PackExpansionType *T, raw_ostream &OS) { printBefore(T->getPattern(), OS); } -void TypePrinter::printPackExpansionAfter(const PackExpansionType *T, +void TypePrinter::printPackExpansionAfter(const PackExpansionType *T, raw_ostream &OS) { printAfter(T->getPattern(), OS); OS << "..."; @@ -1443,9 +1443,27 @@ void TypePrinter::printAttributedAfter(const AttributedType *T, return; } + if (T->getAttrKind() == AttributedType::attr_lifetimebound) { + OS << " [[clang::lifetimebound]]"; + return; + } + OS << " __attribute__(("; switch (T->getAttrKind()) { - default: llvm_unreachable("This attribute should have been handled already"); + case AttributedType::attr_lifetimebound: + case AttributedType::attr_nonnull: + case AttributedType::attr_nullable: + case AttributedType::attr_null_unspecified: + case AttributedType::attr_objc_gc: + case AttributedType::attr_objc_inert_unsafe_unretained: + case AttributedType::attr_objc_kindof: + case AttributedType::attr_objc_ownership: + case AttributedType::attr_ptr32: + case AttributedType::attr_ptr64: + case AttributedType::attr_sptr: + case AttributedType::attr_uptr: + llvm_unreachable("This attribute should have been handled already"); + case AttributedType::attr_address_space: OS << "address_space("; // FIXME: printing the raw LangAS value is wrong. This should probably @@ -1489,36 +1507,6 @@ void TypePrinter::printAttributedAfter(const AttributedType *T, break; } - case AttributedType::attr_objc_gc: { - OS << "objc_gc("; - - QualType tmp = T->getEquivalentType(); - while (tmp.getObjCGCAttr() == Qualifiers::GCNone) { - QualType next = tmp->getPointeeType(); - if (next == tmp) break; - tmp = next; - } - - if (tmp.isObjCGCWeak()) - OS << "weak"; - else - OS << "strong"; - OS << ')'; - break; - } - - case AttributedType::attr_objc_ownership: - OS << "objc_ownership("; - switch (T->getEquivalentType().getObjCLifetime()) { - case Qualifiers::OCL_None: llvm_unreachable("no ownership!"); - case Qualifiers::OCL_ExplicitNone: OS << "none"; break; - case Qualifiers::OCL_Strong: OS << "strong"; break; - case Qualifiers::OCL_Weak: OS << "weak"; break; - case Qualifiers::OCL_Autoreleasing: OS << "autoreleasing"; break; - } - OS << ')'; - break; - case AttributedType::attr_ns_returns_retained: OS << "ns_returns_retained"; break; @@ -1561,13 +1549,13 @@ void TypePrinter::printAttributedAfter(const AttributedType *T, OS << "))"; } -void TypePrinter::printObjCInterfaceBefore(const ObjCInterfaceType *T, - raw_ostream &OS) { +void TypePrinter::printObjCInterfaceBefore(const ObjCInterfaceType *T, + raw_ostream &OS) { OS << T->getDecl()->getName(); spaceBeforePlaceHolder(OS); } -void TypePrinter::printObjCInterfaceAfter(const ObjCInterfaceType *T, +void TypePrinter::printObjCInterfaceAfter(const ObjCInterfaceType *T, raw_ostream &OS) {} void TypePrinter::printObjCTypeParamBefore(const ObjCTypeParamType *T, @@ -1640,7 +1628,7 @@ void TypePrinter::printObjCObjectAfter(const ObjCObjectType *T, return printAfter(T->getBaseType(), OS); } -void TypePrinter::printObjCObjectPointerBefore(const ObjCObjectPointerType *T, +void TypePrinter::printObjCObjectPointerBefore(const ObjCObjectPointerType *T, raw_ostream &OS) { printBefore(T->getPointeeType(), OS); @@ -1653,7 +1641,7 @@ void TypePrinter::printObjCObjectPointerBefore(const ObjCObjectPointerType *T, } } -void TypePrinter::printObjCObjectPointerAfter(const ObjCObjectPointerType *T, +void TypePrinter::printObjCObjectPointerAfter(const ObjCObjectPointerType *T, raw_ostream &OS) {} static @@ -1832,11 +1820,11 @@ void Qualifiers::print(raw_ostream &OS, const PrintingPolicy& Policy, switch (lifetime) { case Qualifiers::OCL_None: llvm_unreachable("none but true"); case Qualifiers::OCL_ExplicitNone: OS << "__unsafe_unretained"; break; - case Qualifiers::OCL_Strong: + case Qualifiers::OCL_Strong: if (!Policy.SuppressStrongLifetime) - OS << "__strong"; + OS << "__strong"; break; - + case Qualifiers::OCL_Weak: OS << "__weak"; break; case Qualifiers::OCL_Autoreleasing: OS << "__autoreleasing"; break; } diff --git a/lib/AST/VTTBuilder.cpp b/lib/AST/VTTBuilder.cpp index b946f10105f4..a3f3dbdfb4f9 100644 --- a/lib/AST/VTTBuilder.cpp +++ b/lib/AST/VTTBuilder.cpp @@ -32,11 +32,11 @@ using namespace clang; VTTBuilder::VTTBuilder(ASTContext &Ctx, const CXXRecordDecl *MostDerivedClass, bool GenerateDefinition) - : Ctx(Ctx), MostDerivedClass(MostDerivedClass), + : Ctx(Ctx), MostDerivedClass(MostDerivedClass), MostDerivedClassLayout(Ctx.getASTRecordLayout(MostDerivedClass)), GenerateDefinition(GenerateDefinition) { // Lay out this VTT. - LayoutVTT(BaseSubobject(MostDerivedClass, CharUnits::Zero()), + LayoutVTT(BaseSubobject(MostDerivedClass, CharUnits::Zero()), /*BaseIsVirtual=*/false); } @@ -69,22 +69,22 @@ void VTTBuilder::LayoutSecondaryVTTs(BaseSubobject Base) { cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(RD); - CharUnits BaseOffset = Base.getBaseOffset() + + CharUnits BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl); - + // Layout the VTT for this base. LayoutVTT(BaseSubobject(BaseDecl, BaseOffset), /*BaseIsVirtual=*/false); } } void -VTTBuilder::LayoutSecondaryVirtualPointers(BaseSubobject Base, +VTTBuilder::LayoutSecondaryVirtualPointers(BaseSubobject Base, bool BaseIsMorallyVirtual, uint64_t VTableIndex, const CXXRecordDecl *VTableClass, VisitedVirtualBasesSetTy &VBases) { const CXXRecordDecl *RD = Base.getBase(); - + // We're not interested in bases that don't have virtual bases, and not // morally virtual bases. if (!RD->getNumVBases() && !BaseIsMorallyVirtual) @@ -96,14 +96,14 @@ VTTBuilder::LayoutSecondaryVirtualPointers(BaseSubobject Base, // Itanium C++ ABI 2.6.2: // Secondary virtual pointers are present for all bases with either - // virtual bases or virtual function declarations overridden along a + // virtual bases or virtual function declarations overridden along a // virtual path. // // If the base class is not dynamic, we don't want to add it, nor any // of its base classes. if (!BaseDecl->isDynamicClass()) continue; - + bool BaseDeclIsMorallyVirtual = BaseIsMorallyVirtual; bool BaseDeclIsNonVirtualPrimaryBase = false; CharUnits BaseOffset; @@ -111,15 +111,15 @@ VTTBuilder::LayoutSecondaryVirtualPointers(BaseSubobject Base, // Ignore virtual bases that we've already visited. if (!VBases.insert(BaseDecl).second) continue; - + BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl); BaseDeclIsMorallyVirtual = true; } else { const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(RD); - - BaseOffset = Base.getBaseOffset() + + + BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl); - + if (!Layout.isPrimaryBaseVirtual() && Layout.getPrimaryBase() == BaseDecl) BaseDeclIsNonVirtualPrimaryBase = true; @@ -133,19 +133,19 @@ VTTBuilder::LayoutSecondaryVirtualPointers(BaseSubobject Base, if (!BaseDeclIsNonVirtualPrimaryBase && (BaseDecl->getNumVBases() || BaseDeclIsMorallyVirtual)) { // Add the vtable pointer. - AddVTablePointer(BaseSubobject(BaseDecl, BaseOffset), VTableIndex, + AddVTablePointer(BaseSubobject(BaseDecl, BaseOffset), VTableIndex, VTableClass); } // And lay out the secondary virtual pointers for the base class. LayoutSecondaryVirtualPointers(BaseSubobject(BaseDecl, BaseOffset), - BaseDeclIsMorallyVirtual, VTableIndex, + BaseDeclIsMorallyVirtual, VTableIndex, VTableClass, VBases); } } -void -VTTBuilder::LayoutSecondaryVirtualPointers(BaseSubobject Base, +void +VTTBuilder::LayoutSecondaryVirtualPointers(BaseSubobject Base, uint64_t VTableIndex) { VisitedVirtualBasesSetTy VBases; LayoutSecondaryVirtualPointers(Base, /*BaseIsMorallyVirtual=*/false, @@ -155,21 +155,21 @@ VTTBuilder::LayoutSecondaryVirtualPointers(BaseSubobject Base, void VTTBuilder::LayoutVirtualVTTs(const CXXRecordDecl *RD, VisitedVirtualBasesSetTy &VBases) { for (const auto &I : RD->bases()) { - const CXXRecordDecl *BaseDecl = + const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); - + // Check if this is a virtual base. if (I.isVirtual()) { // Check if we've seen this base before. if (!VBases.insert(BaseDecl).second) continue; - - CharUnits BaseOffset = + + CharUnits BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl); - + LayoutVTT(BaseSubobject(BaseDecl, BaseOffset), /*BaseIsVirtual=*/true); } - + // We only need to layout virtual VTTs for this base if it actually has // virtual bases. if (BaseDecl->getNumVBases()) @@ -181,7 +181,7 @@ void VTTBuilder::LayoutVTT(BaseSubobject Base, bool BaseIsVirtual) { const CXXRecordDecl *RD = Base.getBase(); // Itanium C++ ABI 2.6.2: - // An array of virtual table addresses, called the VTT, is declared for + // An array of virtual table addresses, called the VTT, is declared for // each class type that has indirect or direct virtual base classes. if (RD->getNumVBases() == 0) return; @@ -201,10 +201,10 @@ void VTTBuilder::LayoutVTT(BaseSubobject Base, bool BaseIsVirtual) { // Add the secondary VTTs. LayoutSecondaryVTTs(Base); - + // Add the secondary virtual pointers. LayoutSecondaryVirtualPointers(Base, VTableIndex); - + // If this is the primary VTT, we want to lay out virtual VTTs as well. if (IsPrimaryVTT) { VisitedVirtualBasesSetTy VBases; diff --git a/lib/AST/VTableBuilder.cpp b/lib/AST/VTableBuilder.cpp index 0a3da024f147..dfc5774ab498 100644 --- a/lib/AST/VTableBuilder.cpp +++ b/lib/AST/VTableBuilder.cpp @@ -35,14 +35,14 @@ namespace { struct BaseOffset { /// DerivedClass - The derived class. const CXXRecordDecl *DerivedClass; - + /// VirtualBase - If the path from the derived class to the base class /// involves virtual base classes, this holds the declaration of the last /// virtual base in this path (i.e. closest to the base class). const CXXRecordDecl *VirtualBase; /// NonVirtualOffset - The offset from the derived class to the base class. - /// (Or the offset from the virtual base class to the base class, if the + /// (Or the offset from the virtual base class to the base class, if the /// path from the derived class to the base class involves a virtual base /// class. CharUnits NonVirtualOffset; @@ -51,7 +51,7 @@ struct BaseOffset { NonVirtualOffset(CharUnits::Zero()) { } BaseOffset(const CXXRecordDecl *DerivedClass, const CXXRecordDecl *VirtualBase, CharUnits NonVirtualOffset) - : DerivedClass(DerivedClass), VirtualBase(VirtualBase), + : DerivedClass(DerivedClass), VirtualBase(VirtualBase), NonVirtualOffset(NonVirtualOffset) { } bool isEmpty() const { return NonVirtualOffset.isZero() && !VirtualBase; } @@ -81,19 +81,19 @@ private: /// MostDerivedClass - The most derived class for which the final overriders /// are stored. const CXXRecordDecl *MostDerivedClass; - - /// MostDerivedClassOffset - If we're building final overriders for a + + /// MostDerivedClassOffset - If we're building final overriders for a /// construction vtable, this holds the offset from the layout class to the /// most derived class. const CharUnits MostDerivedClassOffset; - /// LayoutClass - The class we're using for layout information. Will be + /// LayoutClass - The class we're using for layout information. Will be /// different than the most derived class if the final overriders are for a - /// construction vtable. - const CXXRecordDecl *LayoutClass; + /// construction vtable. + const CXXRecordDecl *LayoutClass; ASTContext &Context; - + /// MostDerivedClassLayout - the AST record layout of the most derived class. const ASTRecordLayout &MostDerivedClassLayout; @@ -103,19 +103,19 @@ private: typedef llvm::DenseMap<MethodBaseOffsetPairTy, OverriderInfo> OverridersMapTy; - - /// OverridersMap - The final overriders for all virtual member functions of + + /// OverridersMap - The final overriders for all virtual member functions of /// all the base subobjects of the most derived class. OverridersMapTy OverridersMap; - + /// SubobjectsToOffsetsMapTy - A mapping from a base subobject (represented /// as a record decl and a subobject number) and its offsets in the most /// derived class as well as the layout class. - typedef llvm::DenseMap<std::pair<const CXXRecordDecl *, unsigned>, + typedef llvm::DenseMap<std::pair<const CXXRecordDecl *, unsigned>, CharUnits> SubobjectOffsetMapTy; typedef llvm::DenseMap<const CXXRecordDecl *, unsigned> SubobjectCountMapTy; - + /// ComputeBaseOffsets - Compute the offsets for all base subobjects of the /// given base. void ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual, @@ -125,40 +125,40 @@ private: SubobjectCountMapTy &SubobjectCounts); typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy; - + /// dump - dump the final overriders for a base subobject, and all its direct /// and indirect base subobjects. void dump(raw_ostream &Out, BaseSubobject Base, VisitedVirtualBasesSetTy& VisitedVirtualBases); - + public: FinalOverriders(const CXXRecordDecl *MostDerivedClass, CharUnits MostDerivedClassOffset, const CXXRecordDecl *LayoutClass); /// getOverrider - Get the final overrider for the given method declaration in - /// the subobject with the given base offset. - OverriderInfo getOverrider(const CXXMethodDecl *MD, + /// the subobject with the given base offset. + OverriderInfo getOverrider(const CXXMethodDecl *MD, CharUnits BaseOffset) const { - assert(OverridersMap.count(std::make_pair(MD, BaseOffset)) && + assert(OverridersMap.count(std::make_pair(MD, BaseOffset)) && "Did not find overrider!"); - + return OverridersMap.lookup(std::make_pair(MD, BaseOffset)); } - + /// dump - dump the final overriders. void dump() { VisitedVirtualBasesSetTy VisitedVirtualBases; - dump(llvm::errs(), BaseSubobject(MostDerivedClass, CharUnits::Zero()), + dump(llvm::errs(), BaseSubobject(MostDerivedClass, CharUnits::Zero()), VisitedVirtualBases); } - + }; FinalOverriders::FinalOverriders(const CXXRecordDecl *MostDerivedClass, CharUnits MostDerivedClassOffset, const CXXRecordDecl *LayoutClass) - : MostDerivedClass(MostDerivedClass), + : MostDerivedClass(MostDerivedClass), MostDerivedClassOffset(MostDerivedClassOffset), LayoutClass(LayoutClass), Context(MostDerivedClass->getASTContext()), MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)) { @@ -167,10 +167,10 @@ FinalOverriders::FinalOverriders(const CXXRecordDecl *MostDerivedClass, SubobjectOffsetMapTy SubobjectOffsets; SubobjectOffsetMapTy SubobjectLayoutClassOffsets; SubobjectCountMapTy SubobjectCounts; - ComputeBaseOffsets(BaseSubobject(MostDerivedClass, CharUnits::Zero()), + ComputeBaseOffsets(BaseSubobject(MostDerivedClass, CharUnits::Zero()), /*IsVirtual=*/false, - MostDerivedClassOffset, - SubobjectOffsets, SubobjectLayoutClassOffsets, + MostDerivedClassOffset, + SubobjectOffsets, SubobjectLayoutClassOffsets, SubobjectCounts); // Get the final overriders. @@ -183,10 +183,10 @@ FinalOverriders::FinalOverriders(const CXXRecordDecl *MostDerivedClass, for (const auto &M : Methods) { unsigned SubobjectNumber = M.first; - assert(SubobjectOffsets.count(std::make_pair(MD->getParent(), + assert(SubobjectOffsets.count(std::make_pair(MD->getParent(), SubobjectNumber)) && "Did not find subobject offset!"); - + CharUnits BaseOffset = SubobjectOffsets[std::make_pair(MD->getParent(), SubobjectNumber)]; @@ -198,12 +198,12 @@ FinalOverriders::FinalOverriders(const CXXRecordDecl *MostDerivedClass, std::make_pair(OverriderRD, Method.Subobject)) && "Did not find subobject offset!"); CharUnits OverriderOffset = - SubobjectLayoutClassOffsets[std::make_pair(OverriderRD, + SubobjectLayoutClassOffsets[std::make_pair(OverriderRD, Method.Subobject)]; OverriderInfo& Overrider = OverridersMap[std::make_pair(MD, BaseOffset)]; assert(!Overrider.Method && "Overrider should not exist yet!"); - + Overrider.Offset = OverriderOffset; Overrider.Method = Method.Method; Overrider.VirtualBase = Method.InVirtualSubobject; @@ -235,11 +235,11 @@ static BaseOffset ComputeBaseOffset(const ASTContext &Context, break; } } - + // Now compute the non-virtual offset. for (unsigned I = NonVirtualStart, E = Path.size(); I != E; ++I) { const CXXBasePathElement &Element = Path[I]; - + // Check the base class offset. const ASTRecordLayout &Layout = Context.getASTRecordLayout(Element.Class); @@ -247,12 +247,12 @@ static BaseOffset ComputeBaseOffset(const ASTContext &Context, NonVirtualOffset += Layout.getBaseClassOffset(Base); } - + // FIXME: This should probably use CharUnits or something. Maybe we should - // even change the base offsets in ASTRecordLayout to be specified in + // even change the base offsets in ASTRecordLayout to be specified in // CharUnits. return BaseOffset(DerivedRD, VirtualBase, NonVirtualOffset); - + } static BaseOffset ComputeBaseOffset(const ASTContext &Context, @@ -268,67 +268,67 @@ static BaseOffset ComputeBaseOffset(const ASTContext &Context, } static BaseOffset -ComputeReturnAdjustmentBaseOffset(ASTContext &Context, +ComputeReturnAdjustmentBaseOffset(ASTContext &Context, const CXXMethodDecl *DerivedMD, const CXXMethodDecl *BaseMD) { const FunctionType *BaseFT = BaseMD->getType()->getAs<FunctionType>(); const FunctionType *DerivedFT = DerivedMD->getType()->getAs<FunctionType>(); - + // Canonicalize the return types. CanQualType CanDerivedReturnType = Context.getCanonicalType(DerivedFT->getReturnType()); CanQualType CanBaseReturnType = Context.getCanonicalType(BaseFT->getReturnType()); - assert(CanDerivedReturnType->getTypeClass() == - CanBaseReturnType->getTypeClass() && + assert(CanDerivedReturnType->getTypeClass() == + CanBaseReturnType->getTypeClass() && "Types must have same type class!"); - + if (CanDerivedReturnType == CanBaseReturnType) { // No adjustment needed. return BaseOffset(); } - + if (isa<ReferenceType>(CanDerivedReturnType)) { - CanDerivedReturnType = + CanDerivedReturnType = CanDerivedReturnType->getAs<ReferenceType>()->getPointeeType(); - CanBaseReturnType = + CanBaseReturnType = CanBaseReturnType->getAs<ReferenceType>()->getPointeeType(); } else if (isa<PointerType>(CanDerivedReturnType)) { - CanDerivedReturnType = + CanDerivedReturnType = CanDerivedReturnType->getAs<PointerType>()->getPointeeType(); - CanBaseReturnType = + CanBaseReturnType = CanBaseReturnType->getAs<PointerType>()->getPointeeType(); } else { llvm_unreachable("Unexpected return type!"); } - + // We need to compare unqualified types here; consider // const T *Base::foo(); // T *Derived::foo(); - if (CanDerivedReturnType.getUnqualifiedType() == + if (CanDerivedReturnType.getUnqualifiedType() == CanBaseReturnType.getUnqualifiedType()) { // No adjustment needed. return BaseOffset(); } - - const CXXRecordDecl *DerivedRD = + + const CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(cast<RecordType>(CanDerivedReturnType)->getDecl()); - - const CXXRecordDecl *BaseRD = + + const CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(cast<RecordType>(CanBaseReturnType)->getDecl()); return ComputeBaseOffset(Context, BaseRD, DerivedRD); } -void +void FinalOverriders::ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual, CharUnits OffsetInLayoutClass, SubobjectOffsetMapTy &SubobjectOffsets, SubobjectOffsetMapTy &SubobjectLayoutClassOffsets, SubobjectCountMapTy &SubobjectCounts) { const CXXRecordDecl *RD = Base.getBase(); - + unsigned SubobjectNumber = 0; if (!IsVirtual) SubobjectNumber = ++SubobjectCounts[RD]; @@ -336,13 +336,13 @@ FinalOverriders::ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual, // Set up the subobject to offset mapping. assert(!SubobjectOffsets.count(std::make_pair(RD, SubobjectNumber)) && "Subobject offset already exists!"); - assert(!SubobjectLayoutClassOffsets.count(std::make_pair(RD, SubobjectNumber)) + assert(!SubobjectLayoutClassOffsets.count(std::make_pair(RD, SubobjectNumber)) && "Subobject offset already exists!"); SubobjectOffsets[std::make_pair(RD, SubobjectNumber)] = Base.getBaseOffset(); SubobjectLayoutClassOffsets[std::make_pair(RD, SubobjectNumber)] = OffsetInLayoutClass; - + // Traverse our bases. for (const auto &B : RD->bases()) { const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl(); @@ -358,19 +358,19 @@ FinalOverriders::ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual, Context.getASTRecordLayout(LayoutClass); BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl); - BaseOffsetInLayoutClass = + BaseOffsetInLayoutClass = LayoutClassLayout.getVBaseClassOffset(BaseDecl); } else { const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); CharUnits Offset = Layout.getBaseClassOffset(BaseDecl); - + BaseOffset = Base.getBaseOffset() + Offset; BaseOffsetInLayoutClass = OffsetInLayoutClass + Offset; } - ComputeBaseOffsets(BaseSubobject(BaseDecl, BaseOffset), - B.isVirtual(), BaseOffsetInLayoutClass, - SubobjectOffsets, SubobjectLayoutClassOffsets, + ComputeBaseOffsets(BaseSubobject(BaseDecl, BaseOffset), + B.isVirtual(), BaseOffsetInLayoutClass, + SubobjectOffsets, SubobjectLayoutClassOffsets, SubobjectCounts); } } @@ -382,7 +382,7 @@ void FinalOverriders::dump(raw_ostream &Out, BaseSubobject Base, for (const auto &B : RD->bases()) { const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl(); - + // Ignore bases that don't have any virtual member functions. if (!BaseDecl->isPolymorphic()) continue; @@ -393,7 +393,7 @@ void FinalOverriders::dump(raw_ostream &Out, BaseSubobject Base, // We've visited this base before. continue; } - + BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl); } else { BaseOffset = Layout.getBaseClassOffset(BaseDecl) + Base.getBaseOffset(); @@ -431,19 +431,19 @@ void FinalOverriders::dump(raw_ostream &Out, BaseSubobject Base, Offset.VirtualBase->printQualifiedName(Out); Out << " vbase, "; } - + Out << Offset.NonVirtualOffset.getQuantity() << " nv]"; } - + Out << "\n"; - } + } } /// VCallOffsetMap - Keeps track of vcall offsets when building a vtable. struct VCallOffsetMap { - + typedef std::pair<const CXXMethodDecl *, CharUnits> MethodAndOffsetPairTy; - + /// Offsets - Keeps track of methods and their offsets. // FIXME: This should be a real map and not a vector. SmallVector<MethodAndOffsetPairTy, 16> Offsets; @@ -458,11 +458,11 @@ public: /// add was successful, or false if there was already a member function with /// the same signature in the map. bool AddVCallOffset(const CXXMethodDecl *MD, CharUnits OffsetOffset); - + /// getVCallOffsetOffset - Returns the vcall offset offset (relative to the /// vtable address point) for the given virtual member function. CharUnits getVCallOffsetOffset(const CXXMethodDecl *MD); - + // empty - Return whether the offset map is empty or not. bool empty() const { return Offsets.empty(); } }; @@ -489,13 +489,13 @@ bool VCallOffsetMap::MethodsCanShareVCallOffset(const CXXMethodDecl *LHS, const CXXMethodDecl *RHS) { assert(LHS->isVirtual() && "LHS must be virtual!"); assert(RHS->isVirtual() && "LHS must be virtual!"); - + // A destructor can share a vcall offset with another destructor. if (isa<CXXDestructorDecl>(LHS)) return isa<CXXDestructorDecl>(RHS); // FIXME: We need to check more things here. - + // The methods must have the same name. DeclarationName LHSName = LHS->getDeclName(); DeclarationName RHSName = RHS->getDeclName(); @@ -506,14 +506,14 @@ bool VCallOffsetMap::MethodsCanShareVCallOffset(const CXXMethodDecl *LHS, return HasSameVirtualSignature(LHS, RHS); } -bool VCallOffsetMap::AddVCallOffset(const CXXMethodDecl *MD, +bool VCallOffsetMap::AddVCallOffset(const CXXMethodDecl *MD, CharUnits OffsetOffset) { // Check if we can reuse an offset. for (const auto &OffsetPair : Offsets) { if (MethodsCanShareVCallOffset(OffsetPair.first, MD)) return false; } - + // Add the offset. Offsets.push_back(MethodAndOffsetPairTy(MD, OffsetOffset)); return true; @@ -525,36 +525,36 @@ CharUnits VCallOffsetMap::getVCallOffsetOffset(const CXXMethodDecl *MD) { if (MethodsCanShareVCallOffset(OffsetPair.first, MD)) return OffsetPair.second; } - + llvm_unreachable("Should always find a vcall offset offset!"); } /// VCallAndVBaseOffsetBuilder - Class for building vcall and vbase offsets. class VCallAndVBaseOffsetBuilder { public: - typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> + typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> VBaseOffsetOffsetsMapTy; private: /// MostDerivedClass - The most derived class for which we're building vcall /// and vbase offsets. const CXXRecordDecl *MostDerivedClass; - - /// LayoutClass - The class we're using for layout information. Will be + + /// LayoutClass - The class we're using for layout information. Will be /// different than the most derived class if we're building a construction /// vtable. const CXXRecordDecl *LayoutClass; - + /// Context - The ASTContext which we will use for layout information. ASTContext &Context; /// Components - vcall and vbase offset components typedef SmallVector<VTableComponent, 64> VTableComponentVectorTy; VTableComponentVectorTy Components; - + /// VisitedVirtualBases - Visited virtual bases. llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases; - + /// VCallOffsets - Keeps track of vcall offsets. VCallOffsetMap VCallOffsets; @@ -562,7 +562,7 @@ private: /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets, /// relative to the address point. VBaseOffsetOffsetsMapTy VBaseOffsetOffsets; - + /// FinalOverriders - The final overriders of the most derived class. /// (Can be null when we're not building a vtable of the most derived class). const FinalOverriders *Overriders; @@ -571,48 +571,48 @@ private: /// given base subobject. void AddVCallAndVBaseOffsets(BaseSubobject Base, bool BaseIsVirtual, CharUnits RealBaseOffset); - + /// AddVCallOffsets - Add vcall offsets for the given base subobject. void AddVCallOffsets(BaseSubobject Base, CharUnits VBaseOffset); - + /// AddVBaseOffsets - Add vbase offsets for the given class. - void AddVBaseOffsets(const CXXRecordDecl *Base, + void AddVBaseOffsets(const CXXRecordDecl *Base, CharUnits OffsetInLayoutClass); - + /// getCurrentOffsetOffset - Get the current vcall or vbase offset offset in /// chars, relative to the vtable address point. CharUnits getCurrentOffsetOffset() const; - + public: VCallAndVBaseOffsetBuilder(const CXXRecordDecl *MostDerivedClass, const CXXRecordDecl *LayoutClass, const FinalOverriders *Overriders, BaseSubobject Base, bool BaseIsVirtual, CharUnits OffsetInLayoutClass) - : MostDerivedClass(MostDerivedClass), LayoutClass(LayoutClass), + : MostDerivedClass(MostDerivedClass), LayoutClass(LayoutClass), Context(MostDerivedClass->getASTContext()), Overriders(Overriders) { - + // Add vcall and vbase offsets. AddVCallAndVBaseOffsets(Base, BaseIsVirtual, OffsetInLayoutClass); } - + /// Methods for iterating over the components. typedef VTableComponentVectorTy::const_reverse_iterator const_iterator; const_iterator components_begin() const { return Components.rbegin(); } const_iterator components_end() const { return Components.rend(); } - + const VCallOffsetMap &getVCallOffsets() const { return VCallOffsets; } const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const { return VBaseOffsetOffsets; } }; - -void + +void VCallAndVBaseOffsetBuilder::AddVCallAndVBaseOffsets(BaseSubobject Base, bool BaseIsVirtual, CharUnits RealBaseOffset) { const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base.getBase()); - + // Itanium C++ ABI 2.5.2: // ..in classes sharing a virtual table with a primary base class, the vcall // and vbase offsets added by the derived class all come before the vcall @@ -626,16 +626,16 @@ VCallAndVBaseOffsetBuilder::AddVCallAndVBaseOffsets(BaseSubobject Base, bool PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual(); CharUnits PrimaryBaseOffset; - + // Get the base offset of the primary base. if (PrimaryBaseIsVirtual) { assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() && "Primary vbase should have a zero offset!"); - + const ASTRecordLayout &MostDerivedClassLayout = Context.getASTRecordLayout(MostDerivedClass); - - PrimaryBaseOffset = + + PrimaryBaseOffset = MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase); } else { assert(Layout.getBaseClassOffset(PrimaryBase).isZero() && @@ -657,19 +657,19 @@ VCallAndVBaseOffsetBuilder::AddVCallAndVBaseOffsets(BaseSubobject Base, } CharUnits VCallAndVBaseOffsetBuilder::getCurrentOffsetOffset() const { - // OffsetIndex is the index of this vcall or vbase offset, relative to the + // OffsetIndex is the index of this vcall or vbase offset, relative to the // vtable address point. (We subtract 3 to account for the information just // above the address point, the RTTI info, the offset to top, and the // vcall offset itself). int64_t OffsetIndex = -(int64_t)(3 + Components.size()); - - CharUnits PointerWidth = + + CharUnits PointerWidth = Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0)); CharUnits OffsetOffset = PointerWidth * OffsetIndex; return OffsetOffset; } -void VCallAndVBaseOffsetBuilder::AddVCallOffsets(BaseSubobject Base, +void VCallAndVBaseOffsetBuilder::AddVCallOffsets(BaseSubobject Base, CharUnits VBaseOffset) { const CXXRecordDecl *RD = Base.getBase(); const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); @@ -687,7 +687,7 @@ void VCallAndVBaseOffsetBuilder::AddVCallOffsets(BaseSubobject Base, AddVCallOffsets(BaseSubobject(PrimaryBase, Base.getBaseOffset()), VBaseOffset); } - + // Add the vcall offsets. for (const auto *MD : RD->methods()) { if (!MD->isVirtual()) @@ -695,7 +695,7 @@ void VCallAndVBaseOffsetBuilder::AddVCallOffsets(BaseSubobject Base, MD = MD->getCanonicalDecl(); CharUnits OffsetOffset = getCurrentOffsetOffset(); - + // Don't add a vcall offset if we already have one for this member function // signature. if (!VCallOffsets.AddVCallOffset(MD, OffsetOffset)) @@ -705,20 +705,20 @@ void VCallAndVBaseOffsetBuilder::AddVCallOffsets(BaseSubobject Base, if (Overriders) { // Get the final overrider. - FinalOverriders::OverriderInfo Overrider = + FinalOverriders::OverriderInfo Overrider = Overriders->getOverrider(MD, Base.getBaseOffset()); - - /// The vcall offset is the offset from the virtual base to the object + + /// The vcall offset is the offset from the virtual base to the object /// where the function was overridden. Offset = Overrider.Offset - VBaseOffset; } - + Components.push_back( VTableComponent::MakeVCallOffset(Offset)); } // And iterate over all non-virtual bases (ignoring the primary base). - for (const auto &B : RD->bases()) { + for (const auto &B : RD->bases()) { if (B.isVirtual()) continue; @@ -727,18 +727,18 @@ void VCallAndVBaseOffsetBuilder::AddVCallOffsets(BaseSubobject Base, continue; // Get the base offset of this base. - CharUnits BaseOffset = Base.getBaseOffset() + + CharUnits BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl); - - AddVCallOffsets(BaseSubobject(BaseDecl, BaseOffset), + + AddVCallOffsets(BaseSubobject(BaseDecl, BaseOffset), VBaseOffset); } } -void +void VCallAndVBaseOffsetBuilder::AddVBaseOffsets(const CXXRecordDecl *RD, CharUnits OffsetInLayoutClass) { - const ASTRecordLayout &LayoutClassLayout = + const ASTRecordLayout &LayoutClassLayout = Context.getASTRecordLayout(LayoutClass); // Add vbase offsets. @@ -747,7 +747,7 @@ VCallAndVBaseOffsetBuilder::AddVBaseOffsets(const CXXRecordDecl *RD, // Check if this is a virtual base that we haven't visited before. if (B.isVirtual() && VisitedVirtualBases.insert(BaseDecl).second) { - CharUnits Offset = + CharUnits Offset = LayoutClassLayout.getVBaseClassOffset(BaseDecl) - OffsetInLayoutClass; // Add the vbase offset offset. @@ -770,12 +770,12 @@ VCallAndVBaseOffsetBuilder::AddVBaseOffsets(const CXXRecordDecl *RD, /// ItaniumVTableBuilder - Class for building vtable layout information. class ItaniumVTableBuilder { public: - /// PrimaryBasesSetVectorTy - A set vector of direct and indirect + /// PrimaryBasesSetVectorTy - A set vector of direct and indirect /// primary bases. - typedef llvm::SmallSetVector<const CXXRecordDecl *, 8> + typedef llvm::SmallSetVector<const CXXRecordDecl *, 8> PrimaryBasesSetVectorTy; - - typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> + + typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> VBaseOffsetOffsetsMapTy; typedef VTableLayout::AddressPointsMapTy AddressPointsMapTy; @@ -785,7 +785,7 @@ public: private: /// VTables - Global vtable information. ItaniumVTableContext &VTables; - + /// MostDerivedClass - The most derived class for which we're building this /// vtable. const CXXRecordDecl *MostDerivedClass; @@ -793,19 +793,19 @@ private: /// MostDerivedClassOffset - If we're building a construction vtable, this /// holds the offset from the layout class to the most derived class. const CharUnits MostDerivedClassOffset; - - /// MostDerivedClassIsVirtual - Whether the most derived class is a virtual + + /// MostDerivedClassIsVirtual - Whether the most derived class is a virtual /// base. (This only makes sense when building a construction vtable). bool MostDerivedClassIsVirtual; - - /// LayoutClass - The class we're using for layout information. Will be + + /// LayoutClass - The class we're using for layout information. Will be /// different than the most derived class if we're building a construction /// vtable. const CXXRecordDecl *LayoutClass; - + /// Context - The ASTContext which we will use for layout information. ASTContext &Context; - + /// FinalOverriders - The final overriders of the most derived class. const FinalOverriders Overriders; @@ -828,29 +828,29 @@ private: struct MethodInfo { /// BaseOffset - The base offset of this method. const CharUnits BaseOffset; - + /// BaseOffsetInLayoutClass - The base offset in the layout class of this /// method. const CharUnits BaseOffsetInLayoutClass; - + /// VTableIndex - The index in the vtable that this method has. /// (For destructors, this is the index of the complete destructor). const uint64_t VTableIndex; - - MethodInfo(CharUnits BaseOffset, CharUnits BaseOffsetInLayoutClass, + + MethodInfo(CharUnits BaseOffset, CharUnits BaseOffsetInLayoutClass, uint64_t VTableIndex) - : BaseOffset(BaseOffset), + : BaseOffset(BaseOffset), BaseOffsetInLayoutClass(BaseOffsetInLayoutClass), VTableIndex(VTableIndex) { } - - MethodInfo() - : BaseOffset(CharUnits::Zero()), - BaseOffsetInLayoutClass(CharUnits::Zero()), + + MethodInfo() + : BaseOffset(CharUnits::Zero()), + BaseOffsetInLayoutClass(CharUnits::Zero()), VTableIndex(0) { } }; - + typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy; - + /// MethodInfoMap - The information for all methods in the vtable we're /// currently building. MethodInfoMapTy MethodInfoMap; @@ -860,25 +860,25 @@ private: MethodVTableIndicesTy MethodVTableIndices; typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy; - - /// VTableThunks - The thunks by vtable index in the vtable currently being + + /// VTableThunks - The thunks by vtable index in the vtable currently being /// built. VTableThunksMapTy VTableThunks; typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy; typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy; - + /// Thunks - A map that contains all the thunks needed for all methods in the /// most derived class for which the vtable is currently being built. ThunksMapTy Thunks; - + /// AddThunk - Add a thunk for the given method. void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk); - + /// ComputeThisAdjustments - Compute the 'this' pointer adjustments for the /// part of the vtable we're currently building. void ComputeThisAdjustments(); - + typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy; /// PrimaryVirtualBases - All known virtual bases who are a primary base of @@ -888,7 +888,7 @@ private: /// ComputeReturnAdjustment - Compute the return adjustment given a return /// adjustment base offset. ReturnAdjustment ComputeReturnAdjustment(BaseOffset Offset); - + /// ComputeThisAdjustmentBaseOffset - Compute the base offset for adjusting /// the 'this' pointer from the base subobject to the derived subobject. BaseOffset ComputeThisAdjustmentBaseOffset(BaseSubobject Base, @@ -897,8 +897,8 @@ private: /// ComputeThisAdjustment - Compute the 'this' pointer adjustment for the /// given virtual member function, its offset in the layout class and its /// final overrider. - ThisAdjustment - ComputeThisAdjustment(const CXXMethodDecl *MD, + ThisAdjustment + ComputeThisAdjustment(const CXXMethodDecl *MD, CharUnits BaseOffsetInLayoutClass, FinalOverriders::OverriderInfo Overrider); @@ -907,7 +907,7 @@ private: void AddMethod(const CXXMethodDecl *MD, ReturnAdjustment ReturnAdjustment); /// IsOverriderUsed - Returns whether the overrider will ever be used in this - /// part of the vtable. + /// part of the vtable. /// /// Itanium C++ ABI 2.5.2: /// @@ -921,16 +921,16 @@ private: /// adjustment is required and no thunk is generated. However, inside D /// objects, A is no longer a primary base of C, so if we allowed calls to /// C::f() to use the copy of A's vtable in the C subobject, we would need - /// to adjust this from C* to B::A*, which would require a third-party - /// thunk. Since we require that a call to C::f() first convert to A*, - /// C-in-D's copy of A's vtable is never referenced, so this is not + /// to adjust this from C* to B::A*, which would require a third-party + /// thunk. Since we require that a call to C::f() first convert to A*, + /// C-in-D's copy of A's vtable is never referenced, so this is not /// necessary. bool IsOverriderUsed(const CXXMethodDecl *Overrider, CharUnits BaseOffsetInLayoutClass, const CXXRecordDecl *FirstBaseInPrimaryBaseChain, CharUnits FirstBaseOffsetInLayoutClass) const; - + /// AddMethods - Add the methods of this base subobject and all its /// primary bases to the vtable components vector. void AddMethods(BaseSubobject Base, CharUnits BaseOffsetInLayoutClass, @@ -949,12 +949,12 @@ private: /// or a direct or indirect base of a virtual base. /// /// \param BaseIsVirtualInLayoutClass - Whether the base subobject is virtual - /// in the layout class. + /// in the layout class. void LayoutPrimaryAndSecondaryVTables(BaseSubobject Base, bool BaseIsMorallyVirtual, bool BaseIsVirtualInLayoutClass, CharUnits OffsetInLayoutClass); - + /// LayoutSecondaryVTables - Layout the secondary vtables for the given base /// subobject. /// @@ -965,18 +965,18 @@ private: /// DeterminePrimaryVirtualBases - Determine the primary virtual bases in this /// class hierarchy. - void DeterminePrimaryVirtualBases(const CXXRecordDecl *RD, + void DeterminePrimaryVirtualBases(const CXXRecordDecl *RD, CharUnits OffsetInLayoutClass, VisitedVirtualBasesSetTy &VBases); /// LayoutVTablesForVirtualBases - Layout vtables for all virtual bases of the /// given base (excluding any primary bases). - void LayoutVTablesForVirtualBases(const CXXRecordDecl *RD, + void LayoutVTablesForVirtualBases(const CXXRecordDecl *RD, VisitedVirtualBasesSetTy &VBases); /// isBuildingConstructionVTable - Return whether this vtable builder is /// building a construction vtable. - bool isBuildingConstructorVTable() const { + bool isBuildingConstructorVTable() const { return MostDerivedClass != LayoutClass; } @@ -1055,16 +1055,16 @@ public: void ItaniumVTableBuilder::AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk) { - assert(!isBuildingConstructorVTable() && + assert(!isBuildingConstructorVTable() && "Can't add thunks for construction vtable"); SmallVectorImpl<ThunkInfo> &ThunksVector = Thunks[MD]; // Check if we have this thunk already. - if (std::find(ThunksVector.begin(), ThunksVector.end(), Thunk) != + if (std::find(ThunksVector.begin(), ThunksVector.end(), Thunk) != ThunksVector.end()) return; - + ThunksVector.push_back(Thunk); } @@ -1107,18 +1107,18 @@ void ItaniumVTableBuilder::ComputeThisAdjustments() { // Ignore adjustments for unused function pointers. uint64_t VTableIndex = MethodInfo.VTableIndex; - if (Components[VTableIndex].getKind() == + if (Components[VTableIndex].getKind() == VTableComponent::CK_UnusedFunctionPointer) continue; - + // Get the final overrider for this method. FinalOverriders::OverriderInfo Overrider = Overriders.getOverrider(MD, MethodInfo.BaseOffset); - + // Check if we need an adjustment at all. if (MethodInfo.BaseOffsetInLayoutClass == Overrider.Offset) { // When a return thunk is needed by a derived class that overrides a - // virtual base, gcc uses a virtual 'this' adjustment as well. + // virtual base, gcc uses a virtual 'this' adjustment as well. // While the thunk itself might be needed by vtables in subclasses or // in construction vtables, there doesn't seem to be a reason for using // the thunk in this vtable. Still, we do so to match gcc. @@ -1143,7 +1143,7 @@ void ItaniumVTableBuilder::ComputeThisAdjustments() { /// Clear the method info map. MethodInfoMap.clear(); - + if (isBuildingConstructorVTable()) { // We don't need to store thunk information for construction vtables. return; @@ -1153,7 +1153,7 @@ void ItaniumVTableBuilder::ComputeThisAdjustments() { const VTableComponent &Component = Components[TI.first]; const ThunkInfo &Thunk = TI.second; const CXXMethodDecl *MD; - + switch (Component.getKind()) { default: llvm_unreachable("Unexpected vtable component kind!"); @@ -1176,7 +1176,7 @@ void ItaniumVTableBuilder::ComputeThisAdjustments() { ReturnAdjustment ItaniumVTableBuilder::ComputeReturnAdjustment(BaseOffset Offset) { ReturnAdjustment Adjustment; - + if (!Offset.isEmpty()) { if (Offset.VirtualBase) { // Get the virtual base offset offset. @@ -1193,7 +1193,7 @@ ItaniumVTableBuilder::ComputeReturnAdjustment(BaseOffset Offset) { Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity(); } - + return Adjustment; } @@ -1201,7 +1201,7 @@ BaseOffset ItaniumVTableBuilder::ComputeThisAdjustmentBaseOffset( BaseSubobject Base, BaseSubobject Derived) const { const CXXRecordDecl *BaseRD = Base.getBase(); const CXXRecordDecl *DerivedRD = Derived.getBase(); - + CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, /*DetectVirtual=*/true); @@ -1214,32 +1214,32 @@ BaseOffset ItaniumVTableBuilder::ComputeThisAdjustmentBaseOffset( BaseOffset Offset = ComputeBaseOffset(Context, DerivedRD, Path); CharUnits OffsetToBaseSubobject = Offset.NonVirtualOffset; - + if (Offset.VirtualBase) { // If we have a virtual base class, the non-virtual offset is relative // to the virtual base class offset. const ASTRecordLayout &LayoutClassLayout = Context.getASTRecordLayout(LayoutClass); - - /// Get the virtual base offset, relative to the most derived class + + /// Get the virtual base offset, relative to the most derived class /// layout. - OffsetToBaseSubobject += + OffsetToBaseSubobject += LayoutClassLayout.getVBaseClassOffset(Offset.VirtualBase); } else { - // Otherwise, the non-virtual offset is relative to the derived class + // Otherwise, the non-virtual offset is relative to the derived class // offset. OffsetToBaseSubobject += Derived.getBaseOffset(); } - + // Check if this path gives us the right base subobject. if (OffsetToBaseSubobject == Base.getBaseOffset()) { // Since we're going from the base class _to_ the derived class, we'll // invert the non-virtual offset here. Offset.NonVirtualOffset = -Offset.NonVirtualOffset; return Offset; - } + } } - + return BaseOffset(); } @@ -1249,13 +1249,13 @@ ThisAdjustment ItaniumVTableBuilder::ComputeThisAdjustment( // Ignore adjustments for pure virtual member functions. if (Overrider.Method->isPure()) return ThisAdjustment(); - - BaseSubobject OverriddenBaseSubobject(MD->getParent(), + + BaseSubobject OverriddenBaseSubobject(MD->getParent(), BaseOffsetInLayoutClass); - + BaseSubobject OverriderBaseSubobject(Overrider.Method->getParent(), Overrider.Offset); - + // Compute the adjustment offset. BaseOffset Offset = ComputeThisAdjustmentBaseOffset(OverriddenBaseSubobject, OverriderBaseSubobject); @@ -1263,7 +1263,7 @@ ThisAdjustment ItaniumVTableBuilder::ComputeThisAdjustment( return ThisAdjustment(); ThisAdjustment Adjustment; - + if (Offset.VirtualBase) { // Get the vcall offset map for this virtual base. VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Offset.VirtualBase]; @@ -1278,24 +1278,24 @@ ThisAdjustment ItaniumVTableBuilder::ComputeThisAdjustment( /*BaseIsVirtual=*/true, /*OffsetInLayoutClass=*/ CharUnits::Zero()); - + VCallOffsets = Builder.getVCallOffsets(); } - + Adjustment.Virtual.Itanium.VCallOffsetOffset = VCallOffsets.getVCallOffsetOffset(MD).getQuantity(); } // Set the non-virtual part of the adjustment. Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity(); - + return Adjustment; } void ItaniumVTableBuilder::AddMethod(const CXXMethodDecl *MD, ReturnAdjustment ReturnAdjustment) { if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) { - assert(ReturnAdjustment.isEmpty() && + assert(ReturnAdjustment.isEmpty() && "Destructor can't have return adjustment!"); // Add both the complete destructor and the deleting destructor. @@ -1312,7 +1312,7 @@ void ItaniumVTableBuilder::AddMethod(const CXXMethodDecl *MD, } /// OverridesIndirectMethodInBase - Return whether the given member function -/// overrides any methods in the set of given bases. +/// overrides any methods in the set of given bases. /// Unlike OverridesMethodInBase, this checks "overriders of overriders". /// For example, if we have: /// @@ -1320,7 +1320,7 @@ void ItaniumVTableBuilder::AddMethod(const CXXMethodDecl *MD, /// struct B : A { virtual void f(); } /// struct C : B { virtual void f(); } /// -/// OverridesIndirectMethodInBase will return true if given C::f as the method +/// OverridesIndirectMethodInBase will return true if given C::f as the method /// and { A } as the set of bases. static bool OverridesIndirectMethodInBases( const CXXMethodDecl *MD, @@ -1333,7 +1333,7 @@ static bool OverridesIndirectMethodInBases( if (OverridesIndirectMethodInBases(OverriddenMD, Bases)) return true; } - + return false; } @@ -1347,9 +1347,9 @@ bool ItaniumVTableBuilder::IsOverriderUsed( return true; // We know now that Base (or a direct or indirect base of it) is a primary - // base in part of the class hierarchy, but not a primary base in the most + // base in part of the class hierarchy, but not a primary base in the most // derived class. - + // If the overrider is the first base in the primary base chain, we know // that the overrider will be used. if (Overrider->getParent() == FirstBaseInPrimaryBaseChain) @@ -1365,10 +1365,10 @@ bool ItaniumVTableBuilder::IsOverriderUsed( while (true) { const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase(); - + if (!PrimaryBase) break; - + if (Layout.isPrimaryBaseVirtual()) { assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() && "Primary base should always be at offset 0!"); @@ -1387,13 +1387,13 @@ bool ItaniumVTableBuilder::IsOverriderUsed( assert(Layout.getBaseClassOffset(PrimaryBase).isZero() && "Primary base should always be at offset 0!"); } - + if (!PrimaryBases.insert(PrimaryBase)) llvm_unreachable("Found a duplicate primary base!"); RD = PrimaryBase; } - + // If the final overrider is an override of one of the primary bases, // then we know that it will be used. return OverridesIndirectMethodInBases(Overrider, PrimaryBases); @@ -1446,13 +1446,13 @@ void ItaniumVTableBuilder::AddMethods( if (Layout.isPrimaryBaseVirtual()) { assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() && "Primary vbase should have a zero offset!"); - + const ASTRecordLayout &MostDerivedClassLayout = Context.getASTRecordLayout(MostDerivedClass); - - PrimaryBaseOffset = + + PrimaryBaseOffset = MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase); - + const ASTRecordLayout &LayoutClassLayout = Context.getASTRecordLayout(LayoutClass); @@ -1467,9 +1467,9 @@ void ItaniumVTableBuilder::AddMethods( } AddMethods(BaseSubobject(PrimaryBase, PrimaryBaseOffset), - PrimaryBaseOffsetInLayoutClass, FirstBaseInPrimaryBaseChain, + PrimaryBaseOffsetInLayoutClass, FirstBaseInPrimaryBaseChain, FirstBaseOffsetInLayoutClass, PrimaryBases); - + if (!PrimaryBases.insert(PrimaryBase)) llvm_unreachable("Found a duplicate primary base!"); } @@ -1486,31 +1486,31 @@ void ItaniumVTableBuilder::AddMethods( MD = MD->getCanonicalDecl(); // Get the final overrider. - FinalOverriders::OverriderInfo Overrider = + FinalOverriders::OverriderInfo Overrider = Overriders.getOverrider(MD, Base.getBaseOffset()); // Check if this virtual member function overrides a method in a primary // base. If this is the case, and the return type doesn't require adjustment // then we can just use the member function from the primary base. - if (const CXXMethodDecl *OverriddenMD = + if (const CXXMethodDecl *OverriddenMD = FindNearestOverriddenMethod(MD, PrimaryBases)) { - if (ComputeReturnAdjustmentBaseOffset(Context, MD, + if (ComputeReturnAdjustmentBaseOffset(Context, MD, OverriddenMD).isEmpty()) { // Replace the method info of the overridden method with our own // method. - assert(MethodInfoMap.count(OverriddenMD) && + assert(MethodInfoMap.count(OverriddenMD) && "Did not find the overridden method!"); MethodInfo &OverriddenMethodInfo = MethodInfoMap[OverriddenMD]; - + MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass, OverriddenMethodInfo.VTableIndex); assert(!MethodInfoMap.count(MD) && "Should not have method info for this method yet!"); - + MethodInfoMap.insert(std::make_pair(MD, MethodInfo)); MethodInfoMap.erase(OverriddenMD); - + // If the overridden method exists in a virtual base class or a direct // or indirect base class of a virtual base class, we need to emit a // thunk if we ever have a class hierarchy where the base class is not @@ -1529,11 +1529,11 @@ void ItaniumVTableBuilder::AddMethods( // the final overrider. BaseOffset ReturnAdjustmentOffset = ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD); - ReturnAdjustment ReturnAdjustment = + ReturnAdjustment ReturnAdjustment = ComputeReturnAdjustment(ReturnAdjustmentOffset); // This is a virtual thunk for the most derived class, add it. - AddThunk(Overrider.Method, + AddThunk(Overrider.Method, ThunkInfo(ThisAdjustment, ReturnAdjustment)); } } @@ -1577,7 +1577,7 @@ void ItaniumVTableBuilder::AddMethods( // Check if this overrider is going to be used. const CXXMethodDecl *OverriderMD = Overrider.Method; if (!IsOverriderUsed(OverriderMD, BaseOffsetInLayoutClass, - FirstBaseInPrimaryBaseChain, + FirstBaseInPrimaryBaseChain, FirstBaseOffsetInLayoutClass)) { Components.push_back(VTableComponent::MakeUnusedFunction(OverriderMD)); continue; @@ -1587,13 +1587,13 @@ void ItaniumVTableBuilder::AddMethods( // We don't want to do this for pure virtual member functions. BaseOffset ReturnAdjustmentOffset; if (!OverriderMD->isPure()) { - ReturnAdjustmentOffset = + ReturnAdjustmentOffset = ComputeReturnAdjustmentBaseOffset(Context, OverriderMD, MD); } - ReturnAdjustment ReturnAdjustment = + ReturnAdjustment ReturnAdjustment = ComputeReturnAdjustment(ReturnAdjustmentOffset); - + AddMethod(Overrider.Method, ReturnAdjustment); } } @@ -1604,14 +1604,14 @@ void ItaniumVTableBuilder::LayoutVTable() { /*BaseIsMorallyVirtual=*/false, MostDerivedClassIsVirtual, MostDerivedClassOffset); - + VisitedVirtualBasesSetTy VBases; - + // Determine the primary virtual bases. - DeterminePrimaryVirtualBases(MostDerivedClass, MostDerivedClassOffset, + DeterminePrimaryVirtualBases(MostDerivedClass, MostDerivedClassOffset, VBases); VBases.clear(); - + LayoutVTablesForVirtualBases(MostDerivedClass, VBases); // -fapple-kext adds an extra entry at end of vtbl. @@ -1630,14 +1630,14 @@ void ItaniumVTableBuilder::LayoutPrimaryAndSecondaryVTables( // Add vcall and vbase offsets for this vtable. VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, LayoutClass, &Overriders, - Base, BaseIsVirtualInLayoutClass, + Base, BaseIsVirtualInLayoutClass, OffsetInLayoutClass); Components.append(Builder.components_begin(), Builder.components_end()); - + // Check if we need to add these vcall offsets. if (BaseIsVirtualInLayoutClass && !Builder.getVCallOffsets().empty()) { VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Base.getBase()]; - + if (VCallOffsets.empty()) VCallOffsets = Builder.getVCallOffsets(); } @@ -1659,7 +1659,7 @@ void ItaniumVTableBuilder::LayoutPrimaryAndSecondaryVTables( // Now go through all virtual member functions and add them. PrimaryBasesSetVectorTy PrimaryBases; AddMethods(Base, OffsetInLayoutClass, - Base.getBase(), OffsetInLayoutClass, + Base.getBase(), OffsetInLayoutClass, PrimaryBases); const CXXRecordDecl *RD = Base.getBase(); @@ -1692,10 +1692,10 @@ void ItaniumVTableBuilder::LayoutPrimaryAndSecondaryVTables( const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase(); - + if (!PrimaryBase) break; - + if (Layout.isPrimaryBaseVirtual()) { // Check if this virtual primary base is a primary base in the layout // class. If it's not, we don't want to add it. @@ -1721,19 +1721,19 @@ ItaniumVTableBuilder::LayoutSecondaryVTables(BaseSubobject Base, bool BaseIsMorallyVirtual, CharUnits OffsetInLayoutClass) { // Itanium C++ ABI 2.5.2: - // Following the primary virtual table of a derived class are secondary + // Following the primary virtual table of a derived class are secondary // virtual tables for each of its proper base classes, except any primary // base(s) with which it shares its primary virtual table. const CXXRecordDecl *RD = Base.getBase(); const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase(); - + for (const auto &B : RD->bases()) { // Ignore virtual bases, we'll emit them later. if (B.isVirtual()) continue; - + const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl(); // Ignore bases that don't have a vtable. @@ -1753,11 +1753,11 @@ ItaniumVTableBuilder::LayoutSecondaryVTables(BaseSubobject Base, // Get the base offset of this base. CharUnits RelativeBaseOffset = Layout.getBaseClassOffset(BaseDecl); CharUnits BaseOffset = Base.getBaseOffset() + RelativeBaseOffset; - - CharUnits BaseOffsetInLayoutClass = + + CharUnits BaseOffsetInLayoutClass = OffsetInLayoutClass + RelativeBaseOffset; - - // Don't emit a secondary vtable for a primary base. We might however want + + // Don't emit a secondary vtable for a primary base. We might however want // to emit secondary vtables for other bases of this base. if (BaseDecl == PrimaryBase) { LayoutSecondaryVTables(BaseSubobject(BaseDecl, BaseOffset), @@ -1778,7 +1778,7 @@ void ItaniumVTableBuilder::DeterminePrimaryVirtualBases( const CXXRecordDecl *RD, CharUnits OffsetInLayoutClass, VisitedVirtualBasesSetTy &VBases) { const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); - + // Check if this base has a primary base. if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) { @@ -1794,13 +1794,13 @@ void ItaniumVTableBuilder::DeterminePrimaryVirtualBases( CharUnits PrimaryBaseOffsetInLayoutClass = LayoutClassLayout.getVBaseClassOffset(PrimaryBase); - - // We know that the base is not a primary base in the layout class if + + // We know that the base is not a primary base in the layout class if // the base offsets are different. if (PrimaryBaseOffsetInLayoutClass != OffsetInLayoutClass) IsPrimaryVirtualBase = false; } - + if (IsPrimaryVirtualBase) PrimaryVirtualBases.insert(PrimaryBase); } @@ -1811,18 +1811,18 @@ void ItaniumVTableBuilder::DeterminePrimaryVirtualBases( const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl(); CharUnits BaseOffsetInLayoutClass; - + if (B.isVirtual()) { if (!VBases.insert(BaseDecl).second) continue; - + const ASTRecordLayout &LayoutClassLayout = Context.getASTRecordLayout(LayoutClass); - BaseOffsetInLayoutClass = + BaseOffsetInLayoutClass = LayoutClassLayout.getVBaseClassOffset(BaseDecl); } else { - BaseOffsetInLayoutClass = + BaseOffsetInLayoutClass = OffsetInLayoutClass + Layout.getBaseClassOffset(BaseDecl); } @@ -1846,12 +1846,12 @@ void ItaniumVTableBuilder::LayoutVTablesForVirtualBases( VBases.insert(BaseDecl).second) { const ASTRecordLayout &MostDerivedClassLayout = Context.getASTRecordLayout(MostDerivedClass); - CharUnits BaseOffset = + CharUnits BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl); - + const ASTRecordLayout &LayoutClassLayout = Context.getASTRecordLayout(LayoutClass); - CharUnits BaseOffsetInLayoutClass = + CharUnits BaseOffsetInLayoutClass = LayoutClassLayout.getVBaseClassOffset(BaseDecl); LayoutPrimaryAndSecondaryVTables( @@ -1860,7 +1860,7 @@ void ItaniumVTableBuilder::LayoutVTablesForVirtualBases( /*BaseIsVirtualInLayoutClass=*/true, BaseOffsetInLayoutClass); } - + // We only need to check the base for virtual base vtables if it actually // has virtual bases. if (BaseDecl->getNumVBases()) @@ -1897,7 +1897,7 @@ void ItaniumVTableBuilder::dumpLayout(raw_ostream &Out) { AddressPointsByIndex.insert(std::make_pair(Index, Base)); } - + for (unsigned I = 0, E = Components.size(); I != E; ++I) { uint64_t Index = I; @@ -1910,7 +1910,7 @@ void ItaniumVTableBuilder::dumpLayout(raw_ostream &Out) { case VTableComponent::CK_VCallOffset: Out << "vcall_offset (" - << Component.getVCallOffset().getQuantity() + << Component.getVCallOffset().getQuantity() << ")"; break; @@ -1925,17 +1925,17 @@ void ItaniumVTableBuilder::dumpLayout(raw_ostream &Out) { << Component.getOffsetToTop().getQuantity() << ")"; break; - + case VTableComponent::CK_RTTI: Component.getRTTIDecl()->printQualifiedName(Out); Out << " RTTI"; break; - + case VTableComponent::CK_FunctionPointer: { const CXXMethodDecl *MD = Component.getFunctionDecl(); - std::string Str = - PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual, + std::string Str = + PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual, MD); Out << Str; if (MD->isPure()) @@ -1950,7 +1950,7 @@ void ItaniumVTableBuilder::dumpLayout(raw_ostream &Out) { if (!Thunk.Return.isEmpty()) { Out << "\n [return adjustment: "; Out << Thunk.Return.NonVirtual << " non-virtual"; - + if (Thunk.Return.Virtual.Itanium.VBaseOffsetOffset) { Out << ", " << Thunk.Return.Virtual.Itanium.VBaseOffsetOffset; Out << " vbase offset offset"; @@ -1963,26 +1963,26 @@ void ItaniumVTableBuilder::dumpLayout(raw_ostream &Out) { if (!Thunk.This.isEmpty()) { Out << "\n [this adjustment: "; Out << Thunk.This.NonVirtual << " non-virtual"; - + if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) { Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset; Out << " vcall offset offset"; } Out << ']'; - } + } } break; } - case VTableComponent::CK_CompleteDtorPointer: + case VTableComponent::CK_CompleteDtorPointer: case VTableComponent::CK_DeletingDtorPointer: { - bool IsComplete = + bool IsComplete = Component.getKind() == VTableComponent::CK_CompleteDtorPointer; - + const CXXDestructorDecl *DD = Component.getDestructorDecl(); - + DD->printQualifiedName(Out); if (IsComplete) Out << "() [complete]"; @@ -1998,15 +1998,15 @@ void ItaniumVTableBuilder::dumpLayout(raw_ostream &Out) { if (!Thunk.This.isEmpty()) { Out << "\n [this adjustment: "; Out << Thunk.This.NonVirtual << " non-virtual"; - + if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) { Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset; Out << " vcall offset offset"; } - + Out << ']'; - } - } + } + } break; } @@ -2014,8 +2014,8 @@ void ItaniumVTableBuilder::dumpLayout(raw_ostream &Out) { case VTableComponent::CK_UnusedFunctionPointer: { const CXXMethodDecl *MD = Component.getUnusedFunctionDecl(); - std::string Str = - PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual, + std::string Str = + PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual, MD); Out << "[unused] " << Str; if (MD->isPure()) @@ -2025,14 +2025,14 @@ void ItaniumVTableBuilder::dumpLayout(raw_ostream &Out) { } Out << '\n'; - + // Dump the next address point. uint64_t NextIndex = Index + 1; if (AddressPointsByIndex.count(NextIndex)) { if (AddressPointsByIndex.count(NextIndex) == 1) { - const BaseSubobject &Base = + const BaseSubobject &Base = AddressPointsByIndex.find(NextIndex)->second; - + Out << " -- ("; Base.getBase()->printQualifiedName(Out); Out << ", " << Base.getBaseOffset().getQuantity(); @@ -2040,7 +2040,7 @@ void ItaniumVTableBuilder::dumpLayout(raw_ostream &Out) { } else { CharUnits BaseOffset = AddressPointsByIndex.lower_bound(NextIndex)->second.getBaseOffset(); - + // We store the class names in a set to get a stable order. std::set<std::string> ClassNames; for (const auto &I : @@ -2060,10 +2060,10 @@ void ItaniumVTableBuilder::dumpLayout(raw_ostream &Out) { } Out << '\n'; - + if (isBuildingConstructorVTable()) return; - + if (MostDerivedClass->getNumVBases()) { // We store the virtual base class names and their offsets in a map to get // a stable order. @@ -2074,7 +2074,7 @@ void ItaniumVTableBuilder::dumpLayout(raw_ostream &Out) { CharUnits OffsetOffset = I.second; ClassNamesAndOffsets.insert(std::make_pair(ClassName, OffsetOffset)); } - + Out << "Virtual base offset offsets for '"; MostDerivedClass->printQualifiedName(Out); Out << "' ("; @@ -2086,17 +2086,17 @@ void ItaniumVTableBuilder::dumpLayout(raw_ostream &Out) { Out << "\n"; } - + if (!Thunks.empty()) { // We store the method names in a map to get a stable order. std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls; for (const auto &I : Thunks) { const CXXMethodDecl *MD = I.first; - std::string MethodName = + std::string MethodName = PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual, MD); - + MethodNamesAndDecls.insert(std::make_pair(MethodName, MD)); } @@ -2113,12 +2113,12 @@ void ItaniumVTableBuilder::dumpLayout(raw_ostream &Out) { Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size(); Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n"; - + for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) { const ThunkInfo &Thunk = ThunksVector[I]; Out << llvm::format("%4d | ", I); - + // If this function pointer has a return pointer adjustment, dump it. if (!Thunk.Return.isEmpty()) { Out << "return adjustment: " << Thunk.Return.NonVirtual; @@ -2136,16 +2136,16 @@ void ItaniumVTableBuilder::dumpLayout(raw_ostream &Out) { if (!Thunk.This.isEmpty()) { Out << "this adjustment: "; Out << Thunk.This.NonVirtual << " non-virtual"; - + if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) { Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset; Out << " vcall offset offset"; } } - + Out << '\n'; } - + Out << '\n'; } } @@ -2227,7 +2227,7 @@ uint64_t ItaniumVTableContext::getMethodVTableIndex(GlobalDecl GD) { MethodVTableIndicesTy::iterator I = MethodVTableIndices.find(GD); if (I != MethodVTableIndices.end()) return I->second; - + const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent(); computeVTableRelatedInformation(RD); @@ -2241,8 +2241,8 @@ CharUnits ItaniumVTableContext::getVirtualBaseOffsetOffset(const CXXRecordDecl *RD, const CXXRecordDecl *VBase) { ClassPairTy ClassPair(RD, VBase); - - VirtualBaseClassOffsetOffsetsMapTy::iterator I = + + VirtualBaseClassOffsetOffsetsMapTy::iterator I = VirtualBaseClassOffsetOffsets.find(ClassPair); if (I != VirtualBaseClassOffsetOffsets.end()) return I->second; @@ -2258,10 +2258,10 @@ ItaniumVTableContext::getVirtualBaseOffsetOffset(const CXXRecordDecl *RD, VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I.second)); } - + I = VirtualBaseClassOffsetOffsets.find(ClassPair); assert(I != VirtualBaseClassOffsetOffsets.end() && "Did not find index!"); - + return I->second; } @@ -2298,10 +2298,10 @@ ItaniumVTableContext::computeVTableRelatedInformation(const CXXRecordDecl *RD) { // the rest of the vtable related information. if (!RD->getNumVBases()) return; - + const CXXRecordDecl *VBase = RD->vbases_begin()->getType()->getAsCXXRecordDecl(); - + if (VirtualBaseClassOffsetOffsets.count(std::make_pair(RD, VBase))) return; diff --git a/lib/Analysis/AnalysisDeclContext.cpp b/lib/Analysis/AnalysisDeclContext.cpp index 486fffbe1299..9557f68452ff 100644 --- a/lib/Analysis/AnalysisDeclContext.cpp +++ b/lib/Analysis/AnalysisDeclContext.cpp @@ -56,13 +56,13 @@ using ManagedAnalysisMap = llvm::DenseMap<const void *, ManagedAnalysis *>; AnalysisDeclContext::AnalysisDeclContext(AnalysisDeclContextManager *Mgr, const Decl *d, const CFG::BuildOptions &buildOptions) - : Manager(Mgr), D(d), cfgBuildOptions(buildOptions) { + : Manager(Mgr), D(d), cfgBuildOptions(buildOptions) { cfgBuildOptions.forcedBlkExprs = &forcedBlkExprs; } AnalysisDeclContext::AnalysisDeclContext(AnalysisDeclContextManager *Mgr, const Decl *d) - : Manager(Mgr), D(d) { + : Manager(Mgr), D(d) { cfgBuildOptions.forcedBlkExprs = &forcedBlkExprs; } @@ -154,7 +154,7 @@ const ImplicitParamDecl *AnalysisDeclContext::getSelfDecl() const { const VarDecl *VD = I.getVariable(); if (isSelfDecl(VD)) return dyn_cast<ImplicitParamDecl>(VD); - } + } } auto *CXXMethod = dyn_cast<CXXMethodDecl>(D); @@ -191,7 +191,7 @@ AnalysisDeclContext::getBlockForRegisteredExpression(const Stmt *stmt) { assert(forcedBlkExprs); if (const auto *e = dyn_cast<Expr>(stmt)) stmt = e->IgnoreParens(); - CFG::BuildOptions::ForcedBlkExprs::const_iterator itr = + CFG::BuildOptions::ForcedBlkExprs::const_iterator itr = forcedBlkExprs->find(stmt); assert(itr != forcedBlkExprs->end()); return itr->second; @@ -251,7 +251,7 @@ CFG *AnalysisDeclContext::getUnoptimizedCFG() { CFGStmtMap *AnalysisDeclContext::getCFGStmtMap() { if (cfgStmtMap) return cfgStmtMap.get(); - + if (CFG *c = getCFG()) { cfgStmtMap.reset(CFGStmtMap::Build(c, &getParentMap())); return cfgStmtMap.get(); @@ -263,7 +263,7 @@ CFGStmtMap *AnalysisDeclContext::getCFGStmtMap() { CFGReverseBlockReachabilityAnalysis *AnalysisDeclContext::getCFGReachablityAnalysis() { if (CFA) return CFA.get(); - + if (CFG *c = getCFG()) { CFA.reset(new CFGReverseBlockReachabilityAnalysis(*c)); return CFA.get(); @@ -346,7 +346,7 @@ bool AnalysisDeclContext::isInStdNamespace(const Decl *D) { LocationContextManager &AnalysisDeclContext::getLocationContextManager() { assert(Manager && "Cannot create LocationContexts without an AnalysisDeclContextManager!"); - return Manager->getLocationContextManager(); + return Manager->getLocationContextManager(); } //===----------------------------------------------------------------------===// @@ -562,9 +562,9 @@ public: IgnoredContexts.insert(BR->getBlockDecl()); Visit(BR->getBlockDecl()->getBody()); } - + void VisitPseudoObjectExpr(PseudoObjectExpr *PE) { - for (PseudoObjectExpr::semantics_iterator it = PE->semantics_begin(), + for (PseudoObjectExpr::semantics_iterator it = PE->semantics_begin(), et = PE->semantics_end(); it != et; ++it) { Expr *Semantic = *it; if (auto *OVE = dyn_cast<OpaqueValueExpr>(Semantic)) diff --git a/lib/Analysis/BodyFarm.cpp b/lib/Analysis/BodyFarm.cpp index b9fb15b2db25..ac8fcdc912a0 100644 --- a/lib/Analysis/BodyFarm.cpp +++ b/lib/Analysis/BodyFarm.cpp @@ -50,33 +50,33 @@ namespace { class ASTMaker { public: ASTMaker(ASTContext &C) : C(C) {} - + /// Create a new BinaryOperator representing a simple assignment. BinaryOperator *makeAssignment(const Expr *LHS, const Expr *RHS, QualType Ty); - + /// Create a new BinaryOperator representing a comparison. BinaryOperator *makeComparison(const Expr *LHS, const Expr *RHS, BinaryOperator::Opcode Op); - + /// Create a new compound stmt using the provided statements. CompoundStmt *makeCompound(ArrayRef<Stmt*>); - + /// Create a new DeclRefExpr for the referenced variable. DeclRefExpr *makeDeclRefExpr(const VarDecl *D, bool RefersToEnclosingVariableOrCapture = false); - + /// Create a new UnaryOperator representing a dereference. UnaryOperator *makeDereference(const Expr *Arg, QualType Ty); - + /// Create an implicit cast for an integer conversion. Expr *makeIntegralCast(const Expr *Arg, QualType Ty); - + /// Create an implicit cast to a builtin boolean type. ImplicitCastExpr *makeIntegralCastToBoolean(const Expr *Arg); - + /// Create an implicit cast for lvalue-to-rvaluate conversions. ImplicitCastExpr *makeLvalueToRvalue(const Expr *Arg, QualType Ty); - + /// Make RValue out of variable declaration, creating a temporary /// DeclRefExpr in the process. ImplicitCastExpr * @@ -92,10 +92,10 @@ public: /// Create an Objective-C ivar reference. ObjCIvarRefExpr *makeObjCIvarRef(const Expr *Base, const ObjCIvarDecl *IVar); - + /// Create a Return statement. ReturnStmt *makeReturn(const Expr *RetVal); - + /// Create an integer literal expression of the given type. IntegerLiteral *makeIntegerLiteral(uint64_t Value, QualType Ty); @@ -342,7 +342,7 @@ static Stmt *create_call_once(ASTContext &C, const FunctionDecl *D) { // Nullable pointer, non-null iff function is a CXXRecordDecl. CXXRecordDecl *CallbackRecordDecl = CallbackType->getAsCXXRecordDecl(); QualType FlagType = Flag->getType().getNonReferenceType(); - auto *FlagRecordDecl = dyn_cast_or_null<RecordDecl>(FlagType->getAsTagDecl()); + auto *FlagRecordDecl = FlagType->getAsRecordDecl(); if (!FlagRecordDecl) { LLVM_DEBUG(llvm::dbgs() << "Flag field is not a record: " @@ -506,9 +506,9 @@ static Stmt *create_dispatch_once(ASTContext &C, const FunctionDecl *D) { // block(); // } // } - + ASTMaker M(C); - + // (1) Create the call. CallExpr *CE = new (C) CallExpr( /*ASTContext=*/C, @@ -532,11 +532,11 @@ static Stmt *create_dispatch_once(ASTContext &C, const FunctionDecl *D) { PredicateTy), M.makeIntegralCast(DoneValue, PredicateTy), PredicateTy); - + // (3) Create the compound statement. Stmt *Stmts[] = { B, CE }; CompoundStmt *CS = M.makeCompound(Stmts); - + // (4) Create the 'if' condition. ImplicitCastExpr *LValToRval = M.makeLvalueToRvalue( @@ -576,7 +576,7 @@ static Stmt *create_dispatch_sync(ASTContext &C, const FunctionDecl *D) { // void dispatch_sync(dispatch_queue_t queue, void (^block)(void)) { // block(); // } - // + // ASTMaker M(C); DeclRefExpr *DR = M.makeDeclRefExpr(PV); ImplicitCastExpr *ICE = M.makeLvalueToRvalue(DR, Ty); @@ -612,16 +612,16 @@ static Stmt *create_OSAtomicCompareAndSwap(ASTContext &C, const FunctionDecl *D) const ParmVarDecl *NewValue = D->getParamDecl(1); QualType NewValueTy = NewValue->getType(); - + assert(OldValueTy == NewValueTy); - + const ParmVarDecl *TheValue = D->getParamDecl(2); QualType TheValueTy = TheValue->getType(); const PointerType *PT = TheValueTy->getAs<PointerType>(); if (!PT) return nullptr; QualType PointeeTy = PT->getPointeeType(); - + ASTMaker M(C); // Construct the comparison. Expr *Comparison = @@ -643,29 +643,29 @@ static Stmt *create_OSAtomicCompareAndSwap(ASTContext &C, const FunctionDecl *D) PointeeTy), M.makeLvalueToRvalue(M.makeDeclRefExpr(NewValue), NewValueTy), NewValueTy); - + Expr *BoolVal = M.makeObjCBool(true); Expr *RetVal = isBoolean ? M.makeIntegralCastToBoolean(BoolVal) : M.makeIntegralCast(BoolVal, ResultTy); Stmts[1] = M.makeReturn(RetVal); CompoundStmt *Body = M.makeCompound(Stmts); - + // Construct the else clause. BoolVal = M.makeObjCBool(false); RetVal = isBoolean ? M.makeIntegralCastToBoolean(BoolVal) : M.makeIntegralCast(BoolVal, ResultTy); Stmt *Else = M.makeReturn(RetVal); - + /// Construct the If. Stmt *If = new (C) IfStmt(C, SourceLocation(), false, nullptr, nullptr, Comparison, Body, SourceLocation(), Else); - return If; + return If; } Stmt *BodyFarm::getBody(const FunctionDecl *D) { D = D->getCanonicalDecl(); - + Optional<Stmt *> &Val = Bodies[D]; if (Val.hasValue()) return Val.getValue(); @@ -692,7 +692,7 @@ Stmt *BodyFarm::getBody(const FunctionDecl *D) { .Case("dispatch_once", create_dispatch_once) .Default(nullptr); } - + if (FF) { Val = FF(C, D); } else if (Injector) { Val = Injector->getBody(D); } return Val.getValue(); diff --git a/lib/Analysis/CFG.cpp b/lib/Analysis/CFG.cpp index 8a3ab15458dd..97829de7ace3 100644 --- a/lib/Analysis/CFG.cpp +++ b/lib/Analysis/CFG.cpp @@ -145,7 +145,7 @@ static bool areExprTypesCompatible(const Expr *E1, const Expr *E2) { namespace { class CFGBuilder; - + /// The CFG builder uses a recursive algorithm to build the CFG. When /// we process an expression, sometimes we know that we must add the /// subexpressions as block-level expressions. For example: @@ -279,7 +279,7 @@ public: private: BumpVectorContext ctx; - + /// Automatic variables in order of declaration. AutomaticVarsTy Vars; @@ -366,7 +366,7 @@ class TryResult { public: TryResult() = default; TryResult(bool b) : X(b ? 1 : 0) {} - + bool isTrue() const { return X == 1; } bool isFalse() const { return X == 0; } bool isKnown() const { return X >= 0; } @@ -492,11 +492,11 @@ class CFGBuilder { bool badCFG = false; const CFG::BuildOptions &BuildOpts; - + // State to track for building switch statements. bool switchExclusivelyCovered = false; Expr::EvalResult *switchCond = nullptr; - + CFG::BuildOptions::ForcedBlkExprs::value_type *cachedEntry = nullptr; const Stmt *lastLookup = nullptr; @@ -516,7 +516,7 @@ public: std::unique_ptr<CFG> buildCFG(const Decl *D, Stmt *Statement); bool alwaysAdd(const Stmt *stmt); - + private: // Visitors to walk an AST and construct the CFG. CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, AddStmtChoice asc); @@ -569,6 +569,7 @@ private: CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S); CFGBlock *VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S); CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S); + CFGBlock *VisitObjCMessageExpr(ObjCMessageExpr *E, AddStmtChoice asc); CFGBlock *VisitPseudoObjectExpr(PseudoObjectExpr *E); CFGBlock *VisitReturnStmt(ReturnStmt *R); CFGBlock *VisitSEHExceptStmt(SEHExceptStmt *S); @@ -683,6 +684,25 @@ private: void findConstructionContexts(const ConstructionContextLayer *Layer, Stmt *Child); + // Scan all arguments of a call expression for a construction context. + // These sorts of call expressions don't have a common superclass, + // hence strict duck-typing. + template <typename CallLikeExpr, + typename = typename std::enable_if< + std::is_same<CallLikeExpr, CallExpr>::value || + std::is_same<CallLikeExpr, CXXConstructExpr>::value || + std::is_same<CallLikeExpr, ObjCMessageExpr>::value>> + void findConstructionContextsForArguments(CallLikeExpr *E) { + for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { + Expr *Arg = E->getArg(i); + if (Arg->getType()->getAsCXXRecordDecl() && !Arg->isGLValue()) + findConstructionContexts( + ConstructionContextLayer::create(cfg->getBumpVectorContext(), + ConstructionContextItem(E, i)), + Arg); + } + } + // Unset the construction context after consuming it. This is done immediately // after adding the CFGConstructor or CFGCXXRecordTypedCall element, so // there's no need to do this manually in every Visit... function. @@ -721,6 +741,19 @@ private: void addLocalScopeAndDtors(Stmt *S); + const ConstructionContext *retrieveAndCleanupConstructionContext(Expr *E) { + if (!BuildOpts.AddRichCXXConstructors) + return nullptr; + + const ConstructionContextLayer *Layer = ConstructionContextMap.lookup(E); + if (!Layer) + return nullptr; + + cleanupConstructionContext(E); + return ConstructionContext::createFromLayers(cfg->getBumpVectorContext(), + Layer); + } + // Interface to CFGBlock - adding CFGElements. void appendStmt(CFGBlock *B, const Stmt *S) { @@ -733,16 +766,10 @@ private: } void appendConstructor(CFGBlock *B, CXXConstructExpr *CE) { - if (BuildOpts.AddRichCXXConstructors) { - if (const ConstructionContextLayer *Layer = - ConstructionContextMap.lookup(CE)) { - cleanupConstructionContext(CE); - if (const auto *CC = ConstructionContext::createFromLayers( - cfg->getBumpVectorContext(), Layer)) { - B->appendConstructor(CE, CC, cfg->getBumpVectorContext()); - return; - } - } + if (const ConstructionContext *CC = + retrieveAndCleanupConstructionContext(CE)) { + B->appendConstructor(CE, CC, cfg->getBumpVectorContext()); + return; } // No valid construction context found. Fall back to statement. @@ -753,18 +780,10 @@ private: if (alwaysAdd(CE) && cachedEntry) cachedEntry->second = B; - if (BuildOpts.AddRichCXXConstructors) { - if (CFGCXXRecordTypedCall::isCXXRecordTypedCall(CE, *Context)) { - if (const ConstructionContextLayer *Layer = - ConstructionContextMap.lookup(CE)) { - cleanupConstructionContext(CE); - if (const auto *CC = ConstructionContext::createFromLayers( - cfg->getBumpVectorContext(), Layer)) { - B->appendCXXRecordTypedCall(CE, CC, cfg->getBumpVectorContext()); - return; - } - } - } + if (const ConstructionContext *CC = + retrieveAndCleanupConstructionContext(CE)) { + B->appendCXXRecordTypedCall(CE, CC, cfg->getBumpVectorContext()); + return; } // No valid construction context found. Fall back to statement. @@ -787,6 +806,20 @@ private: B->appendMemberDtor(FD, cfg->getBumpVectorContext()); } + void appendObjCMessage(CFGBlock *B, ObjCMessageExpr *ME) { + if (alwaysAdd(ME) && cachedEntry) + cachedEntry->second = B; + + if (const ConstructionContext *CC = + retrieveAndCleanupConstructionContext(ME)) { + B->appendCXXRecordTypedCall(ME, CC, cfg->getBumpVectorContext()); + return; + } + + B->appendStmt(const_cast<ObjCMessageExpr *>(ME), + cfg->getBumpVectorContext()); + } + void appendTemporaryDtor(CFGBlock *B, CXXBindTemporaryExpr *E) { B->appendTemporaryDtor(E, cfg->getBumpVectorContext()); } @@ -1067,7 +1100,7 @@ private: bool tryEvaluate(Expr *S, Expr::EvalResult &outResult) { if (!BuildOpts.PruneTriviallyFalseEdges) return false; - return !S->isTypeDependent() && + return !S->isTypeDependent() && !S->isValueDependent() && S->EvaluateAsRValue(outResult, *Context); } @@ -1183,18 +1216,18 @@ inline bool AddStmtChoice::alwaysAdd(CFGBuilder &builder, bool CFGBuilder::alwaysAdd(const Stmt *stmt) { bool shouldAdd = BuildOpts.alwaysAdd(stmt); - + if (!BuildOpts.forcedBlkExprs) return shouldAdd; - if (lastLookup == stmt) { + if (lastLookup == stmt) { if (cachedEntry) { assert(cachedEntry->first == stmt); return true; } return shouldAdd; } - + lastLookup = stmt; // Perform the lookup! @@ -1215,7 +1248,7 @@ bool CFGBuilder::alwaysAdd(const Stmt *stmt) { cachedEntry = &*itr; return true; } - + // FIXME: Add support for dependent-sized array types in C++? // Does it even make sense to build a CFG for an uninstantiated template? static const VariableArrayType *FindVA(const Type *t) { @@ -1232,6 +1265,8 @@ static const VariableArrayType *FindVA(const Type *t) { void CFGBuilder::consumeConstructionContext( const ConstructionContextLayer *Layer, Expr *E) { + assert((isa<CXXConstructExpr>(E) || isa<CallExpr>(E) || + isa<ObjCMessageExpr>(E)) && "Expression cannot construct an object!"); if (const ConstructionContextLayer *PreviouslyStoredLayer = ConstructionContextMap.lookup(E)) { (void)PreviouslyStoredLayer; @@ -1252,8 +1287,8 @@ void CFGBuilder::findConstructionContexts( if (!Child) return; - auto withExtraLayer = [this, Layer](Stmt *S) { - return ConstructionContextLayer::create(cfg->getBumpVectorContext(), S, + auto withExtraLayer = [this, Layer](const ConstructionContextItem &Item) { + return ConstructionContextLayer::create(cfg->getBumpVectorContext(), Item, Layer); }; @@ -1275,10 +1310,11 @@ void CFGBuilder::findConstructionContexts( case Stmt::CallExprClass: case Stmt::CXXMemberCallExprClass: case Stmt::CXXOperatorCallExprClass: - case Stmt::UserDefinedLiteralClass: { - auto *CE = cast<CallExpr>(Child); - if (CFGCXXRecordTypedCall::isCXXRecordTypedCall(CE, *Context)) - consumeConstructionContext(Layer, CE); + case Stmt::UserDefinedLiteralClass: + case Stmt::ObjCMessageExprClass: { + auto *E = cast<Expr>(Child); + if (CFGCXXRecordTypedCall::isCXXRecordTypedCall(E)) + consumeConstructionContext(Layer, E); break; } case Stmt::ExprWithCleanupsClass: { @@ -1313,18 +1349,17 @@ void CFGBuilder::findConstructionContexts( // it indicates the beginning of a temporary object construction context, // so it shouldn't be found in the middle. However, if it is the beginning // of an elidable copy or move construction context, we need to include it. - if (const auto *CE = - dyn_cast_or_null<CXXConstructExpr>(Layer->getTriggerStmt())) { - if (CE->isElidable()) { - auto *MTE = cast<MaterializeTemporaryExpr>(Child); - findConstructionContexts(withExtraLayer(MTE), MTE->GetTemporaryExpr()); - } + if (Layer->getItem().getKind() == + ConstructionContextItem::ElidableConstructorKind) { + auto *MTE = cast<MaterializeTemporaryExpr>(Child); + findConstructionContexts(withExtraLayer(MTE), MTE->GetTemporaryExpr()); } break; } case Stmt::ConditionalOperatorClass: { auto *CO = cast<ConditionalOperator>(Child); - if (!dyn_cast_or_null<MaterializeTemporaryExpr>(Layer->getTriggerStmt())) { + if (Layer->getItem().getKind() != + ConstructionContextItem::MaterializationKind) { // If the object returned by the conditional operator is not going to be a // temporary object that needs to be immediately materialized, then // it must be C++17 with its mandatory copy elision. Do not yet promise @@ -1427,7 +1462,7 @@ std::unique_ptr<CFG> CFGBuilder::buildCFG(const Decl *D, Stmt *Statement) { // If there is no target block that contains label, then we are looking // at an incomplete AST. Handle this by not registering a successor. if (LI == LabelMap.end()) continue; - + addSuccessor(B, LI->second.block); } @@ -1513,7 +1548,7 @@ CFGBlock *CFGBuilder::addInitializer(CXXCtorInitializer *I) { return Block; } -/// Retrieve the type of the temporary object whose lifetime was +/// Retrieve the type of the temporary object whose lifetime was /// extended by a local reference with the given initializer. static QualType getReferenceInitTemporaryType(const Expr *Init, bool *FoundMTE = nullptr) { @@ -1766,7 +1801,7 @@ LocalScope* CFGBuilder::createOrReuseLocalScope(LocalScope* Scope) { } /// addLocalScopeForStmt - Add LocalScope to local scopes tree for statement -/// that should create implicit scope (e.g. if/else substatements). +/// that should create implicit scope (e.g. if/else substatements). void CFGBuilder::addLocalScopeForStmt(Stmt *S) { if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime && !BuildOpts.AddScopes) @@ -2101,6 +2136,9 @@ CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc) { case Stmt::ObjCForCollectionStmtClass: return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S)); + case Stmt::ObjCMessageExprClass: + return VisitObjCMessageExpr(cast<ObjCMessageExpr>(S), asc); + case Stmt::OpaqueValueExprClass: return Block; @@ -2383,12 +2421,7 @@ CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, AddStmtChoice asc) { if (!boundType.isNull()) calleeType = boundType; } - // FIXME: Once actually implemented, this construction context layer should - // include the number of the argument as well. - for (auto Arg: C->arguments()) { - findConstructionContexts( - ConstructionContextLayer::create(cfg->getBumpVectorContext(), C), Arg); - } + findConstructionContextsForArguments(C); // If this is a call to a no-return function, this stops the block here. bool NoReturn = getFunctionExtInfo(*calleeType).getNoReturn(); @@ -2574,7 +2607,7 @@ CFGBlock *CFGBuilder::VisitConditionalOperator(AbstractConditionalOperator *C, // At least one of this or the above will be run. return addStmt(BCO->getCommon()); } - + return addStmt(condExpr); } @@ -2583,7 +2616,7 @@ CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) { // CFG entirely. if (isa<LabelDecl>(*DS->decl_begin())) return Block; - + // This case also handles static_asserts. if (DS->isSingleDecl()) return VisitDeclSubExpr(DS); @@ -3032,7 +3065,7 @@ CFGBlock *CFGBuilder::VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc) { } return LastBlock; } - + CFGBlock *CFGBuilder::VisitGotoStmt(GotoStmt *G) { // Goto is a control-flow statement. Thus we stop processing the current // block and create a new one. @@ -3146,7 +3179,7 @@ CFGBlock *CFGBuilder::VisitForStmt(ForStmt *F) { else if (badCFG) return nullptr; } - + // Because of short-circuit evaluation, the condition of the loop can span // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that // evaluate the condition. @@ -3188,8 +3221,7 @@ CFGBlock *CFGBuilder::VisitForStmt(ForStmt *F) { const DeclStmt *DS = F->getConditionVariableDeclStmt(); assert(DS->isSingleDecl()); findConstructionContexts( - ConstructionContextLayer::create(cfg->getBumpVectorContext(), - const_cast<DeclStmt *>(DS)), + ConstructionContextLayer::create(cfg->getBumpVectorContext(), DS), Init); appendStmt(Block, DS); EntryConditionBlock = addStmt(Init); @@ -3214,7 +3246,7 @@ CFGBlock *CFGBuilder::VisitForStmt(ForStmt *F) { // Link up the loop-back block to the entry condition block. addSuccessor(TransitionBlock, EntryConditionBlock); - + // The condition block is the implicit successor for any code above the loop. Succ = EntryConditionBlock; @@ -3334,7 +3366,7 @@ CFGBlock *CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) { CFGBlock *LoopBackBlock = nullptr; Succ = LoopBackBlock = createBlock(); LoopBackBlock->setLoopTarget(S); - + BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos); ContinueJumpTarget = JumpTarget(Succ, ScopePos); @@ -3401,7 +3433,7 @@ CFGBlock *CFGBuilder::VisitPseudoObjectExpr(PseudoObjectExpr *E) { // Add the PseudoObject as the last thing. appendStmt(Block, E); - CFGBlock *lastBlock = Block; + CFGBlock *lastBlock = Block; // Before that, evaluate all of the semantics in order. In // CFG-land, that means appending them in reverse order. @@ -3580,6 +3612,16 @@ CFGBlock *CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) { return VisitStmt(S, AddStmtChoice::AlwaysAdd); } +CFGBlock *CFGBuilder::VisitObjCMessageExpr(ObjCMessageExpr *ME, + AddStmtChoice asc) { + findConstructionContextsForArguments(ME); + + autoCreateBlock(); + appendObjCMessage(Block, ME); + + return VisitChildren(ME); +} + CFGBlock *CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr *T) { // If we were in the middle of a block we stop processing that block. if (badCFG) @@ -3734,7 +3776,7 @@ CFGBlock *CFGBuilder::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E, // VLA types have expressions that must be evaluated. CFGBlock *lastBlock = Block; - + if (E->isArgumentType()) { for (const VariableArrayType *VA =FindVA(E->getArgumentType().getTypePtr()); VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr())) @@ -3863,7 +3905,7 @@ CFGBlock *CFGBuilder::VisitSwitchStmt(SwitchStmt *Terminator) { return LastBlock; } - + static bool shouldAddCase(bool &switchExclusivelyCovered, const Expr::EvalResult *switchCond, const CaseStmt *CS, @@ -3878,7 +3920,7 @@ static bool shouldAddCase(bool &switchExclusivelyCovered, // Evaluate the LHS of the case value. const llvm::APSInt &lhsInt = CS->getLHS()->EvaluateKnownConstInt(Ctx); const llvm::APSInt &condInt = switchCond->Val.getInt(); - + if (condInt == lhsInt) { addCase = true; switchExclusivelyCovered = true; @@ -3897,7 +3939,7 @@ static bool shouldAddCase(bool &switchExclusivelyCovered, else addCase = true; } - return addCase; + return addCase; } CFGBlock *CFGBuilder::VisitCaseStmt(CaseStmt *CS) { @@ -4069,7 +4111,7 @@ CFGBlock *CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt *CS) { CFGBlock *CatchBlock = Block; if (!CatchBlock) CatchBlock = createBlock(); - + // CXXCatchStmt is more than just a label. They have semantic meaning // as well, as they implicitly "initialize" the catch variable. Add // it to the CFG as a CFGElement so that the control-flow of these @@ -4244,6 +4286,11 @@ CFGBlock *CFGBuilder::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E, CFGBlock *CFGBuilder::VisitCXXConstructExpr(CXXConstructExpr *C, AddStmtChoice asc) { + // If the constructor takes objects as arguments by value, we need to properly + // construct these objects. Construction contexts we find here aren't for the + // constructor C, they're for its arguments only. + findConstructionContextsForArguments(C); + autoCreateBlock(); appendConstructor(Block, C); @@ -4624,7 +4671,7 @@ CFGImplicitDtor::getDestructorDecl(ASTContext &astContext) const { const RecordType *recordType = ty->getAs<RecordType>(); const CXXRecordDecl *classDecl = cast<CXXRecordDecl>(recordType->getDecl()); - return classDecl->getDestructor(); + return classDecl->getDestructor(); } case CFGElement::DeleteDtor: { const CXXDeleteExpr *DE = castAs<CFGDeleteDtor>().getDeleteExpr(); @@ -4722,7 +4769,7 @@ public: for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) { unsigned j = 1; for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ; - BI != BEnd; ++BI, ++j ) { + BI != BEnd; ++BI, ++j ) { if (Optional<CFGStmt> SE = BI->getAs<CFGStmt>()) { const Stmt *stmt= SE->getStmt(); std::pair<unsigned, unsigned> P((*I)->getBlockID(), j); @@ -4961,7 +5008,7 @@ static void print_construction_context(raw_ostream &OS, OS << ", "; const auto *SICC = cast<SimpleConstructorInitializerConstructionContext>(CC); print_initializer(OS, Helper, SICC->getCXXCtorInitializer()); - break; + return; } case ConstructionContext::CXX17ElidedCopyConstructorInitializerKind: { OS << ", "; @@ -5012,6 +5059,17 @@ static void print_construction_context(raw_ostream &OS, Stmts.push_back(TOCC->getConstructorAfterElision()); break; } + case ConstructionContext::ArgumentKind: { + const auto *ACC = cast<ArgumentConstructionContext>(CC); + if (const Stmt *BTE = ACC->getCXXBindTemporaryExpr()) { + OS << ", "; + Helper.handledStmt(const_cast<Stmt *>(BTE), OS); + } + OS << ", "; + Helper.handledStmt(const_cast<Expr *>(ACC->getCallLikeExpr()), OS); + OS << "+" << ACC->getIndex(); + return; + } } for (auto I: Stmts) if (I) { @@ -5151,7 +5209,7 @@ static void print_block(raw_ostream &OS, const CFG* cfg, // Print the header. if (ShowColors) OS.changeColor(raw_ostream::YELLOW, true); - + OS << "\n [B" << B.getBlockID(); if (&B == &cfg->getEntry()) @@ -5164,7 +5222,7 @@ static void print_block(raw_ostream &OS, const CFG* cfg, OS << " (NORETURN)]\n"; else OS << "]\n"; - + if (ShowColors) OS.resetColor(); @@ -5235,7 +5293,7 @@ static void print_block(raw_ostream &OS, const CFG* cfg, CFGBlockTerminatorPrint TPrinter(OS, &Helper, PP); TPrinter.print(B.getTerminator()); OS << '\n'; - + if (ShowColors) OS.resetColor(); } @@ -5254,7 +5312,7 @@ static void print_block(raw_ostream &OS, const CFG* cfg, if (ShowColors) OS.changeColor(Color); - + for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end(); I != E; ++I, ++i) { if (i % 10 == 8) @@ -5271,7 +5329,7 @@ static void print_block(raw_ostream &OS, const CFG* cfg, if (!Reachable) OS << "(Unreachable)"; } - + if (ShowColors) OS.resetColor(); diff --git a/lib/Analysis/CFGReachabilityAnalysis.cpp b/lib/Analysis/CFGReachabilityAnalysis.cpp index 6f557e092fd7..cdad5b57aee8 100644 --- a/lib/Analysis/CFGReachabilityAnalysis.cpp +++ b/lib/Analysis/CFGReachabilityAnalysis.cpp @@ -27,13 +27,13 @@ CFGReverseBlockReachabilityAnalysis::CFGReverseBlockReachabilityAnalysis( bool CFGReverseBlockReachabilityAnalysis::isReachable(const CFGBlock *Src, const CFGBlock *Dst) { const unsigned DstBlockID = Dst->getBlockID(); - + // If we haven't analyzed the destination node, run the analysis now if (!analyzed[DstBlockID]) { mapReachability(Dst); analyzed[DstBlockID] = true; } - + // Return the cached result return reachable[DstBlockID][Src->getBlockID()]; } @@ -43,10 +43,10 @@ bool CFGReverseBlockReachabilityAnalysis::isReachable(const CFGBlock *Src, void CFGReverseBlockReachabilityAnalysis::mapReachability(const CFGBlock *Dst) { SmallVector<const CFGBlock *, 11> worklist; llvm::BitVector visited(analyzed.size()); - + ReachableSet &DstReachability = reachable[Dst->getBlockID()]; DstReachability.resize(analyzed.size(), false); - + // Start searching from the destination node, since we commonly will perform // multiple queries relating to a destination node. worklist.push_back(Dst); @@ -58,7 +58,7 @@ void CFGReverseBlockReachabilityAnalysis::mapReachability(const CFGBlock *Dst) { if (visited[block->getBlockID()]) continue; visited[block->getBlockID()] = true; - + // Update reachability information for this node -> Dst if (!firstRun) { // Don't insert Dst -> Dst unless it was a predecessor of itself @@ -66,9 +66,9 @@ void CFGReverseBlockReachabilityAnalysis::mapReachability(const CFGBlock *Dst) { } else firstRun = false; - + // Add the predecessors to the worklist. - for (CFGBlock::const_pred_iterator i = block->pred_begin(), + for (CFGBlock::const_pred_iterator i = block->pred_begin(), e = block->pred_end(); i != e; ++i) { if (*i) worklist.push_back(*i); diff --git a/lib/Analysis/CFGStmtMap.cpp b/lib/Analysis/CFGStmtMap.cpp index 19b80191f7a7..3eed0d52f848 100644 --- a/lib/Analysis/CFGStmtMap.cpp +++ b/lib/Analysis/CFGStmtMap.cpp @@ -24,7 +24,7 @@ static SMap *AsMap(void *m) { return (SMap*) m; } CFGStmtMap::~CFGStmtMap() { delete AsMap(M); } -CFGBlock *CFGStmtMap::getBlock(Stmt *S) { +CFGBlock *CFGStmtMap::getBlock(Stmt *S) { SMap *SM = AsMap(M); Stmt *X = S; @@ -53,17 +53,17 @@ static void Accumulate(SMap &SM, CFGBlock *B) { Optional<CFGStmt> CS = CE.getAs<CFGStmt>(); if (!CS) continue; - + CFGBlock *&Entry = SM[CS->getStmt()]; // If 'Entry' is already initialized (e.g., a terminator was already), // skip. if (Entry) continue; - + Entry = B; - + } - + // Look at the label of the block. if (Stmt *Label = B->getLabel()) SM[Label] = B; @@ -82,7 +82,7 @@ CFGStmtMap *CFGStmtMap::Build(CFG *C, ParentMap *PM) { SMap *SM = new SMap(); // Walk all blocks, accumulating the block-level expressions, labels, - // and terminators. + // and terminators. for (CFG::iterator I = C->begin(), E = C->end(); I != E; ++I) Accumulate(*SM, *I); diff --git a/lib/Analysis/CallGraph.cpp b/lib/Analysis/CallGraph.cpp index fb6d7e87a9a3..bac00680ffda 100644 --- a/lib/Analysis/CallGraph.cpp +++ b/lib/Analysis/CallGraph.cpp @@ -84,7 +84,7 @@ public: void VisitObjCMessageExpr(ObjCMessageExpr *ME) { if (ObjCInterfaceDecl *IDecl = ME->getReceiverInterface()) { Selector Sel = ME->getSelector(); - + // Find the callee definition within the same translation unit. Decl *D = nullptr; if (ME->isInstanceMessage()) diff --git a/lib/Analysis/CocoaConventions.cpp b/lib/Analysis/CocoaConventions.cpp index 4d57623e2161..b2d416c171a1 100644 --- a/lib/Analysis/CocoaConventions.cpp +++ b/lib/Analysis/CocoaConventions.cpp @@ -7,7 +7,7 @@ // //===----------------------------------------------------------------------===// // -// This file implements cocoa naming convention analysis. +// This file implements cocoa naming convention analysis. // //===----------------------------------------------------------------------===// @@ -34,15 +34,15 @@ bool cocoa::isRefType(QualType RetTy, StringRef Prefix, return false; RetTy = TD->getDecl()->getUnderlyingType(); } - + if (Name.empty()) return false; - + // Is the type void*? const PointerType* PT = RetTy->getAs<PointerType>(); if (!(PT->getPointeeType().getUnqualifiedType()->isVoidType())) return false; - + // Does the name start with the prefix? return Name.startswith(Prefix); } @@ -66,32 +66,32 @@ bool coreFoundation::isCFObjectRef(QualType T) { bool cocoa::isCocoaObjectRef(QualType Ty) { if (!Ty->isObjCObjectPointerType()) return false; - + const ObjCObjectPointerType *PT = Ty->getAs<ObjCObjectPointerType>(); - + // Can be true for objects with the 'NSObject' attribute. if (!PT) return true; - + // We assume that id<..>, id, Class, and Class<..> all represent tracked // objects. if (PT->isObjCIdType() || PT->isObjCQualifiedIdType() || PT->isObjCClassType() || PT->isObjCQualifiedClassType()) return true; - + // Does the interface subclass NSObject? // FIXME: We can memoize here if this gets too expensive. const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); - + // Assume that anything declared with a forward declaration and no // @interface subclasses NSObject. if (!ID->hasDefinition()) return true; - + for ( ; ID ; ID = ID->getSuperClass()) if (ID->getIdentifier()->getName() == "NSObject") return true; - + return false; } @@ -101,11 +101,11 @@ bool coreFoundation::followsCreateRule(const FunctionDecl *fn) { const IdentifierInfo *ident = fn->getIdentifier(); if (!ident) return false; StringRef functionName = ident->getName(); - + StringRef::iterator it = functionName.begin(); StringRef::iterator start = it; StringRef::iterator endI = functionName.end(); - + while (true) { // Scan for the start of 'create' or 'copy'. for ( ; it != endI ; ++it) { @@ -124,7 +124,7 @@ bool coreFoundation::followsCreateRule(const FunctionDecl *fn) { // Did we hit the end of the string? If so, we didn't find a match. if (it == endI) return false; - + // Scan for *lowercase* 'reate' or 'opy', followed by no lowercase // character. StringRef suffix = functionName.substr(it - start); @@ -137,10 +137,10 @@ bool coreFoundation::followsCreateRule(const FunctionDecl *fn) { // Keep scanning. continue; } - + if (it == endI || !isLowercase(*it)) return true; - + // If we matched a lowercase character, it isn't the end of the // word. Keep scanning. } diff --git a/lib/Analysis/ConstructionContext.cpp b/lib/Analysis/ConstructionContext.cpp index ed1e63243217..8169d4a93a6d 100644 --- a/lib/Analysis/ConstructionContext.cpp +++ b/lib/Analysis/ConstructionContext.cpp @@ -15,15 +15,17 @@ //===----------------------------------------------------------------------===// #include "clang/Analysis/ConstructionContext.h" +#include "clang/AST/ExprObjC.h" using namespace clang; const ConstructionContextLayer * -ConstructionContextLayer::create(BumpVectorContext &C, TriggerTy Trigger, +ConstructionContextLayer::create(BumpVectorContext &C, + const ConstructionContextItem &Item, const ConstructionContextLayer *Parent) { ConstructionContextLayer *CC = C.getAllocator().Allocate<ConstructionContextLayer>(); - return new (CC) ConstructionContextLayer(Trigger, Parent); + return new (CC) ConstructionContextLayer(Item, Parent); } bool ConstructionContextLayer::isStrictlyMoreSpecificThan( @@ -32,7 +34,7 @@ bool ConstructionContextLayer::isStrictlyMoreSpecificThan( while (true) { if (!Other) return Self; - if (!Self || !Self->isSameLayer(Other)) + if (!Self || !(Self->Item == Other->Item)) return false; Self = Self->getParent(); Other = Other->getParent(); @@ -40,145 +42,176 @@ bool ConstructionContextLayer::isStrictlyMoreSpecificThan( llvm_unreachable("The above loop can only be terminated via return!"); } +const ConstructionContext * +ConstructionContext::createMaterializedTemporaryFromLayers( + BumpVectorContext &C, const MaterializeTemporaryExpr *MTE, + const CXXBindTemporaryExpr *BTE, + const ConstructionContextLayer *ParentLayer) { + assert(MTE); + + // If the object requires destruction and is not lifetime-extended, + // then it must have a BTE within its MTE, otherwise it shouldn't. + // FIXME: This should be an assertion. + if (!BTE && !(MTE->getType().getCanonicalType()->getAsCXXRecordDecl() + ->hasTrivialDestructor() || + MTE->getStorageDuration() != SD_FullExpression)) { + return nullptr; + } + + // If the temporary is lifetime-extended, don't save the BTE, + // because we don't need a temporary destructor, but an automatic + // destructor. + if (MTE->getStorageDuration() != SD_FullExpression) { + BTE = nullptr; + } + + // Handle pre-C++17 copy and move elision. + const CXXConstructExpr *ElidedCE = nullptr; + const ConstructionContext *ElidedCC = nullptr; + if (ParentLayer) { + const ConstructionContextItem &ElidedItem = ParentLayer->getItem(); + assert(ElidedItem.getKind() == + ConstructionContextItem::ElidableConstructorKind); + ElidedCE = cast<CXXConstructExpr>(ElidedItem.getStmt()); + assert(ElidedCE->isElidable()); + // We're creating a construction context that might have already + // been created elsewhere. Maybe we should unique our construction + // contexts. That's what we often do, but in this case it's unlikely + // to bring any benefits. + ElidedCC = createFromLayers(C, ParentLayer->getParent()); + if (!ElidedCC) { + // We may fail to create the elided construction context. + // In this case, skip copy elision entirely. + return create<SimpleTemporaryObjectConstructionContext>(C, BTE, MTE); + } + return create<ElidedTemporaryObjectConstructionContext>( + C, BTE, MTE, ElidedCE, ElidedCC); + } + + // This is a normal temporary. + assert(!ParentLayer); + return create<SimpleTemporaryObjectConstructionContext>(C, BTE, MTE); +} + +const ConstructionContext *ConstructionContext::createBoundTemporaryFromLayers( + BumpVectorContext &C, const CXXBindTemporaryExpr *BTE, + const ConstructionContextLayer *ParentLayer) { + if (!ParentLayer) { + // A temporary object that doesn't require materialization. + // In particular, it shouldn't require copy elision, because + // copy/move constructors take a reference, which requires + // materialization to obtain the glvalue. + return create<SimpleTemporaryObjectConstructionContext>(C, BTE, + /*MTE=*/nullptr); + } + + const ConstructionContextItem &ParentItem = ParentLayer->getItem(); + switch (ParentItem.getKind()) { + case ConstructionContextItem::VariableKind: { + const auto *DS = cast<DeclStmt>(ParentItem.getStmt()); + assert(!cast<VarDecl>(DS->getSingleDecl())->getType().getCanonicalType() + ->getAsCXXRecordDecl()->hasTrivialDestructor()); + return create<CXX17ElidedCopyVariableConstructionContext>(C, DS, BTE); + } + case ConstructionContextItem::NewAllocatorKind: { + llvm_unreachable("This context does not accept a bound temporary!"); + } + case ConstructionContextItem::ReturnKind: { + assert(ParentLayer->isLast()); + const auto *RS = cast<ReturnStmt>(ParentItem.getStmt()); + assert(!RS->getRetValue()->getType().getCanonicalType() + ->getAsCXXRecordDecl()->hasTrivialDestructor()); + return create<CXX17ElidedCopyReturnedValueConstructionContext>(C, RS, + BTE); + } + + case ConstructionContextItem::MaterializationKind: { + // No assert. We may have an elidable copy on the grandparent layer. + const auto *MTE = cast<MaterializeTemporaryExpr>(ParentItem.getStmt()); + return createMaterializedTemporaryFromLayers(C, MTE, BTE, + ParentLayer->getParent()); + } + case ConstructionContextItem::TemporaryDestructorKind: { + llvm_unreachable("Duplicate CXXBindTemporaryExpr in the AST!"); + } + case ConstructionContextItem::ElidedDestructorKind: { + llvm_unreachable("Elided destructor items are not produced by the CFG!"); + } + case ConstructionContextItem::ElidableConstructorKind: { + llvm_unreachable("Materialization is necessary to put temporary into a " + "copy or move constructor!"); + } + case ConstructionContextItem::ArgumentKind: { + assert(ParentLayer->isLast()); + const auto *E = cast<Expr>(ParentItem.getStmt()); + assert(isa<CallExpr>(E) || isa<CXXConstructExpr>(E) || + isa<ObjCMessageExpr>(E)); + return create<ArgumentConstructionContext>(C, E, ParentItem.getIndex(), + BTE); + } + case ConstructionContextItem::InitializerKind: { + assert(ParentLayer->isLast()); + const auto *I = ParentItem.getCXXCtorInitializer(); + assert(!I->getAnyMember()->getType().getCanonicalType() + ->getAsCXXRecordDecl()->hasTrivialDestructor()); + return create<CXX17ElidedCopyConstructorInitializerConstructionContext>( + C, I, BTE); + } + } // switch (ParentItem.getKind()) + + llvm_unreachable("Unexpected construction context with destructor!"); +} + const ConstructionContext *ConstructionContext::createFromLayers( BumpVectorContext &C, const ConstructionContextLayer *TopLayer) { // Before this point all we've had was a stockpile of arbitrary layers. // Now validate that it is shaped as one of the finite amount of expected // patterns. - if (const Stmt *S = TopLayer->getTriggerStmt()) { - if (const auto *DS = dyn_cast<DeclStmt>(S)) { - assert(TopLayer->isLast()); - return create<SimpleVariableConstructionContext>(C, DS); - } - if (const auto *NE = dyn_cast<CXXNewExpr>(S)) { - assert(TopLayer->isLast()); - return create<NewAllocatedObjectConstructionContext>(C, NE); - } - if (const auto *BTE = dyn_cast<CXXBindTemporaryExpr>(S)) { - const MaterializeTemporaryExpr *MTE = nullptr; - assert(BTE->getType().getCanonicalType() - ->getAsCXXRecordDecl()->hasNonTrivialDestructor()); - // For temporaries with destructors, there may or may not be - // lifetime extension on the parent layer. - if (const ConstructionContextLayer *ParentLayer = TopLayer->getParent()) { - // C++17 *requires* elision of the constructor at the return site - // and at variable/member initialization site, while previous standards - // were allowing an optional elidable constructor. - // This is the C++17 copy-elided construction into a ctor initializer. - if (const CXXCtorInitializer *I = ParentLayer->getTriggerInit()) { - return create< - CXX17ElidedCopyConstructorInitializerConstructionContext>(C, - I, BTE); - } - assert(ParentLayer->getTriggerStmt() && - "Non-statement-based layers have been handled above!"); - // This is the normal, non-C++17 case: a temporary object which has - // both destruction and materialization info attached to it in the AST. - if ((MTE = dyn_cast<MaterializeTemporaryExpr>( - ParentLayer->getTriggerStmt()))) { - if (MTE->getStorageDuration() != SD_FullExpression) { - // If the temporary is lifetime-extended, don't save the BTE, - // because we don't need a temporary destructor, but an automatic - // destructor. - BTE = nullptr; - } - - // Handle pre-C++17 copy and move elision. - const CXXConstructExpr *ElidedCE = nullptr; - const ConstructionContext *ElidedCC = nullptr; - if (const ConstructionContextLayer *ElidedLayer = - ParentLayer->getParent()) { - ElidedCE = cast<CXXConstructExpr>(ElidedLayer->getTriggerStmt()); - assert(ElidedCE->isElidable()); - // We're creating a construction context that might have already - // been created elsewhere. Maybe we should unique our construction - // contexts. That's what we often do, but in this case it's unlikely - // to bring any benefits. - ElidedCC = createFromLayers(C, ElidedLayer->getParent()); - if (!ElidedCC) { - // We may fail to create the elided construction context. - // In this case, skip copy elision entirely. - return create<SimpleTemporaryObjectConstructionContext>(C, BTE, - MTE); - } else { - return create<ElidedTemporaryObjectConstructionContext>( - C, BTE, MTE, ElidedCE, ElidedCC); - } - } - assert(ParentLayer->isLast()); - return create<SimpleTemporaryObjectConstructionContext>(C, BTE, MTE); - } - assert(ParentLayer->isLast()); - - // This is a constructor into a function argument. Not implemented yet. - if (isa<CallExpr>(ParentLayer->getTriggerStmt())) - return nullptr; - // This is C++17 copy-elided construction into return statement. - if (auto *RS = dyn_cast<ReturnStmt>(ParentLayer->getTriggerStmt())) { - assert(!RS->getRetValue()->getType().getCanonicalType() - ->getAsCXXRecordDecl()->hasTrivialDestructor()); - return create<CXX17ElidedCopyReturnedValueConstructionContext>(C, - RS, BTE); - } - // This is C++17 copy-elided construction into a simple variable. - if (auto *DS = dyn_cast<DeclStmt>(ParentLayer->getTriggerStmt())) { - assert(!cast<VarDecl>(DS->getSingleDecl())->getType() - .getCanonicalType()->getAsCXXRecordDecl() - ->hasTrivialDestructor()); - return create<CXX17ElidedCopyVariableConstructionContext>(C, DS, BTE); - } - llvm_unreachable("Unexpected construction context with destructor!"); - } - // A temporary object that doesn't require materialization. - // In particular, it shouldn't require copy elision, because - // copy/move constructors take a reference, which requires - // materialization to obtain the glvalue. - return create<SimpleTemporaryObjectConstructionContext>(C, BTE, - /*MTE=*/nullptr); - } - if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(S)) { - // If the object requires destruction and is not lifetime-extended, - // then it must have a BTE within its MTE. - // FIXME: This should be an assertion. - if (!(MTE->getType().getCanonicalType() - ->getAsCXXRecordDecl()->hasTrivialDestructor() || - MTE->getStorageDuration() != SD_FullExpression)) - return nullptr; - - // Handle pre-C++17 copy and move elision. - const CXXConstructExpr *ElidedCE = nullptr; - const ConstructionContext *ElidedCC = nullptr; - if (const ConstructionContextLayer *ElidedLayer = TopLayer->getParent()) { - ElidedCE = cast<CXXConstructExpr>(ElidedLayer->getTriggerStmt()); - assert(ElidedCE->isElidable()); - // We're creating a construction context that might have already - // been created elsewhere. Maybe we should unique our construction - // contexts. That's what we often do, but in this case it's unlikely - // to bring any benefits. - ElidedCC = createFromLayers(C, ElidedLayer->getParent()); - if (!ElidedCC) { - // We may fail to create the elided construction context. - // In this case, skip copy elision entirely. - return create<SimpleTemporaryObjectConstructionContext>(C, nullptr, - MTE); - } - return create<ElidedTemporaryObjectConstructionContext>( - C, nullptr, MTE, ElidedCE, ElidedCC); - } - assert(TopLayer->isLast()); - return create<SimpleTemporaryObjectConstructionContext>(C, nullptr, MTE); - } - if (const auto *RS = dyn_cast<ReturnStmt>(S)) { - assert(TopLayer->isLast()); - return create<SimpleReturnedValueConstructionContext>(C, RS); - } - // This is a constructor into a function argument. Not implemented yet. - if (isa<CallExpr>(TopLayer->getTriggerStmt())) - return nullptr; - llvm_unreachable("Unexpected construction context with statement!"); - } else if (const CXXCtorInitializer *I = TopLayer->getTriggerInit()) { + const ConstructionContextItem &TopItem = TopLayer->getItem(); + switch (TopItem.getKind()) { + case ConstructionContextItem::VariableKind: { + assert(TopLayer->isLast()); + const auto *DS = cast<DeclStmt>(TopItem.getStmt()); + return create<SimpleVariableConstructionContext>(C, DS); + } + case ConstructionContextItem::NewAllocatorKind: { + assert(TopLayer->isLast()); + const auto *NE = cast<CXXNewExpr>(TopItem.getStmt()); + return create<NewAllocatedObjectConstructionContext>(C, NE); + } + case ConstructionContextItem::ReturnKind: { assert(TopLayer->isLast()); + const auto *RS = cast<ReturnStmt>(TopItem.getStmt()); + return create<SimpleReturnedValueConstructionContext>(C, RS); + } + case ConstructionContextItem::MaterializationKind: { + const auto *MTE = cast<MaterializeTemporaryExpr>(TopItem.getStmt()); + return createMaterializedTemporaryFromLayers(C, MTE, /*BTE=*/nullptr, + TopLayer->getParent()); + } + case ConstructionContextItem::TemporaryDestructorKind: { + const auto *BTE = cast<CXXBindTemporaryExpr>(TopItem.getStmt()); + assert(BTE->getType().getCanonicalType()->getAsCXXRecordDecl() + ->hasNonTrivialDestructor()); + return createBoundTemporaryFromLayers(C, BTE, TopLayer->getParent()); + } + case ConstructionContextItem::ElidedDestructorKind: { + llvm_unreachable("Elided destructor items are not produced by the CFG!"); + } + case ConstructionContextItem::ElidableConstructorKind: { + llvm_unreachable("The argument needs to be materialized first!"); + } + case ConstructionContextItem::InitializerKind: { + assert(TopLayer->isLast()); + const CXXCtorInitializer *I = TopItem.getCXXCtorInitializer(); return create<SimpleConstructorInitializerConstructionContext>(C, I); } + case ConstructionContextItem::ArgumentKind: { + assert(TopLayer->isLast()); + const auto *E = cast<Expr>(TopItem.getStmt()); + return create<ArgumentConstructionContext>(C, E, TopItem.getIndex(), + /*BTE=*/nullptr); + } + } // switch (TopItem.getKind()) llvm_unreachable("Unexpected construction context!"); } diff --git a/lib/Analysis/Consumed.cpp b/lib/Analysis/Consumed.cpp index a46386e2d13d..bc81a71b3d91 100644 --- a/lib/Analysis/Consumed.cpp +++ b/lib/Analysis/Consumed.cpp @@ -40,7 +40,7 @@ // TODO: Adjust states of args to constructors in the same way that arguments to // function calls are handled. // TODO: Use information from tests in for- and while-loop conditional. -// TODO: Add notes about the actual and expected state for +// TODO: Add notes about the actual and expected state for // TODO: Correctly identify unreachable blocks when chaining boolean operators. // TODO: Adjust the parser and AttributesList class to support lists of // identifiers. @@ -124,30 +124,30 @@ static bool isCallableInState(const CallableWhenAttr *CWAttr, case CallableWhenAttr::Unknown: MappedAttrState = CS_Unknown; break; - + case CallableWhenAttr::Unconsumed: MappedAttrState = CS_Unconsumed; break; - + case CallableWhenAttr::Consumed: MappedAttrState = CS_Consumed; break; } - + if (MappedAttrState == State) return true; } - + return false; } static bool isConsumableType(const QualType &QT) { if (QT->isPointerType() || QT->isReferenceType()) return false; - + if (const CXXRecordDecl *RD = QT->getAsCXXRecordDecl()) return RD->hasAttr<ConsumableAttr>(); - + return false; } @@ -250,13 +250,13 @@ static StringRef stateToString(ConsumedState State) { switch (State) { case consumed::CS_None: return "none"; - + case consumed::CS_Unknown: return "unknown"; - + case consumed::CS_Unconsumed: return "unconsumed"; - + case consumed::CS_Consumed: return "consumed"; } @@ -307,7 +307,7 @@ class PropagationInfo { VarTestResult LTest; VarTestResult RTest; }; - + union { ConsumedState State; VarTestResult VarTest; @@ -315,7 +315,7 @@ class PropagationInfo { const CXXBindTemporaryExpr *Tmp; BinTestTy BinTest; }; - + public: PropagationInfo() = default; PropagationInfo(const VarTestResult &VarTest) @@ -326,7 +326,7 @@ public: VarTest.Var = Var; VarTest.TestsFor = TestsFor; } - + PropagationInfo(const BinaryOperator *Source, EffectiveOp EOp, const VarTestResult <est, const VarTestResult &RTest) : InfoType(IT_BinTest) { @@ -335,7 +335,7 @@ public: BinTest.LTest = LTest; BinTest.RTest = RTest; } - + PropagationInfo(const BinaryOperator *Source, EffectiveOp EOp, const VarDecl *LVar, ConsumedState LTestsFor, const VarDecl *RVar, ConsumedState RTestsFor) @@ -347,46 +347,46 @@ public: BinTest.RTest.Var = RVar; BinTest.RTest.TestsFor = RTestsFor; } - + PropagationInfo(ConsumedState State) : InfoType(IT_State), State(State) {} PropagationInfo(const VarDecl *Var) : InfoType(IT_Var), Var(Var) {} PropagationInfo(const CXXBindTemporaryExpr *Tmp) : InfoType(IT_Tmp), Tmp(Tmp) {} - + const ConsumedState &getState() const { assert(InfoType == IT_State); return State; } - + const VarTestResult &getVarTest() const { assert(InfoType == IT_VarTest); return VarTest; } - + const VarTestResult &getLTest() const { assert(InfoType == IT_BinTest); return BinTest.LTest; } - + const VarTestResult &getRTest() const { assert(InfoType == IT_BinTest); return BinTest.RTest; } - + const VarDecl *getVar() const { assert(InfoType == IT_Var); return Var; } - + const CXXBindTemporaryExpr *getTmp() const { assert(InfoType == IT_Tmp); return Tmp; } - + ConsumedState getAsState(const ConsumedStateMap *StateMap) const { assert(isVar() || isTmp() || isState()); - + if (isVar()) return StateMap->getState(Var); else if (isTmp()) @@ -396,39 +396,39 @@ public: else return CS_None; } - + EffectiveOp testEffectiveOp() const { assert(InfoType == IT_BinTest); return BinTest.EOp; } - + const BinaryOperator * testSourceNode() const { assert(InfoType == IT_BinTest); return BinTest.Source; } - + bool isValid() const { return InfoType != IT_None; } bool isState() const { return InfoType == IT_State; } bool isVarTest() const { return InfoType == IT_VarTest; } bool isBinTest() const { return InfoType == IT_BinTest; } bool isVar() const { return InfoType == IT_Var; } bool isTmp() const { return InfoType == IT_Tmp; } - + bool isTest() const { return InfoType == IT_VarTest || InfoType == IT_BinTest; } - + bool isPointerToValue() const { return InfoType == IT_Var || InfoType == IT_Tmp; } - + PropagationInfo invertTest() const { assert(InfoType == IT_VarTest || InfoType == IT_BinTest); - + if (InfoType == IT_VarTest) { return PropagationInfo(VarTest.Var, invertConsumedUnconsumed(VarTest.TestsFor)); - + } else if (InfoType == IT_BinTest) { return PropagationInfo(BinTest.Source, BinTest.EOp == EO_And ? EO_Or : EO_And, @@ -447,7 +447,7 @@ static void setStateForVarOrTmp(ConsumedStateMap *StateMap, const PropagationInfo &PInfo, ConsumedState State) { assert(PInfo.isVar() || PInfo.isTmp()); - + if (PInfo.isVar()) StateMap->setState(PInfo.getVar(), State); else @@ -462,7 +462,7 @@ class ConsumedStmtVisitor : public ConstStmtVisitor<ConsumedStmtVisitor> { using PairType= std::pair<const Stmt *, PropagationInfo>; using InfoEntry = MapType::iterator; using ConstInfoEntry = MapType::const_iterator; - + AnalysisDeclContext &AC; ConsumedAnalyzer &Analyzer; ConsumedStateMap *StateMap; @@ -498,7 +498,7 @@ public: SourceLocation BlameLoc); bool handleCall(const CallExpr *Call, const Expr *ObjArg, const FunctionDecl *FunD); - + void VisitBinaryOperator(const BinaryOperator *BinOp); void VisitCallExpr(const CallExpr *Call); void VisitCastExpr(const CastExpr *Cast); @@ -518,16 +518,16 @@ public: ConsumedStmtVisitor(AnalysisDeclContext &AC, ConsumedAnalyzer &Analyzer, ConsumedStateMap *StateMap) : AC(AC), Analyzer(Analyzer), StateMap(StateMap) {} - + PropagationInfo getInfo(const Expr *StmtNode) const { ConstInfoEntry Entry = findInfo(StmtNode); - + if (Entry != PropagationMap.end()) return Entry->second; else return {}; } - + void reset(ConsumedStateMap *NewStateMap) { StateMap = NewStateMap; } @@ -696,7 +696,7 @@ void ConsumedStmtVisitor::propagateReturnType(const Expr *Call, ReturnState = mapReturnTypestateAttrState(RTA); else ReturnState = mapConsumableAttrState(RetType); - + PropagationMap.insert(PairType(Call, PropagationInfo(ReturnState))); } } @@ -707,16 +707,16 @@ void ConsumedStmtVisitor::VisitBinaryOperator(const BinaryOperator *BinOp) { case BO_LOr : { InfoEntry LEntry = findInfo(BinOp->getLHS()), REntry = findInfo(BinOp->getRHS()); - + VarTestResult LTest, RTest; - + if (LEntry != PropagationMap.end() && LEntry->second.isVarTest()) { LTest = LEntry->second.getVarTest(); } else { LTest.Var = nullptr; LTest.TestsFor = CS_None; } - + if (REntry != PropagationMap.end() && REntry->second.isVarTest()) { RTest = REntry->second.getVarTest(); } else { @@ -729,12 +729,12 @@ void ConsumedStmtVisitor::VisitBinaryOperator(const BinaryOperator *BinOp) { static_cast<EffectiveOp>(BinOp->getOpcode() == BO_LOr), LTest, RTest))); break; } - + case BO_PtrMemD: case BO_PtrMemI: forwardInfo(BinOp->getLHS(), BinOp); break; - + default: break; } @@ -762,9 +762,9 @@ void ConsumedStmtVisitor::VisitCastExpr(const CastExpr *Cast) { void ConsumedStmtVisitor::VisitCXXBindTemporaryExpr( const CXXBindTemporaryExpr *Temp) { - + InfoEntry Entry = findInfo(Temp->getSubExpr()); - + if (Entry != PropagationMap.end() && !Entry->second.isTest()) { StateMap->setState(Temp, Entry->second.getAsState(StateMap)); PropagationMap.insert(PairType(Temp, PropagationInfo(Temp))); @@ -776,13 +776,13 @@ void ConsumedStmtVisitor::VisitCXXConstructExpr(const CXXConstructExpr *Call) { ASTContext &CurrContext = AC.getASTContext(); QualType ThisType = Constructor->getThisType(CurrContext)->getPointeeType(); - + if (!isConsumableType(ThisType)) return; - + // FIXME: What should happen if someone annotates the move constructor? if (ReturnTypestateAttr *RTA = Constructor->getAttr<ReturnTypestateAttr>()) { - // TODO: Adjust state of args appropriately. + // TODO: Adjust state of args appropriately. ConsumedState RetState = mapReturnTypestateAttrState(RTA); PropagationMap.insert(PairType(Call, PropagationInfo(RetState))); } else if (Constructor->isDefaultConstructor()) { @@ -840,10 +840,10 @@ void ConsumedStmtVisitor::VisitDeclRefExpr(const DeclRefExpr *DeclRef) { } void ConsumedStmtVisitor::VisitDeclStmt(const DeclStmt *DeclS) { - for (const auto *DI : DeclS->decls()) + for (const auto *DI : DeclS->decls()) if (isa<VarDecl>(DI)) VisitVarDecl(cast<VarDecl>(DI)); - + if (DeclS->isSingleDecl()) if (const auto *Var = dyn_cast_or_null<VarDecl>(DeclS->getSingleDecl())) PropagationMap.insert(PairType(DeclS, PropagationInfo(Var))); @@ -861,38 +861,38 @@ void ConsumedStmtVisitor::VisitMemberExpr(const MemberExpr *MExpr) { void ConsumedStmtVisitor::VisitParmVarDecl(const ParmVarDecl *Param) { QualType ParamType = Param->getType(); ConsumedState ParamState = consumed::CS_None; - + if (const ParamTypestateAttr *PTA = Param->getAttr<ParamTypestateAttr>()) - ParamState = mapParamTypestateAttrState(PTA); + ParamState = mapParamTypestateAttrState(PTA); else if (isConsumableType(ParamType)) - ParamState = mapConsumableAttrState(ParamType); + ParamState = mapConsumableAttrState(ParamType); else if (isRValueRef(ParamType) && isConsumableType(ParamType->getPointeeType())) - ParamState = mapConsumableAttrState(ParamType->getPointeeType()); + ParamState = mapConsumableAttrState(ParamType->getPointeeType()); else if (ParamType->isReferenceType() && isConsumableType(ParamType->getPointeeType())) ParamState = consumed::CS_Unknown; - + if (ParamState != CS_None) StateMap->setState(Param, ParamState); } void ConsumedStmtVisitor::VisitReturnStmt(const ReturnStmt *Ret) { ConsumedState ExpectedState = Analyzer.getExpectedReturnState(); - + if (ExpectedState != CS_None) { InfoEntry Entry = findInfo(Ret->getRetValue()); - + if (Entry != PropagationMap.end()) { ConsumedState RetState = Entry->second.getAsState(StateMap); - + if (RetState != ExpectedState) Analyzer.WarningsHandler.warnReturnTypestateMismatch( Ret->getReturnLoc(), stateToString(ExpectedState), stateToString(RetState)); } } - + StateMap->checkParamsForReturnTypestate(Ret->getLocStart(), Analyzer.WarningsHandler); } @@ -900,17 +900,17 @@ void ConsumedStmtVisitor::VisitReturnStmt(const ReturnStmt *Ret) { void ConsumedStmtVisitor::VisitUnaryOperator(const UnaryOperator *UOp) { InfoEntry Entry = findInfo(UOp->getSubExpr()); if (Entry == PropagationMap.end()) return; - + switch (UOp->getOpcode()) { case UO_AddrOf: PropagationMap.insert(PairType(UOp, Entry->second)); break; - + case UO_LNot: if (Entry->second.isTest()) PropagationMap.insert(PairType(UOp, Entry->second.invertTest())); break; - + default: break; } @@ -924,7 +924,7 @@ void ConsumedStmtVisitor::VisitVarDecl(const VarDecl *Var) { if (VIT != PropagationMap.end()) { PropagationInfo PInfo = VIT->second; ConsumedState St = PInfo.getAsState(StateMap); - + if (St != consumed::CS_None) { StateMap->setState(Var, St); return; @@ -940,7 +940,7 @@ static void splitVarStateForIf(const IfStmt *IfNode, const VarTestResult &Test, ConsumedStateMap *ThenStates, ConsumedStateMap *ElseStates) { ConsumedState VarState = ThenStates->getState(Test.Var); - + if (VarState == CS_Unknown) { ThenStates->setState(Test.Var, Test.TestsFor); ElseStates->setState(Test.Var, invertConsumedUnconsumed(Test.TestsFor)); @@ -956,10 +956,10 @@ static void splitVarStateForIfBinOp(const PropagationInfo &PInfo, ConsumedStateMap *ElseStates) { const VarTestResult <est = PInfo.getLTest(), &RTest = PInfo.getRTest(); - + ConsumedState LState = LTest.Var ? ThenStates->getState(LTest.Var) : CS_None, RState = RTest.Var ? ThenStates->getState(RTest.Var) : CS_None; - + if (LTest.Var) { if (PInfo.testEffectiveOp() == EO_And) { if (LState == CS_Unknown) { @@ -987,7 +987,7 @@ static void splitVarStateForIfBinOp(const PropagationInfo &PInfo, } } } - + if (RTest.Var) { if (PInfo.testEffectiveOp() == EO_And) { if (RState == CS_Unknown) @@ -1008,7 +1008,7 @@ bool ConsumedBlockInfo::allBackEdgesVisited(const CFGBlock *CurrBlock, const CFGBlock *TargetBlock) { assert(CurrBlock && "Block pointer must not be NULL"); assert(TargetBlock && "TargetBlock pointer must not be NULL"); - + unsigned int CurrBlockOrder = VisitOrder[CurrBlock->getBlockID()]; for (CFGBlock::const_pred_iterator PI = TargetBlock->pred_begin(), PE = TargetBlock->pred_end(); PI != PE; ++PI) { @@ -1069,7 +1069,7 @@ ConsumedBlockInfo::getInfo(const CFGBlock *Block) { bool ConsumedBlockInfo::isBackEdge(const CFGBlock *From, const CFGBlock *To) { assert(From && "From block must not be NULL"); assert(To && "From block must not be NULL"); - + return VisitOrder[From->getBlockID()] > VisitOrder[To->getBlockID()]; } @@ -1080,7 +1080,7 @@ bool ConsumedBlockInfo::isBackEdgeTarget(const CFGBlock *Block) { // edge. if (Block->pred_size() < 2) return false; - + unsigned int BlockVisitOrder = VisitOrder[Block->getBlockID()]; for (CFGBlock::const_pred_iterator PI = Block->pred_begin(), PE = Block->pred_end(); PI != PE; ++PI) { @@ -1092,16 +1092,16 @@ bool ConsumedBlockInfo::isBackEdgeTarget(const CFGBlock *Block) { void ConsumedStateMap::checkParamsForReturnTypestate(SourceLocation BlameLoc, ConsumedWarningsHandlerBase &WarningsHandler) const { - + for (const auto &DM : VarMap) { if (isa<ParmVarDecl>(DM.first)) { const auto *Param = cast<ParmVarDecl>(DM.first); const ReturnTypestateAttr *RTA = Param->getAttr<ReturnTypestateAttr>(); - + if (!RTA) continue; - - ConsumedState ExpectedState = mapReturnTypestateAttrState(RTA); + + ConsumedState ExpectedState = mapReturnTypestateAttrState(RTA); if (DM.second != ExpectedState) WarningsHandler.warnParamReturnTypestateMismatch(BlameLoc, Param->getNameAsString(), stateToString(ExpectedState), @@ -1116,20 +1116,20 @@ void ConsumedStateMap::clearTemporaries() { ConsumedState ConsumedStateMap::getState(const VarDecl *Var) const { VarMapType::const_iterator Entry = VarMap.find(Var); - + if (Entry != VarMap.end()) return Entry->second; - + return CS_None; } ConsumedState ConsumedStateMap::getState(const CXXBindTemporaryExpr *Tmp) const { TmpMapType::const_iterator Entry = TmpMap.find(Tmp); - + if (Entry != TmpMap.end()) return Entry->second; - + return CS_None; } @@ -1143,10 +1143,10 @@ void ConsumedStateMap::intersect(const ConsumedStateMap &Other) { for (const auto &DM : Other.VarMap) { LocalState = this->getState(DM.first); - + if (LocalState == CS_None) continue; - + if (LocalState != DM.second) VarMap[DM.first] = CS_Unknown; } @@ -1155,16 +1155,16 @@ void ConsumedStateMap::intersect(const ConsumedStateMap &Other) { void ConsumedStateMap::intersectAtLoopHead(const CFGBlock *LoopHead, const CFGBlock *LoopBack, const ConsumedStateMap *LoopBackStates, ConsumedWarningsHandlerBase &WarningsHandler) { - + ConsumedState LocalState; SourceLocation BlameLoc = getLastStmtLoc(LoopBack); - - for (const auto &DM : LoopBackStates->VarMap) { + + for (const auto &DM : LoopBackStates->VarMap) { LocalState = this->getState(DM.first); - + if (LocalState == CS_None) continue; - + if (LocalState != DM.second) { VarMap[DM.first] = CS_Unknown; WarningsHandler.warnLoopStateMismatch(BlameLoc, @@ -1195,7 +1195,7 @@ void ConsumedStateMap::remove(const CXXBindTemporaryExpr *Tmp) { bool ConsumedStateMap::operator!=(const ConsumedStateMap *Other) const { for (const auto &DM : Other->VarMap) if (this->getState(DM.first) != DM.second) - return true; + return true; return false; } @@ -1235,15 +1235,15 @@ bool ConsumedAnalyzer::splitState(const CFGBlock *CurrBlock, std::unique_ptr<ConsumedStateMap> FalseStates( new ConsumedStateMap(*CurrStates)); PropagationInfo PInfo; - + if (const auto *IfNode = dyn_cast_or_null<IfStmt>(CurrBlock->getTerminator().getStmt())) { const Expr *Cond = IfNode->getCond(); - + PInfo = Visitor.getInfo(Cond); if (!PInfo.isValid() && isa<BinaryOperator>(Cond)) PInfo = Visitor.getInfo(cast<BinaryOperator>(Cond)->getRHS()); - + if (PInfo.isVarTest()) { CurrStates->setSource(Cond); FalseStates->setSource(Cond); @@ -1262,26 +1262,26 @@ bool ConsumedAnalyzer::splitState(const CFGBlock *CurrBlock, if (!PInfo.isVarTest()) { if ((BinOp = dyn_cast_or_null<BinaryOperator>(BinOp->getLHS()))) { PInfo = Visitor.getInfo(BinOp->getRHS()); - + if (!PInfo.isVarTest()) return false; } else { return false; } } - + CurrStates->setSource(BinOp); FalseStates->setSource(BinOp); - + const VarTestResult &Test = PInfo.getVarTest(); ConsumedState VarState = CurrStates->getState(Test.Var); - + if (BinOp->getOpcode() == BO_LAnd) { if (VarState == CS_Unknown) CurrStates->setState(Test.Var, Test.TestsFor); else if (VarState == invertConsumedUnconsumed(Test.TestsFor)) CurrStates->markUnreachable(); - + } else if (BinOp->getOpcode() == BO_LOr) { if (VarState == CS_Unknown) FalseStates->setState(Test.Var, @@ -1292,9 +1292,9 @@ bool ConsumedAnalyzer::splitState(const CFGBlock *CurrBlock, } else { return false; } - + CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(); - + if (*SI) BlockInfo.addInfo(*SI, std::move(CurrStates)); else @@ -1310,7 +1310,7 @@ void ConsumedAnalyzer::run(AnalysisDeclContext &AC) { const auto *D = dyn_cast_or_null<FunctionDecl>(AC.getDecl()); if (!D) return; - + CFG *CFGraph = AC.getCFG(); if (!CFGraph) return; @@ -1319,7 +1319,7 @@ void ConsumedAnalyzer::run(AnalysisDeclContext &AC) { PostOrderCFGView *SortedGraph = AC.getAnalysis<PostOrderCFGView>(); // AC.getCFG()->viewCFG(LangOptions()); - + BlockInfo = ConsumedBlockInfo(CFGraph->getNumBlockIDs(), SortedGraph); CurrStates = llvm::make_unique<ConsumedStateMap>(); @@ -1328,12 +1328,12 @@ void ConsumedAnalyzer::run(AnalysisDeclContext &AC) { // Add all trackable parameters to the state map. for (const auto *PI : D->parameters()) Visitor.VisitParmVarDecl(PI); - + // Visit all of the function's basic blocks. for (const auto *CurrBlock : *SortedGraph) { if (!CurrStates) CurrStates = BlockInfo.getInfo(CurrBlock); - + if (!CurrStates) { continue; } else if (!CurrStates->isReachable()) { @@ -1349,34 +1349,34 @@ void ConsumedAnalyzer::run(AnalysisDeclContext &AC) { case CFGElement::Statement: Visitor.Visit(B.castAs<CFGStmt>().getStmt()); break; - + case CFGElement::TemporaryDtor: { const CFGTemporaryDtor &DTor = B.castAs<CFGTemporaryDtor>(); const CXXBindTemporaryExpr *BTE = DTor.getBindTemporaryExpr(); - + Visitor.checkCallability(PropagationInfo(BTE), DTor.getDestructorDecl(AC.getASTContext()), BTE->getExprLoc()); CurrStates->remove(BTE); break; } - + case CFGElement::AutomaticObjectDtor: { const CFGAutomaticObjDtor &DTor = B.castAs<CFGAutomaticObjDtor>(); SourceLocation Loc = DTor.getTriggerStmt()->getLocEnd(); const VarDecl *Var = DTor.getVarDecl(); - + Visitor.checkCallability(PropagationInfo(Var), DTor.getDestructorDecl(AC.getASTContext()), Loc); break; } - + default: break; } } - + // TODO: Handle other forms of branching with precision, including while- // and for-loops. (Deferred) if (!splitState(CurrBlock, Visitor)) { @@ -1406,13 +1406,13 @@ void ConsumedAnalyzer::run(AnalysisDeclContext &AC) { CurrStates = nullptr; } } - + if (CurrBlock == &AC.getCFG()->getExit() && D->getCallResultType()->isVoidType()) CurrStates->checkParamsForReturnTypestate(D->getLocation(), WarningsHandler); } // End of block iterator. - + // Delete the last existing state map. CurrStates = nullptr; diff --git a/lib/Analysis/FormatString.cpp b/lib/Analysis/FormatString.cpp index c62e537e92dd..f37e4affae3f 100644 --- a/lib/Analysis/FormatString.cpp +++ b/lib/Analysis/FormatString.cpp @@ -407,7 +407,7 @@ ArgType::matchesType(ASTContext &C, QualType argTy) const { case WIntTy: { - QualType PromoArg = + QualType PromoArg = argTy->isPromotableIntegerType() ? C.getPromotedIntegerType(argTy) : argTy; @@ -623,7 +623,7 @@ const char *ConversionSpecifier::toString() const { Optional<ConversionSpecifier> ConversionSpecifier::getStandardSpecifier() const { ConversionSpecifier::Kind NewKind; - + switch (getKind()) { default: return None; @@ -672,7 +672,7 @@ bool FormatSpecifier::hasValidLengthModifier(const TargetInfo &Target) const { switch (LM.getKind()) { case LengthModifier::None: return true; - + // Handle most integer flags case LengthModifier::AsShort: if (Target.getTriple().isOSMSVCRT()) { @@ -712,7 +712,7 @@ bool FormatSpecifier::hasValidLengthModifier(const TargetInfo &Target) const { default: return false; } - + // Handle 'l' flag case LengthModifier::AsLong: // or AsWideChar switch (CS.getKind()) { @@ -745,7 +745,7 @@ bool FormatSpecifier::hasValidLengthModifier(const TargetInfo &Target) const { default: return false; } - + case LengthModifier::AsLongDouble: switch (CS.getKind()) { case ConversionSpecifier::aArg: diff --git a/lib/Analysis/FormatStringParsing.h b/lib/Analysis/FormatStringParsing.h index 17fd2f6aefb8..a63140b366cd 100644 --- a/lib/Analysis/FormatStringParsing.h +++ b/lib/Analysis/FormatStringParsing.h @@ -23,7 +23,7 @@ public: }; namespace analyze_format_string { - + OptionalAmount ParseAmount(const char *&Beg, const char *E); OptionalAmount ParseNonPositionAmount(const char *&Beg, const char *E, unsigned &argIndex); @@ -31,12 +31,12 @@ OptionalAmount ParseNonPositionAmount(const char *&Beg, const char *E, OptionalAmount ParsePositionAmount(FormatStringHandler &H, const char *Start, const char *&Beg, const char *E, PositionContext p); - + bool ParseFieldWidth(FormatStringHandler &H, FormatSpecifier &CS, const char *Start, const char *&Beg, const char *E, unsigned *argIndex); - + bool ParseArgPosition(FormatStringHandler &H, FormatSpecifier &CS, const char *Start, const char *&Beg, const char *E); @@ -62,7 +62,7 @@ public: SpecifierResult(const char *start, const T &fs) : FS(fs), Start(start), Stop(false) {} - + const char *getStart() const { return Start; } bool shouldStop() const { return Stop; } bool hasValue() const { return Start != nullptr; } @@ -72,7 +72,7 @@ public: } const T &getValue() { return FS; } }; - + } // end analyze_format_string namespace } // end clang namespace diff --git a/lib/Analysis/LiveVariables.cpp b/lib/Analysis/LiveVariables.cpp index b8ea1e960095..05bc1a5d102c 100644 --- a/lib/Analysis/LiveVariables.cpp +++ b/lib/Analysis/LiveVariables.cpp @@ -39,7 +39,7 @@ public: : enqueuedBlocks(cfg.getNumBlockIDs()), POV(Ctx.getAnalysis<PostOrderCFGView>()), worklist(POV->getComparator()) {} - + void enqueueBlock(const CFGBlock *block); void enqueuePredecessors(const CFGBlock *block); @@ -73,7 +73,7 @@ const CFGBlock *DataflowWorklist::dequeue() { namespace { class LiveVariablesImpl { -public: +public: AnalysisDeclContext &analysisContext; llvm::ImmutableSet<const Stmt *>::Factory SSetFact; llvm::ImmutableSet<const VarDecl *>::Factory DSetFact; @@ -83,7 +83,7 @@ public: llvm::DenseMap<const Stmt *, LiveVariables::LivenessValues> stmtsToLiveness; llvm::DenseMap<const DeclRefExpr *, unsigned> inAssignment; const bool killAtAssign; - + LiveVariables::LivenessValues merge(LiveVariables::LivenessValues valsA, LiveVariables::LivenessValues valsB); @@ -130,7 +130,7 @@ namespace { SET mergeSets(SET A, SET B) { if (A.isEmpty()) return B; - + for (typename SET::iterator it = B.begin(), ei = B.end(); it != ei; ++it) { A = A.add(*it); } @@ -142,17 +142,17 @@ void LiveVariables::Observer::anchor() { } LiveVariables::LivenessValues LiveVariablesImpl::merge(LiveVariables::LivenessValues valsA, - LiveVariables::LivenessValues valsB) { - + LiveVariables::LivenessValues valsB) { + llvm::ImmutableSetRef<const Stmt *> SSetRefA(valsA.liveStmts.getRootWithoutRetain(), SSetFact.getTreeFactory()), SSetRefB(valsB.liveStmts.getRootWithoutRetain(), SSetFact.getTreeFactory()); - - + + llvm::ImmutableSetRef<const VarDecl *> DSetRefA(valsA.liveDecls.getRootWithoutRetain(), DSetFact.getTreeFactory()), DSetRefB(valsB.liveDecls.getRootWithoutRetain(), DSetFact.getTreeFactory()); - + llvm::ImmutableSetRef<const BindingDecl *> BSetRefA(valsA.liveBindings.getRootWithoutRetain(), BSetFact.getTreeFactory()), BSetRefB(valsB.liveBindings.getRootWithoutRetain(), BSetFact.getTreeFactory()); @@ -160,12 +160,12 @@ LiveVariablesImpl::merge(LiveVariables::LivenessValues valsA, SSetRefA = mergeSets(SSetRefA, SSetRefB); DSetRefA = mergeSets(DSetRefA, DSetRefB); BSetRefA = mergeSets(BSetRefA, BSetRefB); - + // asImmutableSet() canonicalizes the tree, allowing us to do an easy // comparison afterwards. return LiveVariables::LivenessValues(SSetRefA.asImmutableSet(), DSetRefA.asImmutableSet(), - BSetRefA.asImmutableSet()); + BSetRefA.asImmutableSet()); } bool LiveVariables::LivenessValues::equals(const LivenessValues &V) const { @@ -211,7 +211,7 @@ public: void VisitBinaryOperator(BinaryOperator *BO); void VisitBlockExpr(BlockExpr *BE); - void VisitDeclRefExpr(DeclRefExpr *DR); + void VisitDeclRefExpr(DeclRefExpr *DR); void VisitDeclStmt(DeclStmt *DS); void VisitObjCForCollectionStmt(ObjCForCollectionStmt *OS); void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *UE); @@ -226,7 +226,7 @@ static const VariableArrayType *FindVA(QualType Ty) { if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(VT)) if (VAT->getSizeExpr()) return VAT; - + ty = VT->getElementType().getTypePtr(); } @@ -236,7 +236,7 @@ static const VariableArrayType *FindVA(QualType Ty) { static const Stmt *LookThroughStmt(const Stmt *S) { while (S) { if (const Expr *Ex = dyn_cast<Expr>(S)) - S = Ex->IgnoreParens(); + S = Ex->IgnoreParens(); if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(S)) { S = EWC->getSubExpr(); continue; @@ -259,15 +259,15 @@ static void AddLiveStmt(llvm::ImmutableSet<const Stmt *> &Set, void TransferFunctions::Visit(Stmt *S) { if (observer) observer->observeStmt(S, currentBlock, val); - + StmtVisitor<TransferFunctions>::Visit(S); - + if (isa<Expr>(S)) { val.liveStmts = LV.SSetFact.remove(val.liveStmts, S); } // Mark all children expressions live. - + switch (S->getStmtClass()) { default: break; @@ -344,7 +344,7 @@ void TransferFunctions::VisitBinaryOperator(BinaryOperator *B) { if (B->isAssignmentOp()) { if (!LV.killAtAssign) return; - + // Assigning to a variable? Expr *LHS = B->getLHS()->IgnoreParens(); @@ -414,7 +414,7 @@ void TransferFunctions::VisitObjCForCollectionStmt(ObjCForCollectionStmt *OS) { else if ((DR = dyn_cast<DeclRefExpr>(cast<Expr>(element)->IgnoreParens()))) { VD = cast<VarDecl>(DR->getDecl()); } - + if (VD) { val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD); if (observer && DR) @@ -444,12 +444,12 @@ void TransferFunctions::VisitUnaryOperator(UnaryOperator *UO) { // since a ++/-- acts as both a kill and a "use". if (!observer) return; - + switch (UO->getOpcode()) { default: return; case UO_PostInc: - case UO_PostDec: + case UO_PostDec: case UO_PreInc: case UO_PreDec: break; @@ -470,11 +470,11 @@ LiveVariablesImpl::runOnBlock(const CFGBlock *block, LiveVariables::Observer *obs) { TransferFunctions TF(*this, val, obs, block); - + // Visit the terminator (if any). if (const Stmt *term = block->getTerminator()) TF.Visit(const_cast<Stmt*>(term)); - + // Apply the transfer function for all Stmts in the block. for (CFGBlock::const_reverse_iterator it = block->rbegin(), ei = block->rend(); it != ei; ++it) { @@ -488,7 +488,7 @@ LiveVariablesImpl::runOnBlock(const CFGBlock *block, if (!elem.getAs<CFGStmt>()) continue; - + const Stmt *S = elem.castAs<CFGStmt>().getStmt(); TF.Visit(const_cast<Stmt*>(S)); stmtsToLiveness[S] = val; @@ -499,10 +499,10 @@ LiveVariablesImpl::runOnBlock(const CFGBlock *block, void LiveVariables::runOnAllBlocks(LiveVariables::Observer &obs) { const CFG *cfg = getImpl(impl).analysisContext.getCFG(); for (CFG::const_iterator it = cfg->begin(), ei = cfg->end(); it != ei; ++it) - getImpl(impl).runOnBlock(*it, getImpl(impl).blocksEndToLiveness[*it], &obs); + getImpl(impl).runOnBlock(*it, getImpl(impl).blocksEndToLiveness[*it], &obs); } -LiveVariables::LiveVariables(void *im) : impl(im) {} +LiveVariables::LiveVariables(void *im) : impl(im) {} LiveVariables::~LiveVariables() { delete (LiveVariablesImpl*) impl; @@ -533,7 +533,7 @@ LiveVariables::computeLiveness(AnalysisDeclContext &AC, for (CFG::const_iterator it = cfg->begin(), ei = cfg->end(); it != ei; ++it) { const CFGBlock *block = *it; worklist.enqueueBlock(block); - + // FIXME: Scan for DeclRefExprs using in the LHS of an assignment. // We need to do this because we lack context in the reverse analysis // to determine if a DeclRefExpr appears in such a context, and thus @@ -554,35 +554,35 @@ LiveVariables::computeLiveness(AnalysisDeclContext &AC, } } } - + while (const CFGBlock *block = worklist.dequeue()) { // Determine if the block's end value has changed. If not, we // have nothing left to do for this block. LivenessValues &prevVal = LV->blocksEndToLiveness[block]; - + // Merge the values of all successor blocks. LivenessValues val; for (CFGBlock::const_succ_iterator it = block->succ_begin(), ei = block->succ_end(); it != ei; ++it) { - if (const CFGBlock *succ = *it) { + if (const CFGBlock *succ = *it) { val = LV->merge(val, LV->blocksBeginToLiveness[succ]); } } - + if (!everAnalyzedBlock[block->getBlockID()]) everAnalyzedBlock[block->getBlockID()] = true; else if (prevVal.equals(val)) continue; prevVal = val; - + // Update the dataflow value for the start of this block. LV->blocksBeginToLiveness[block] = LV->runOnBlock(block, val); - + // Enqueue the value to the predecessors. worklist.enqueuePredecessors(block); } - + return new LiveVariables(LV); } @@ -595,7 +595,7 @@ void LiveVariablesImpl::dumpBlockLiveness(const SourceManager &M) { for (llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues>::iterator it = blocksEndToLiveness.begin(), ei = blocksEndToLiveness.end(); it != ei; ++it) { - vec.push_back(it->first); + vec.push_back(it->first); } llvm::sort(vec.begin(), vec.end(), [](const CFGBlock *A, const CFGBlock *B) { return A->getBlockID() < B->getBlockID(); @@ -607,14 +607,14 @@ void LiveVariablesImpl::dumpBlockLiveness(const SourceManager &M) { it = vec.begin(), ei = vec.end(); it != ei; ++it) { llvm::errs() << "\n[ B" << (*it)->getBlockID() << " (live variables at block exit) ]\n"; - + LiveVariables::LivenessValues vals = blocksEndToLiveness[*it]; declVec.clear(); - + for (llvm::ImmutableSet<const VarDecl *>::iterator si = vals.liveDecls.begin(), se = vals.liveDecls.end(); si != se; ++si) { - declVec.push_back(*si); + declVec.push_back(*si); } llvm::sort(declVec.begin(), declVec.end(), @@ -630,7 +630,7 @@ void LiveVariablesImpl::dumpBlockLiveness(const SourceManager &M) { llvm::errs() << ">\n"; } } - llvm::errs() << "\n"; + llvm::errs() << "\n"; } const void *LiveVariables::getTag() { static int x; return &x; } diff --git a/lib/Analysis/ObjCNoReturn.cpp b/lib/Analysis/ObjCNoReturn.cpp index 52d844bf9dd8..f27568c0c322 100644 --- a/lib/Analysis/ObjCNoReturn.cpp +++ b/lib/Analysis/ObjCNoReturn.cpp @@ -32,13 +32,13 @@ ObjCNoReturn::ObjCNoReturn(ASTContext &C) { // Generate selectors. SmallVector<IdentifierInfo*, 3> II; - + // raise:format: II.push_back(&C.Idents.get("raise")); II.push_back(&C.Idents.get("format")); NSExceptionInstanceRaiseSelectors[0] = C.Selectors.getSelector(II.size(), &II[0]); - + // raise:format:arguments: II.push_back(&C.Idents.get("arguments")); NSExceptionInstanceRaiseSelectors[1] = @@ -48,7 +48,7 @@ ObjCNoReturn::ObjCNoReturn(ASTContext &C) bool ObjCNoReturn::isImplicitNoReturn(const ObjCMessageExpr *ME) { Selector S = ME->getSelector(); - + if (ME->isInstanceMessage()) { // Check for the "raise" message. return S == RaiseSel; @@ -62,6 +62,6 @@ bool ObjCNoReturn::isImplicitNoReturn(const ObjCMessageExpr *ME) { } } } - + return false; } diff --git a/lib/Analysis/PostOrderCFGView.cpp b/lib/Analysis/PostOrderCFGView.cpp index 124424bf2567..d5d0bafe664c 100644 --- a/lib/Analysis/PostOrderCFGView.cpp +++ b/lib/Analysis/PostOrderCFGView.cpp @@ -22,11 +22,11 @@ void PostOrderCFGView::anchor() {} PostOrderCFGView::PostOrderCFGView(const CFG *cfg) { Blocks.reserve(cfg->getNumBlockIDs()); CFGBlockSet BSet(cfg); - + for (po_iterator I = po_iterator::begin(cfg, BSet), E = po_iterator::end(cfg, BSet); I != E; ++I) { BlockOrder[*I] = Blocks.size() + 1; - Blocks.push_back(*I); + Blocks.push_back(*I); } } @@ -43,7 +43,7 @@ bool PostOrderCFGView::BlockOrderCompare::operator()(const CFGBlock *b1, const CFGBlock *b2) const { PostOrderCFGView::BlockOrderTy::const_iterator b1It = POV.BlockOrder.find(b1); PostOrderCFGView::BlockOrderTy::const_iterator b2It = POV.BlockOrder.find(b2); - + unsigned b1V = (b1It == POV.BlockOrder.end()) ? 0 : b1It->second; unsigned b2V = (b2It == POV.BlockOrder.end()) ? 0 : b2It->second; return b1V > b2V; diff --git a/lib/Analysis/PrintfFormatString.cpp b/lib/Analysis/PrintfFormatString.cpp index 00591ab2b048..dcb15c5e3758 100644 --- a/lib/Analysis/PrintfFormatString.cpp +++ b/lib/Analysis/PrintfFormatString.cpp @@ -348,7 +348,7 @@ static PrintfSpecifierResult ParsePrintfSpecifier(FormatStringHandler &H, if (Target.getTriple().isOSMSVCRT()) k = ConversionSpecifier::ZArg; } - + // Check to see if we used the Objective-C modifier flags with // a conversion specifier other than '@'. if (k != ConversionSpecifier::ObjCObjArg && @@ -416,9 +416,9 @@ bool clang::analyze_format_string::ParseFormatStringHasSArg(const char *I, const char *E, const LangOptions &LO, const TargetInfo &Target) { - + unsigned argIndex = 0; - + // Keep looking for a %s format specifier until we have exhausted the string. FormatStringHandler H; while (I != E) { diff --git a/lib/Analysis/ProgramPoint.cpp b/lib/Analysis/ProgramPoint.cpp index 26b59bb71de2..d9833659d7b3 100644 --- a/lib/Analysis/ProgramPoint.cpp +++ b/lib/Analysis/ProgramPoint.cpp @@ -43,7 +43,7 @@ ProgramPoint ProgramPoint::getProgramPoint(const Stmt *S, ProgramPoint::Kind K, } } -SimpleProgramPointTag::SimpleProgramPointTag(StringRef MsgProvider, +SimpleProgramPointTag::SimpleProgramPointTag(StringRef MsgProvider, StringRef Msg) : Desc((MsgProvider + " : " + Msg).str()) {} diff --git a/lib/Analysis/ReachableCode.cpp b/lib/Analysis/ReachableCode.cpp index f644d503dc49..ed26a94f3d60 100644 --- a/lib/Analysis/ReachableCode.cpp +++ b/lib/Analysis/ReachableCode.cpp @@ -201,7 +201,7 @@ static bool isConfigurationValue(const Stmt *S, // Special case looking for the sigil '()' around an integer literal. if (const ParenExpr *PE = dyn_cast<ParenExpr>(S)) if (!PE->getLocStart().isMacroID()) - return isConfigurationValue(PE->getSubExpr(), PP, SilenceableCondVal, + return isConfigurationValue(PE->getSubExpr(), PP, SilenceableCondVal, IncludeIntegers, true); if (const Expr *Ex = dyn_cast<Expr>(S)) @@ -310,19 +310,19 @@ static unsigned scanFromBlock(const CFGBlock *Start, Preprocessor *PP, bool IncludeSometimesUnreachableEdges) { unsigned count = 0; - + // Prep work queue SmallVector<const CFGBlock*, 32> WL; - + // The entry block may have already been marked reachable // by the caller. if (!Reachable[Start->getBlockID()]) { ++count; Reachable[Start->getBlockID()] = true; } - + WL.push_back(Start); - + // Find the reachable blocks from 'Start'. while (!WL.empty()) { const CFGBlock *item = WL.pop_back_val(); @@ -337,7 +337,7 @@ static unsigned scanFromBlock(const CFGBlock *Start, if (!IncludeSometimesUnreachableEdges) TreatAllSuccessorsAsReachable = false; - for (CFGBlock::const_succ_iterator I = item->succ_begin(), + for (CFGBlock::const_succ_iterator I = item->succ_begin(), E = item->succ_end(); I != E; ++I) { const CFGBlock *B = *I; if (!B) do { @@ -644,7 +644,7 @@ void DeadCodeScan::reportDeadCode(const CFGBlock *B, Loc, SourceRange(), SourceRange(Loc, Loc), R2); return; } - + // Check if the dead block has a predecessor whose branch has // a configuration value that *could* be modified to // silence the warning. @@ -690,7 +690,7 @@ void FindUnreachableCode(AnalysisDeclContext &AC, Preprocessor &PP, scanMaybeReachableFromBlock(&cfg->getEntry(), PP, reachable); if (numReachable == cfg->getNumBlockIDs()) return; - + // If there aren't explicit EH edges, we should include the 'try' dispatch // blocks as roots. if (!AC.getCFGBuildOptions().AddEHEdges) { @@ -703,16 +703,16 @@ void FindUnreachableCode(AnalysisDeclContext &AC, Preprocessor &PP, } // There are some unreachable blocks. We need to find the root blocks that - // contain code that should be considered unreachable. + // contain code that should be considered unreachable. for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) { const CFGBlock *block = *I; // A block may have been marked reachable during this loop. if (reachable[block->getBlockID()]) continue; - + DeadCodeScan DS(reachable, PP, AC.getASTContext()); numReachable += DS.scanBackwards(block, CB); - + if (numReachable == cfg->getNumBlockIDs()) return; } diff --git a/lib/Analysis/ScanfFormatString.cpp b/lib/Analysis/ScanfFormatString.cpp index 8398a4b82d5a..a9af0cdfdacd 100644 --- a/lib/Analysis/ScanfFormatString.cpp +++ b/lib/Analysis/ScanfFormatString.cpp @@ -41,7 +41,7 @@ static bool ParseScanList(FormatStringHandler &H, H.HandleIncompleteScanList(start, I); return true; } - + // Special case: ']' is the first character. if (*I == ']') { if (++I == E) { @@ -65,7 +65,7 @@ static bool ParseScanList(FormatStringHandler &H, H.HandleIncompleteScanList(start, I - 1); return true; } - } + } CS.setEndScanList(I); return false; @@ -98,17 +98,17 @@ static ScanfSpecifierResult ParseScanfSpecifier(FormatStringHandler &H, break; } } - + // No format specifier found? if (!Start) return false; - + if (I == E) { // No more characters left? H.HandleIncompleteSpecifier(Start, E - Start); return true; } - + ScanfSpecifier FS; if (ParseArgPosition(H, FS, Start, I, E)) return true; @@ -118,7 +118,7 @@ static ScanfSpecifierResult ParseScanfSpecifier(FormatStringHandler &H, H.HandleIncompleteSpecifier(Start, E - Start); return true; } - + // Look for '*' flag if it is present. if (*I == '*') { FS.setSuppressAssignment(I); @@ -127,7 +127,7 @@ static ScanfSpecifierResult ParseScanfSpecifier(FormatStringHandler &H, return true; } } - + // Look for the field width (if any). Unlike printf, this is either // a fixed integer or isn't present. const OptionalAmount &Amt = clang::analyze_format_string::ParseAmount(I, E); @@ -141,20 +141,20 @@ static ScanfSpecifierResult ParseScanfSpecifier(FormatStringHandler &H, return true; } } - + // Look for the length modifier. if (ParseLengthModifier(FS, I, E, LO, /*scanf=*/true) && I == E) { // No more characters left? H.HandleIncompleteSpecifier(Start, E - Start); return true; } - + // Detect spurious null characters, which are likely errors. if (*I == '\0') { H.HandleNullChar(I); return true; } - + // Finally, look for the conversion specifier. const char *conversionPosition = I++; ScanfConversionSpecifier::Kind k = ScanfConversionSpecifier::InvalidSpecifier; @@ -207,7 +207,7 @@ static ScanfSpecifierResult ParseScanfSpecifier(FormatStringHandler &H, if (CS.consumesDataArgument() && !FS.getSuppressAssignment() && !FS.usesPositionalArg()) FS.setArgIndex(argIndex++); - + // FIXME: '%' and '*' doesn't make sense. Issue a warning. // FIXME: 'ConsumedSoFar' and '*' doesn't make sense. @@ -537,9 +537,9 @@ bool clang::analyze_format_string::ParseScanfString(FormatStringHandler &H, const char *E, const LangOptions &LO, const TargetInfo &Target) { - + unsigned argIndex = 0; - + // Keep looking for a format specifier until we have exhausted the string. while (I != E) { const ScanfSpecifierResult &FSR = ParseScanfSpecifier(H, I, E, argIndex, diff --git a/lib/Analysis/UninitializedValues.cpp b/lib/Analysis/UninitializedValues.cpp index 63353292349b..31c88a109565 100644 --- a/lib/Analysis/UninitializedValues.cpp +++ b/lib/Analysis/UninitializedValues.cpp @@ -62,13 +62,13 @@ class DeclToIndex { public: DeclToIndex() = default; - + /// Compute the actual mapping from declarations to bits. void computeMap(const DeclContext &dc); - + /// Return the number of declarations in the map. unsigned size() const { return map.size(); } - + /// Returns the bit vector index for a given declaration. Optional<unsigned> getValueIndex(const VarDecl *d) const; }; @@ -126,8 +126,8 @@ public: CFGBlockValues(const CFG &cfg); unsigned getNumEntries() const { return declToIndex.size(); } - - void computeSetOfDeclarations(const DeclContext &dc); + + void computeSetOfDeclarations(const DeclContext &dc); ValueVector &getValueVector(const CFGBlock *block) { return vals[block->getBlockID()]; @@ -136,13 +136,13 @@ public: void setAllScratchValues(Value V); void mergeIntoScratch(ValueVector const &source, bool isFirst); bool updateValueVectorWithScratch(const CFGBlock *block); - + bool hasNoDeclarations() const { return declToIndex.size() == 0; } void resetScratch(); - + ValueVector::reference operator[](const VarDecl *vd); Value getValue(const CFGBlock *block, const CFGBlock *dstBlock, @@ -151,7 +151,7 @@ public: assert(idx.hasValue()); return getValueVector(block)[idx.getValue()]; } -}; +}; } // namespace @@ -235,7 +235,7 @@ public: ++PO_I; } } - + void enqueueSuccessors(const CFGBlock *block); const CFGBlock *dequeue(); }; @@ -614,7 +614,7 @@ public: const CFGBlock *Pred = *I; if (!Pred) continue; - + Value AtPredExit = vals.getValue(Pred, B, vd); if (AtPredExit == Initialized) // This block initializes the variable. @@ -923,7 +923,7 @@ void clang::runUninitializedVariablesAnalysis( classification, wasAnalyzed, PBH); ++stats.NumBlockVisits; if (changed || !previouslyVisited[block->getBlockID()]) - worklist.enqueueSuccessors(block); + worklist.enqueueSuccessors(block); previouslyVisited[block->getBlockID()] = true; } diff --git a/lib/Basic/Diagnostic.cpp b/lib/Basic/Diagnostic.cpp index 519e835e32a2..f1ebd9d38b9e 100644 --- a/lib/Basic/Diagnostic.cpp +++ b/lib/Basic/Diagnostic.cpp @@ -116,12 +116,12 @@ void DiagnosticsEngine::Reset() { UncompilableErrorOccurred = false; FatalErrorOccurred = false; UnrecoverableErrorOccurred = false; - + NumWarnings = 0; NumErrors = 0; TrapNumErrorsOccurred = 0; TrapNumUnrecoverableErrorsOccurred = 0; - + CurDiagID = std::numeric_limits<unsigned>::max(); LastDiagLevel = DiagnosticIDs::Ignored; DelayedDiagID = 0; @@ -759,7 +759,7 @@ FormatDiagnostic(SmallVectorImpl<char> &OutStr) const { return; } - StringRef Diag = + StringRef Diag = getDiags()->getDiagnosticIDs()->getDescription(getID()); FormatDiagnostic(Diag.begin(), Diag.end(), OutStr); @@ -880,7 +880,7 @@ FormatDiagnostic(const char *DiagStr, const char *DiagEnd, continue; } } - + switch (Kind) { // ---- STRINGS ---- case DiagnosticsEngine::ak_std_string: { @@ -1056,7 +1056,7 @@ FormatDiagnostic(const char *DiagStr, const char *DiagEnd, break; } } - + // Remember this argument info for subsequent formatting operations. Turn // std::strings into a null terminated string to make it be the same case as // all the other ones. @@ -1077,7 +1077,7 @@ StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID, StringRef Message) : ID(ID), Level(Level), Message(Message) {} -StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, +StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, const Diagnostic &Info) : ID(Info.getID()), Level(Level) { assert((Info.getLocation().isInvalid() || Info.hasSourceManager()) && diff --git a/lib/Basic/DiagnosticIDs.cpp b/lib/Basic/DiagnosticIDs.cpp index 697de68a5afb..8f2c3d06a504 100644 --- a/lib/Basic/DiagnosticIDs.cpp +++ b/lib/Basic/DiagnosticIDs.cpp @@ -685,7 +685,7 @@ bool DiagnosticIDs::ProcessDiag(DiagnosticsEngine &Diag) const { ++Diag.NumErrors; } - // If we've emitted a lot of errors, emit a fatal error instead of it to + // If we've emitted a lot of errors, emit a fatal error instead of it to // stop a flood of bogus errors. if (Diag.ErrorLimit && Diag.NumErrors > Diag.ErrorLimit && DiagLevel == DiagnosticIDs::Error) { diff --git a/lib/Basic/FileManager.cpp b/lib/Basic/FileManager.cpp index 7e2d01c4981d..d339b972ae8e 100644 --- a/lib/Basic/FileManager.cpp +++ b/lib/Basic/FileManager.cpp @@ -71,7 +71,7 @@ void FileManager::addStatCache(std::unique_ptr<FileSystemStatCache> statCache, StatCache = std::move(statCache); return; } - + FileSystemStatCache *LastCache = StatCache.get(); while (LastCache->getNextStatCache()) LastCache = LastCache->getNextStatCache(); @@ -82,18 +82,18 @@ void FileManager::addStatCache(std::unique_ptr<FileSystemStatCache> statCache, void FileManager::removeStatCache(FileSystemStatCache *statCache) { if (!statCache) return; - + if (StatCache.get() == statCache) { // This is the first stat cache. StatCache = StatCache->takeNextStatCache(); return; } - + // Find the stat cache in the list. FileSystemStatCache *PrevCache = StatCache.get(); while (PrevCache && PrevCache->getNextStatCache() != statCache) PrevCache = PrevCache->getNextStatCache(); - + assert(PrevCache && "Stat cache not found for removal"); PrevCache->setNextStatCache(statCache->takeNextStatCache()); } @@ -247,7 +247,7 @@ const FileEntry *FileManager::getFile(StringRef Filename, bool openFile, return nullptr; } - + // FIXME: Use the directory info to prune this, before doing the stat syscall. // FIXME: This will reduce the # syscalls. @@ -394,7 +394,7 @@ FileManager::getVirtualFile(StringRef Filename, off_t Size, bool FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const { StringRef pathRef(path.data(), path.size()); - if (FileSystemOpts.WorkingDir.empty() + if (FileSystemOpts.WorkingDir.empty() || llvm::sys::path::is_absolute(pathRef)) return false; @@ -505,14 +505,14 @@ void FileManager::GetUniqueIDMapping( SmallVectorImpl<const FileEntry *> &UIDToFiles) const { UIDToFiles.clear(); UIDToFiles.resize(NextFileUID); - + // Map file entries for (llvm::StringMap<FileEntry*, llvm::BumpPtrAllocator>::const_iterator FE = SeenFileEntries.begin(), FEEnd = SeenFileEntries.end(); FE != FEEnd; ++FE) if (FE->getValue() && FE->getValue() != NON_EXISTENT_FILE) UIDToFiles[FE->getValue()->getUID()] = FE->getValue(); - + // Map virtual file entries for (const auto &VFE : VirtualFileEntries) if (VFE && VFE.get() != NON_EXISTENT_FILE) diff --git a/lib/Basic/FileSystemStatCache.cpp b/lib/Basic/FileSystemStatCache.cpp index ebee32670e0a..f5856cb6542a 100644 --- a/lib/Basic/FileSystemStatCache.cpp +++ b/lib/Basic/FileSystemStatCache.cpp @@ -95,17 +95,17 @@ bool FileSystemStatCache::get(StringRef Path, FileData &Data, bool isFile, // If the path doesn't exist, return failure. if (R == CacheMissing) return true; - + // If the path exists, make sure that its "directoryness" matches the clients // demands. if (Data.IsDirectory != isForDir) { // If not, close the file if opened. if (F) *F = nullptr; - + return true; } - + return false; } @@ -120,7 +120,7 @@ MemorizeStatCalls::getStat(StringRef Path, FileData &Data, bool isFile, // entries). if (Result == CacheMissing) return Result; - + // Cache file 'stat' results and directories with absolutely paths. if (!Data.IsDirectory || llvm::sys::path::is_absolute(Path)) StatCalls[Path] = Data; diff --git a/lib/Basic/IdentifierTable.cpp b/lib/Basic/IdentifierTable.cpp index 2fef481ae2c5..7ec3cb7dd65b 100644 --- a/lib/Basic/IdentifierTable.cpp +++ b/lib/Basic/IdentifierTable.cpp @@ -319,7 +319,7 @@ tok::PPKeywordKind IdentifierInfo::getPPKeywordID() const { CASE( 6, 'i', 'n', ifndef); CASE( 6, 'i', 'p', import); CASE( 6, 'p', 'a', pragma); - + CASE( 7, 'd', 'f', defined); CASE( 7, 'i', 'c', include); CASE( 7, 'w', 'r', warning); @@ -328,7 +328,7 @@ tok::PPKeywordKind IdentifierInfo::getPPKeywordID() const { CASE(12, 'i', 'c', include_next); CASE(14, '_', 'p', __public_macro); - + CASE(15, '_', 'p', __private_macro); CASE(16, '_', 'i', __include_macros); @@ -566,9 +566,9 @@ ObjCMethodFamily Selector::getMethodFamilyImpl(Selector sel) { ObjCInstanceTypeFamily Selector::getInstTypeMethodFamily(Selector sel) { IdentifierInfo *first = sel.getIdentifierInfoForSlot(0); if (!first) return OIT_None; - + StringRef name = first->getName(); - + if (name.empty()) return OIT_None; switch (name.front()) { case 'a': @@ -593,22 +593,22 @@ ObjCInstanceTypeFamily Selector::getInstTypeMethodFamily(Selector sel) { ObjCStringFormatFamily Selector::getStringFormatFamilyImpl(Selector sel) { IdentifierInfo *first = sel.getIdentifierInfoForSlot(0); if (!first) return SFF_None; - + StringRef name = first->getName(); - + switch (name.front()) { case 'a': if (name == "appendFormat") return SFF_NSString; break; - + case 'i': if (name == "initWithFormat") return SFF_NSString; break; - + case 'l': if (name == "localizedStringWithFormat") return SFF_NSString; break; - + case 's': if (name == "stringByAppendingFormat" || name == "stringWithFormat") return SFF_NSString; diff --git a/lib/Basic/Module.cpp b/lib/Basic/Module.cpp index 2714b98120c0..1a0c19059058 100644 --- a/lib/Basic/Module.cpp +++ b/lib/Basic/Module.cpp @@ -58,7 +58,7 @@ Module::Module(StringRef Name, SourceLocation DefinitionLoc, Module *Parent, if (Parent->ModuleMapIsPrivate) ModuleMapIsPrivate = true; IsMissingRequirement = Parent->IsMissingRequirement; - + Parent->SubModuleIndex[Name] = Parent->SubModules.size(); Parent->SubModules.push_back(this); } @@ -134,10 +134,10 @@ bool Module::isSubModuleOf(const Module *Other) const { do { if (This == Other) return true; - + This = This->Parent; } while (This); - + return false; } @@ -145,7 +145,7 @@ const Module *Module::getTopLevelModule() const { const Module *Result = this; while (Result->Parent) Result = Result->Parent; - + return Result; } @@ -181,16 +181,16 @@ static void printModuleId(raw_ostream &OS, const Container &C) { std::string Module::getFullModuleName(bool AllowStringLiterals) const { SmallVector<StringRef, 2> Names; - + // Build up the set of module names (from innermost to outermost). for (const Module *M = this; M; M = M->Parent) Names.push_back(M->Name); - + std::string Result; llvm::raw_string_ostream Out(Result); printModuleId(Out, Names.rbegin(), Names.rend(), AllowStringLiterals); - Out.flush(); + Out.flush(); return Result; } @@ -207,7 +207,7 @@ bool Module::fullModuleNameIs(ArrayRef<StringRef> nameParts) const { Module::DirectoryName Module::getUmbrellaDir() const { if (Header U = getUmbrellaHeader()) return {"", U.Entry->getDir()}; - + return {UmbrellaAsWritten, Umbrella.dyn_cast<const DirectoryEntry *>()}; } @@ -388,7 +388,7 @@ void Module::print(raw_ostream &OS, unsigned Indent) const { } OS << " {\n"; - + if (!Requirements.empty()) { OS.indent(Indent + 2); OS << "requires "; @@ -401,7 +401,7 @@ void Module::print(raw_ostream &OS, unsigned Indent) const { } OS << "\n"; } - + if (Header H = getUmbrellaHeader()) { OS.indent(Indent + 2); OS << "umbrella header \""; @@ -411,7 +411,7 @@ void Module::print(raw_ostream &OS, unsigned Indent) const { OS.indent(Indent + 2); OS << "umbrella \""; OS.write_escaped(D.NameAsWritten); - OS << "\"\n"; + OS << "\"\n"; } if (!ConfigMacros.empty() || ConfigMacrosExhaustive) { @@ -468,7 +468,7 @@ void Module::print(raw_ostream &OS, unsigned Indent) const { OS.indent(Indent + 2); OS << "export_as" << ExportAsModule << "\n"; } - + for (submodule_const_iterator MI = submodule_begin(), MIEnd = submodule_end(); MI != MIEnd; ++MI) // Print inferred subframework modules so that we don't need to re-infer @@ -477,7 +477,7 @@ void Module::print(raw_ostream &OS, unsigned Indent) const { // those header files anyway. if (!(*MI)->IsInferred || (*MI)->IsFramework) (*MI)->print(OS, Indent + 2); - + for (unsigned I = 0, N = Exports.size(); I != N; ++I) { OS.indent(Indent + 2); OS << "export "; @@ -554,7 +554,7 @@ void Module::print(raw_ostream &OS, unsigned Indent) const { OS.indent(Indent + 2); OS << "}\n"; } - + OS.indent(Indent); OS << "}\n"; } diff --git a/lib/Basic/ObjCRuntime.cpp b/lib/Basic/ObjCRuntime.cpp index 8fa0afbe03f2..311bd067261a 100644 --- a/lib/Basic/ObjCRuntime.cpp +++ b/lib/Basic/ObjCRuntime.cpp @@ -27,7 +27,7 @@ std::string ObjCRuntime::getAsString() const { llvm::raw_string_ostream Out(Result); Out << *this; } - return Result; + return Result; } raw_ostream &clang::operator<<(raw_ostream &out, const ObjCRuntime &value) { diff --git a/lib/Basic/SourceLocation.cpp b/lib/Basic/SourceLocation.cpp index fef1f44fc8a5..eb916ec76fdc 100644 --- a/lib/Basic/SourceLocation.cpp +++ b/lib/Basic/SourceLocation.cpp @@ -49,7 +49,7 @@ void SourceLocation::print(raw_ostream &OS, const SourceManager &SM)const{ if (isFileID()) { PresumedLoc PLoc = SM.getPresumedLoc(*this); - + if (PLoc.isInvalid()) { OS << "<invalid>"; return; diff --git a/lib/Basic/SourceManager.cpp b/lib/Basic/SourceManager.cpp index ae76817826e1..efa6ad2493b2 100644 --- a/lib/Basic/SourceManager.cpp +++ b/lib/Basic/SourceManager.cpp @@ -105,9 +105,9 @@ llvm::MemoryBuffer *ContentCache::getBuffer(DiagnosticsEngine &Diag, if (Buffer.getPointer() || !ContentsEntry) { if (Invalid) *Invalid = isBufferInvalid(); - + return Buffer.getPointer(); - } + } bool isVolatile = SM.userFilesAreVolatile() && !IsSystemFile; auto BufferOrError = @@ -141,7 +141,7 @@ llvm::MemoryBuffer *ContentCache::getBuffer(DiagnosticsEngine &Diag, << ContentsEntry->getName() << BufferOrError.getError().message(); Buffer.setInt(Buffer.getInt() | InvalidFlag); - + if (Invalid) *Invalid = true; return Buffer.getPointer(); } @@ -187,10 +187,10 @@ llvm::MemoryBuffer *ContentCache::getBuffer(DiagnosticsEngine &Diag, << InvalidBOM << ContentsEntry->getName(); Buffer.setInt(Buffer.getInt() | InvalidFlag); } - + if (Invalid) *Invalid = isBufferInvalid(); - + return Buffer.getPointer(); } @@ -672,7 +672,7 @@ StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const { bool MyInvalid = false; const SLocEntry &SLoc = getSLocEntry(FID, &MyInvalid); if (!SLoc.isFile() || MyInvalid) { - if (Invalid) + if (Invalid) *Invalid = true; return "<<<<<INVALID SOURCE LOCATION>>>>>"; } @@ -684,7 +684,7 @@ StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const { if (MyInvalid) return "<<<<<INVALID SOURCE LOCATION>>>>>"; - + return Buf->getBuffer(); } @@ -770,7 +770,7 @@ FileID SourceManager::getFileIDLocal(unsigned SLocOffset) const { unsigned MidOffset = getLocalSLocEntry(MiddleIndex, &Invalid).getOffset(); if (Invalid) return FileID::get(0); - + ++NumProbes; // If the offset of the midpoint is too large, chop the high side of the @@ -1104,7 +1104,7 @@ const char *SourceManager::getCharacterData(SourceLocation SL, if (CharDataInvalid || !Entry.isFile()) { if (Invalid) *Invalid = true; - + return "<<<<INVALID BUFFER>>>>"; } llvm::MemoryBuffer *Buffer = Entry.getFile().getContentCache()->getBuffer( @@ -1289,7 +1289,7 @@ FoundSpecialChar: /// for the position indicated. This requires building and caching a table of /// line offsets for the MemoryBuffer, so this is not cheap: use only when /// about to emit a diagnostic. -unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos, +unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos, bool *Invalid) const { if (FID.isInvalid()) { if (Invalid) @@ -1308,10 +1308,10 @@ unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos, *Invalid = true; return 1; } - + Content = const_cast<ContentCache*>(Entry.getFile().getContentCache()); } - + // If this is the first use of line information for this buffer, compute the /// SourceLineCache for it on demand. if (!Content->SourceLineCache) { @@ -1383,7 +1383,7 @@ unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos, return LineNo; } -unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc, +unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc, bool *Invalid) const { if (isInvalid(Loc, Invalid)) return 0; std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc); @@ -1418,7 +1418,7 @@ SourceManager::getFileCharacteristic(SourceLocation Loc) const { const SLocEntry &SEntry = getSLocEntry(LocInfo.first, &Invalid); if (Invalid || !SEntry.isFile()) return C_User; - + const SrcMgr::FileInfo &FI = SEntry.getFile(); // If there are no #line directives in this file, just return the whole-file @@ -1466,7 +1466,7 @@ PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc, const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid); if (Invalid || !Entry.isFile()) return PresumedLoc(); - + const SrcMgr::FileInfo &FI = Entry.getFile(); const SrcMgr::ContentCache *C = FI.getContentCache(); @@ -1485,7 +1485,7 @@ PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc, unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid); if (Invalid) return PresumedLoc(); - + SourceLocation IncludeLoc = FI.getIncludeLoc(); // If we have #line directives in this file, update and overwrite the physical @@ -1621,7 +1621,7 @@ FileID SourceManager::translateFile(const FileEntry *SourceFile) const { const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid); if (Invalid) return FileID(); - + if (MainSLoc.isFile()) { const ContentCache *MainContentCache = MainSLoc.getFile().getContentCache(); @@ -1658,8 +1658,8 @@ FileID SourceManager::translateFile(const FileEntry *SourceFile) const { const SLocEntry &SLoc = getLocalSLocEntry(I, &Invalid); if (Invalid) return FileID(); - - if (SLoc.isFile() && + + if (SLoc.isFile() && SLoc.getFile().getContentCache() && SLoc.getFile().getContentCache()->OrigEntry == SourceFile) { FirstFID = FileID::get(I); @@ -1670,7 +1670,7 @@ FileID SourceManager::translateFile(const FileEntry *SourceFile) const { if (FirstFID.isInvalid()) { for (unsigned I = 0, N = loaded_sloc_entry_size(); I != N; ++I) { const SLocEntry &SLoc = getLoadedSLocEntry(I); - if (SLoc.isFile() && + if (SLoc.isFile() && SLoc.getFile().getContentCache() && SLoc.getFile().getContentCache()->OrigEntry == SourceFile) { FirstFID = FileID::get(-int(I) - 2); @@ -1681,7 +1681,7 @@ FileID SourceManager::translateFile(const FileEntry *SourceFile) const { } // If we haven't found what we want yet, try again, but this time stat() - // each of the files in case the files have changed since we originally + // each of the files in case the files have changed since we originally // parsed the file. if (FirstFID.isInvalid() && (SourceFileName || @@ -1694,13 +1694,13 @@ FileID SourceManager::translateFile(const FileEntry *SourceFile) const { const SLocEntry &SLoc = getSLocEntry(IFileID, &Invalid); if (Invalid) return FileID(); - - if (SLoc.isFile()) { - const ContentCache *FileContentCache + + if (SLoc.isFile()) { + const ContentCache *FileContentCache = SLoc.getFile().getContentCache(); const FileEntry *Entry = FileContentCache ? FileContentCache->OrigEntry : nullptr; - if (Entry && + if (Entry && *SourceFileName == llvm::sys::path::filename(Entry->getName())) { if (Optional<llvm::sys::fs::UniqueID> EntryUID = getActualFileUID(Entry)) { @@ -1712,9 +1712,9 @@ FileID SourceManager::translateFile(const FileEntry *SourceFile) const { } } } - } + } } - + (void) SourceFile; return FirstFID; } @@ -1948,7 +1948,7 @@ SourceManager::getMacroArgExpandedLocation(SourceLocation Loc) const { assert(!MacroArgsCache->empty()); MacroArgsMap::iterator I = MacroArgsCache->upper_bound(Offset); --I; - + unsigned MacroArgBeginOffs = I->first; SourceLocation MacroArgExpandedLoc = I->second; if (MacroArgExpandedLoc.isValid()) @@ -2151,7 +2151,7 @@ void SourceManager::PrintStats() const { << " loaded SLocEntries allocated, " << MaxLoadedOffset - CurrentLoadedOffset << "B of Sloc address space used.\n"; - + unsigned NumLineNumsComputed = 0; unsigned NumFileBytesMapped = 0; for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){ @@ -2231,7 +2231,7 @@ ExternalSLocEntrySource::~ExternalSLocEntrySource() = default; SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const { size_t malloc_bytes = 0; size_t mmap_bytes = 0; - + for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped()) switch (MemBufferInfos[i]->getMemoryBufferKind()) { @@ -2242,7 +2242,7 @@ SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const { malloc_bytes += sized_mapped; break; } - + return MemoryBufferSizes(malloc_bytes, mmap_bytes); } @@ -2252,7 +2252,7 @@ size_t SourceManager::getDataStructureSizes() const { + llvm::capacity_in_bytes(LoadedSLocEntryTable) + llvm::capacity_in_bytes(SLocEntryLoaded) + llvm::capacity_in_bytes(FileInfos); - + if (OverriddenFilesInfo) size += llvm::capacity_in_bytes(OverriddenFilesInfo->OverriddenFiles); diff --git a/lib/Basic/Targets/ARM.cpp b/lib/Basic/Targets/ARM.cpp index efed9b096d56..19fcc5abea97 100644 --- a/lib/Basic/Targets/ARM.cpp +++ b/lib/Basic/Targets/ARM.cpp @@ -185,6 +185,10 @@ StringRef ARMTargetInfo::getCPUAttr() const { return "8_1A"; case llvm::ARM::ArchKind::ARMV8_2A: return "8_2A"; + case llvm::ARM::ArchKind::ARMV8_3A: + return "8_3A"; + case llvm::ARM::ArchKind::ARMV8_4A: + return "8_4A"; case llvm::ARM::ArchKind::ARMV8MBaseline: return "8M_BASE"; case llvm::ARM::ArchKind::ARMV8MMainline: diff --git a/lib/Basic/Targets/X86.cpp b/lib/Basic/Targets/X86.cpp index 7ae0696ce7e7..e295cff9d5d2 100644 --- a/lib/Basic/Targets/X86.cpp +++ b/lib/Basic/Targets/X86.cpp @@ -1757,7 +1757,7 @@ void X86TargetInfo::fillValidCPUList(SmallVectorImpl<StringRef> &Values) const { #define PROC(ENUM, STRING, IS64BIT) \ if (IS64BIT || getTriple().getArch() == llvm::Triple::x86) \ Values.emplace_back(STRING); - // Go through CPUKind checking to ensure that the alias is de-aliased and + // Go through CPUKind checking to ensure that the alias is de-aliased and // 64 bit-ness is checked. #define PROC_ALIAS(ENUM, ALIAS) \ if (checkCPUKind(getCPUKind(ALIAS))) \ diff --git a/lib/Basic/Targets/X86.h b/lib/Basic/Targets/X86.h index b6cb27977b69..019bc8d51a63 100644 --- a/lib/Basic/Targets/X86.h +++ b/lib/Basic/Targets/X86.h @@ -132,7 +132,7 @@ public: : TargetInfo(Triple) { LongDoubleFormat = &llvm::APFloat::x87DoubleExtended(); } - + unsigned getFloatEvalMethod() const override { // X87 evaluates with 80 bits "long double" precision. return SSELevel == NoSSE ? 2 : 0; @@ -238,7 +238,7 @@ public: void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override; - + static void setSSELevel(llvm::StringMap<bool> &Features, X86SSEEnum Level, bool Enabled); @@ -577,7 +577,7 @@ public: IntPtrType = SignedLong; PtrDiffType = SignedLong; } - + void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override { X86_32TargetInfo::getTargetDefines(Opts, Builder); @@ -664,7 +664,7 @@ public: bool hasInt128Type() const override { return true; } unsigned getUnwindWordWidth() const override { return 64; } - + unsigned getRegisterWidth() const override { return 64; } bool validateGlobalRegisterVariable(StringRef RegName, unsigned RegSize, diff --git a/lib/Basic/Warnings.cpp b/lib/Basic/Warnings.cpp index 6306ceabc638..a999c45a0c3e 100644 --- a/lib/Basic/Warnings.cpp +++ b/lib/Basic/Warnings.cpp @@ -51,7 +51,7 @@ void clang::ProcessWarningOptions(DiagnosticsEngine &Diags, Diags.setElideType(Opts.ElideType); Diags.setPrintTemplateTree(Opts.ShowTemplateTree); Diags.setShowColors(Opts.ShowColors); - + // Handle -ferror-limit if (Opts.ErrorLimit) Diags.setErrorLimit(Opts.ErrorLimit); @@ -75,7 +75,7 @@ void clang::ProcessWarningOptions(DiagnosticsEngine &Diags, Diags.getDiagnosticIDs(); // We parse the warning options twice. The first pass sets diagnostic state, // while the second pass reports warnings/errors. This has the effect that - // we follow the more canonical "last option wins" paradigm when there are + // we follow the more canonical "last option wins" paradigm when there are // conflicting options. for (unsigned Report = 0, ReportEnd = 2; Report != ReportEnd; ++Report) { bool SetDiagnostic = (Report == 0); @@ -114,7 +114,7 @@ void clang::ProcessWarningOptions(DiagnosticsEngine &Diags, Diags.setSuppressSystemWarnings(!isPositive); continue; } - + // -Weverything is a special case as well. It implicitly enables all // warnings, including ones not explicitly in a warning group. if (Opt == "everything") { @@ -128,8 +128,8 @@ void clang::ProcessWarningOptions(DiagnosticsEngine &Diags, } continue; } - - // -Werror/-Wno-error is a special case, not controlled by the option + + // -Werror/-Wno-error is a special case, not controlled by the option // table. It also has the "specifier" form of -Werror=foo and -Werror-foo. if (Opt.startswith("error")) { StringRef Specifier; @@ -142,13 +142,13 @@ void clang::ProcessWarningOptions(DiagnosticsEngine &Diags, } Specifier = Opt.substr(6); } - + if (Specifier.empty()) { if (SetDiagnostic) Diags.setWarningsAsErrors(isPositive); continue; } - + if (SetDiagnostic) { // Set the warning as error flag for this specifier. Diags.setDiagnosticGroupWarningAsError(Specifier, isPositive); @@ -157,7 +157,7 @@ void clang::ProcessWarningOptions(DiagnosticsEngine &Diags, } continue; } - + // -Wfatal-errors is yet another special case. if (Opt.startswith("fatal-errors")) { StringRef Specifier; @@ -176,7 +176,7 @@ void clang::ProcessWarningOptions(DiagnosticsEngine &Diags, Diags.setErrorsAsFatal(isPositive); continue; } - + if (SetDiagnostic) { // Set the error as fatal flag for this specifier. Diags.setDiagnosticGroupErrorAsFatal(Specifier, isPositive); @@ -185,7 +185,7 @@ void clang::ProcessWarningOptions(DiagnosticsEngine &Diags, } continue; } - + if (Report) { if (DiagIDs->getDiagnosticsInGroup(Flavor, Opt, _Diags)) EmitUnknownDiagWarning(Diags, Flavor, isPositive ? "-W" : "-Wno-", diff --git a/lib/CodeGen/CGBlocks.cpp b/lib/CodeGen/CGBlocks.cpp index 617856a7b43e..8269b5b229a2 100644 --- a/lib/CodeGen/CGBlocks.cpp +++ b/lib/CodeGen/CGBlocks.cpp @@ -85,7 +85,7 @@ static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM, cast<llvm::IntegerType>(CGM.getTypes().ConvertType(C.UnsignedLongTy)); llvm::PointerType *i8p = nullptr; if (CGM.getLangOpts().OpenCL) - i8p = + i8p = llvm::Type::getInt8PtrTy( CGM.getLLVMContext(), C.getTargetAddressSpace(LangAS::opencl_constant)); else @@ -117,7 +117,7 @@ static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM, CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr()); elements.add(llvm::ConstantExpr::getBitCast( CGM.GetAddrOfConstantCString(typeAtEncoding).getPointer(), i8p)); - + // GC layout. if (C.getLangOpts().ObjC1) { if (CGM.getLangOpts().getGC() != LangOptions::NonGC) @@ -381,7 +381,7 @@ static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF, else if (C.getLangOpts().ObjC1 && CGM.getLangOpts().getGC() == LangOptions::NonGC) info.HasCapturedVariableLayout = true; - + // Collect the layout chunks. SmallVector<BlockLayoutChunk, 16> layout; layout.reserve(block->capturesCXXThis() + @@ -487,12 +487,12 @@ static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF, QualType VT = getCaptureFieldType(*CGF, CI); CharUnits size = C.getTypeSizeInChars(VT); CharUnits align = C.getDeclAlign(variable); - + maxFieldAlign = std::max(maxFieldAlign, align); llvm::Type *llvmType = CGM.getTypes().ConvertTypeForMem(VT); - + layout.push_back( BlockLayoutChunk(align, size, lifetime, &CI, llvmType, VT)); } @@ -509,11 +509,11 @@ static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF, // to get reproducible results. There should probably be an // llvm::array_pod_stable_sort. std::stable_sort(layout.begin(), layout.end()); - + // Needed for blocks layout info. info.BlockHeaderForcedGapOffset = info.BlockSize; info.BlockHeaderForcedGapSize = CharUnits::Zero(); - + CharUnits &blockSize = info.BlockSize; info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign); @@ -564,7 +564,7 @@ static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF, } assert(endAlign == getLowBit(blockSize)); - + // At this point, we just have to add padding if the end align still // isn't aligned right. if (endAlign < maxFieldAlign) { @@ -685,7 +685,7 @@ static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) { CleanupKind cleanupKind = InactiveNormalCleanup; bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind); - if (useArrayEHCleanup) + if (useArrayEHCleanup) cleanupKind = InactiveNormalAndEHCleanup; CGF.pushDestroy(cleanupKind, addr, VT, @@ -1315,7 +1315,7 @@ CodeGenFunction::GenerateBlockFunction(GlobalDecl GD, CurGD = GD; CurEHLocation = blockInfo.getBlockExpr()->getLocEnd(); - + BlockInfo = &blockInfo; // Arrange for local static and local extern declarations to appear @@ -1977,7 +1977,7 @@ public: // variable. llvm::Value *value = CGF.Builder.CreateLoad(srcField); - + llvm::Value *null = llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType())); @@ -2149,7 +2149,7 @@ generateByrefCopyHelper(CodeGenFunction &CGF, const BlockByrefInfo &byrefInfo, "src-object"); generator.emitCopy(CGF, destField, srcField); - } + } CGF.FinishFunction(); @@ -2321,7 +2321,7 @@ CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType, BlockFieldFlags flags; if (type->isBlockPointerType()) { flags |= BLOCK_FIELD_IS_BLOCK; - } else if (CGM.getContext().isObjCNSObjectType(type) || + } else if (CGM.getContext().isObjCNSObjectType(type) || type->isObjCObjectPointerType()) { flags |= BLOCK_FIELD_IS_OBJECT; } else { @@ -2380,24 +2380,24 @@ const BlockByrefInfo &CodeGenFunction::getBlockByrefInfo(const VarDecl *D) { llvm::StructType *byrefType = llvm::StructType::create(getLLVMContext(), "struct.__block_byref_" + D->getNameAsString()); - + QualType Ty = D->getType(); CharUnits size; SmallVector<llvm::Type *, 8> types; - + // void *__isa; types.push_back(Int8PtrTy); size += getPointerSize(); - + // void *__forwarding; types.push_back(llvm::PointerType::getUnqual(byrefType)); size += getPointerSize(); - + // int32_t __flags; types.push_back(Int32Ty); size += CharUnits::fromQuantity(4); - + // int32_t __size; types.push_back(Int32Ty); size += CharUnits::fromQuantity(4); @@ -2408,7 +2408,7 @@ const BlockByrefInfo &CodeGenFunction::getBlockByrefInfo(const VarDecl *D) { /// void *__copy_helper; types.push_back(Int8PtrTy); size += getPointerSize(); - + /// void *__destroy_helper; types.push_back(Int8PtrTy); size += getPointerSize(); diff --git a/lib/CodeGen/CGBlocks.h b/lib/CodeGen/CGBlocks.h index 5a8e960ffcc1..5abf82b3f6e1 100644 --- a/lib/CodeGen/CGBlocks.h +++ b/lib/CodeGen/CGBlocks.h @@ -70,7 +70,7 @@ public: BlockFlags() : flags(0) {} BlockFlags(BlockLiteralFlags flag) : flags(flag) {} BlockFlags(BlockByrefFlags flag) : flags(flag) {} - + uint32_t getBitMask() const { return flags; } bool empty() const { return flags == 0; } @@ -208,7 +208,7 @@ public: Capture v; v.Data = reinterpret_cast<uintptr_t>(value); return v; - } + } }; /// CanBeGlobal - True if the block can be global, i.e. it has @@ -226,13 +226,13 @@ public: /// UsesStret : True if the block uses an stret return. Mutable /// because it gets set later in the block-creation process. mutable bool UsesStret : 1; - + /// HasCapturedVariableLayout : True if block has captured variables /// and their layout meta-data has been generated. bool HasCapturedVariableLayout : 1; /// The mapping of allocated indexes within the block. - llvm::DenseMap<const VarDecl*, Capture> Captures; + llvm::DenseMap<const VarDecl*, Capture> Captures; Address LocalAddress; llvm::StructType *StructureType; @@ -241,7 +241,7 @@ public: CharUnits BlockSize; CharUnits BlockAlign; CharUnits CXXThisOffset; - + // Offset of the gap caused by block header having a smaller // alignment than the alignment of the block descriptor. This // is the gap offset before the first capturued field. diff --git a/lib/CodeGen/CGBuilder.h b/lib/CodeGen/CGBuilder.h index d2e5eb256d3b..654ef72060b7 100644 --- a/lib/CodeGen/CGBuilder.h +++ b/lib/CodeGen/CGBuilder.h @@ -116,7 +116,7 @@ public: CharUnits Align, bool IsVolatile = false) { return CreateAlignedStore(Val, Addr, Align.getQuantity(), IsVolatile); } - + // FIXME: these "default-aligned" APIs should be removed, // but I don't feel like fixing all the builtin code right now. llvm::StoreInst *CreateDefaultAlignedStore(llvm::Value *Val, diff --git a/lib/CodeGen/CGBuiltin.cpp b/lib/CodeGen/CGBuiltin.cpp index 0892e84a044c..e99121c46d9b 100644 --- a/lib/CodeGen/CGBuiltin.cpp +++ b/lib/CodeGen/CGBuiltin.cpp @@ -8848,7 +8848,7 @@ static Value *EmitX86Ternlog(CodeGenFunction &CGF, bool ZeroMask, return EmitX86Select(CGF, Ops[4], Ternlog, PassThru); } -static Value *EmitX86SExtMask(CodeGenFunction &CGF, Value *Op, +static Value *EmitX86SExtMask(CodeGenFunction &CGF, Value *Op, llvm::Type *DstTy) { unsigned NumberOfElements = DstTy->getVectorNumElements(); Value *Mask = getMaskVecValue(CGF, Op, NumberOfElements); @@ -9970,7 +9970,7 @@ Value *CodeGenFunction::EmitX86BuiltinExpr(unsigned BuiltinID, Value *A = Builder.CreateExtractElement(Ops[0], (uint64_t)0); Function *F = CGM.getIntrinsic(Intrinsic::sqrt, A->getType()); A = Builder.CreateCall(F, {A}); - return Builder.CreateInsertElement(Ops[0], A, (uint64_t)0); + return Builder.CreateInsertElement(Ops[0], A, (uint64_t)0); } case X86::BI__builtin_ia32_sqrtsd_round_mask: case X86::BI__builtin_ia32_sqrtss_round_mask: { @@ -10282,7 +10282,7 @@ Value *CodeGenFunction::EmitX86BuiltinExpr(unsigned BuiltinID, return EmitX86MaskedCompareResult(*this, Cmp, NumElts, Ops[3]); } default: - return getVectorFCmpIR(Pred); + return getVectorFCmpIR(Pred); } } diff --git a/lib/CodeGen/CGCXX.cpp b/lib/CodeGen/CGCXX.cpp index 475f17b77d92..d5945be43458 100644 --- a/lib/CodeGen/CGCXX.cpp +++ b/lib/CodeGen/CGCXX.cpp @@ -284,12 +284,12 @@ static CGCallee BuildAppleKextVirtualCall(CodeGenFunction &CGF, /// indirect call to virtual functions. It makes the call through indexing /// into the vtable. CGCallee -CodeGenFunction::BuildAppleKextVirtualCall(const CXXMethodDecl *MD, +CodeGenFunction::BuildAppleKextVirtualCall(const CXXMethodDecl *MD, NestedNameSpecifier *Qual, llvm::Type *Ty) { assert((Qual->getKind() == NestedNameSpecifier::TypeSpec) && "BuildAppleKextVirtualCall - bad Qual kind"); - + const Type *QTy = Qual->getAsType(); QualType T = QualType(QTy, 0); const RecordType *RT = T->getAs<RecordType>(); diff --git a/lib/CodeGen/CGCXXABI.cpp b/lib/CodeGen/CGCXXABI.cpp index 0611749acf17..3b1b47cdfe07 100644 --- a/lib/CodeGen/CGCXXABI.cpp +++ b/lib/CodeGen/CGCXXABI.cpp @@ -51,9 +51,9 @@ CGCallee CGCXXABI::EmitLoadOfMemberFunctionPointer( ErrorUnsupportedABI(CGF, "calls through member pointers"); ThisPtrForCall = This.getPointer(); - const FunctionProtoType *FPT = + const FunctionProtoType *FPT = MPT->getPointeeType()->getAs<FunctionProtoType>(); - const CXXRecordDecl *RD = + const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl()); llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType( CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr)); diff --git a/lib/CodeGen/CGCall.cpp b/lib/CodeGen/CGCall.cpp index f066ce168588..fa51dc30c58b 100644 --- a/lib/CodeGen/CGCall.cpp +++ b/lib/CodeGen/CGCall.cpp @@ -789,7 +789,7 @@ CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType, bool erased = FunctionsBeingProcessed.erase(FI); (void)erased; assert(erased && "Not in set?"); - + return *FI; } @@ -1344,7 +1344,7 @@ static void CreateCoercedStore(llvm::Value *Src, } static Address emitAddressAtOffset(CodeGenFunction &CGF, Address addr, - const ABIArgInfo &info) { + const ABIArgInfo &info) { if (unsigned offset = info.getDirectOffset()) { addr = CGF.Builder.CreateElementBitCast(addr, CGF.Int8Ty); addr = CGF.Builder.CreateConstInBoundsByteGEP(addr, @@ -1675,7 +1675,7 @@ llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) { if (!isFuncTypeConvertible(FPT)) return llvm::StructType::get(getLLVMContext()); - + const CGFunctionInfo *Info; if (isa<CXXDestructorDecl>(MD)) Info = @@ -2683,7 +2683,7 @@ static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF, llvm::Value *retainedValue = retainCall->getArgOperand(0); llvm::LoadInst *load = dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts()); - if (!load || load->isAtomic() || load->isVolatile() || + if (!load || load->isAtomic() || load->isVolatile() || load->getPointerOperand() != CGF.GetAddrOfLocalVar(self).getPointer()) return nullptr; @@ -3139,7 +3139,7 @@ static void emitWriteback(CodeGenFunction &CGF, // Cast it back, in case we're writing an id to a Foo* or something. value = CGF.Builder.CreateBitCast(value, srcAddr.getElementType(), "icr.writeback-cast"); - + // Perform the writeback. // If we have a "to use" value, it's something we need to emit a use @@ -3245,7 +3245,7 @@ static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args, // isn't null, so we need to register a dominating point so that the cleanups // system will make valid IR. CodeGenFunction::ConditionalEvaluation condEval(CGF); - + // Zero-initialize it if we're not doing a copy-initialization. bool shouldCopy = CRE->shouldCopy(); if (!shouldCopy) { @@ -3269,7 +3269,7 @@ static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args, llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull"); - finalArgument = CGF.Builder.CreateSelect(isNull, + finalArgument = CGF.Builder.CreateSelect(isNull, llvm::ConstantPointerNull::get(destType), temp.getPointer(), "icr.argument"); @@ -3309,7 +3309,7 @@ static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args, valueToUse = src; } } - + // Finish the control flow if we needed it. if (shouldCopy && !provablyNonNull) { llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock(); @@ -3360,7 +3360,7 @@ void CodeGenFunction::EmitNonNullArgCheck(RValue RV, QualType ArgType, auto PVD = ParmNum < AC.getNumParams() ? AC.getParamDecl(ParmNum) : nullptr; unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum; - // Prefer the nonnull attribute if it's present. + // Prefer the nonnull attribute if it's present. const NonNullAttr *NNAttr = nullptr; if (SanOpts.has(SanitizerKind::NonnullAttribute)) NNAttr = getNonNullAttr(AC.getDecl(), PVD, ArgType, ArgNo); @@ -3713,7 +3713,7 @@ void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee, getBundlesForFunclet(callee); if (getInvokeDest()) { - llvm::InvokeInst *invoke = + llvm::InvokeInst *invoke = Builder.CreateInvoke(callee, getUnreachableBlock(), getInvokeDest(), diff --git a/lib/CodeGen/CGCall.h b/lib/CodeGen/CGCall.h index 8adbe76fa6c3..99a36e4e12f1 100644 --- a/lib/CodeGen/CGCall.h +++ b/lib/CodeGen/CGCall.h @@ -356,7 +356,7 @@ public: class FunctionArgList : public SmallVector<const VarDecl*, 16> { }; - /// ReturnValueSlot - Contains the address where the return value of a + /// ReturnValueSlot - Contains the address where the return value of a /// function can be stored, and whether the address is volatile or not. class ReturnValueSlot { llvm::PointerIntPair<llvm::Value *, 2, unsigned int> Value; @@ -381,7 +381,7 @@ public: Address getValue() const { return Address(Value.getPointer(), Alignment); } bool isUnused() const { return Value.getInt() & IS_UNUSED; } }; - + } // end namespace CodeGen } // end namespace clang diff --git a/lib/CodeGen/CGClass.cpp b/lib/CodeGen/CGClass.cpp index 0b9311f7771c..ec4eb000a3b9 100644 --- a/lib/CodeGen/CGClass.cpp +++ b/lib/CodeGen/CGClass.cpp @@ -655,7 +655,7 @@ static void EmitMemberInitializer(CodeGenFunction &CGF, // the constructor. QualType::DestructionKind dtorKind = FieldType.isDestructedType(); if (CGF.needsEHCleanup(dtorKind)) - CGF.pushEHDestroy(dtorKind, LHS.getAddress(), FieldType); + CGF.pushEHDestroy(dtorKind, LHS.getAddress(), FieldType); return; } } @@ -685,7 +685,10 @@ void CodeGenFunction::EmitInitializerForField(FieldDecl *Field, LValue LHS, AggValueSlot::IsDestructed, AggValueSlot::DoesNotNeedGCBarriers, AggValueSlot::IsNotAliased, - overlapForFieldInit(Field)); + overlapForFieldInit(Field), + AggValueSlot::IsNotZeroed, + // Checks are made by the code that calls constructor. + AggValueSlot::IsSanitizerChecked); EmitAggExpr(Init, Slot); break; } @@ -887,7 +890,7 @@ namespace { SanitizerSet OldSanOpts; }; } // end anonymous namespace - + namespace { class FieldMemcpyizer { public: @@ -1869,12 +1872,14 @@ void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD, /// zero-initialized before it is constructed void CodeGenFunction::EmitCXXAggrConstructorCall( const CXXConstructorDecl *ctor, const ArrayType *arrayType, - Address arrayBegin, const CXXConstructExpr *E, bool zeroInitialize) { + Address arrayBegin, const CXXConstructExpr *E, bool NewPointerIsChecked, + bool zeroInitialize) { QualType elementType; llvm::Value *numElements = emitArrayLength(arrayType, elementType, arrayBegin); - EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin, E, zeroInitialize); + EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin, E, + NewPointerIsChecked, zeroInitialize); } /// EmitCXXAggrConstructorCall - Emit a loop to call a particular @@ -1890,6 +1895,7 @@ void CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor, llvm::Value *numElements, Address arrayBase, const CXXConstructExpr *E, + bool NewPointerIsChecked, bool zeroInitialize) { // It's legal for numElements to be zero. This can happen both // dynamically, because x can be zero in 'new A[x]', and statically, @@ -1931,7 +1937,7 @@ void CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor, // The alignment of the base, adjusted by the size of a single element, // provides a conservative estimate of the alignment of every element. // (This assumes we never start tracking offsetted alignments.) - // + // // Note that these are complete objects and so we don't need to // use the non-virtual size or alignment. QualType type = getContext().getTypeDeclType(ctor->getParent()); @@ -1966,7 +1972,7 @@ void CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor, EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/false, /*Delegating=*/false, curAddr, E, - AggValueSlot::DoesNotOverlap); + AggValueSlot::DoesNotOverlap, NewPointerIsChecked); } // Go to the next element. @@ -2002,7 +2008,8 @@ void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D, bool ForVirtualBase, bool Delegating, Address This, const CXXConstructExpr *E, - AggValueSlot::Overlap_t Overlap) { + AggValueSlot::Overlap_t Overlap, + bool NewPointerIsChecked) { CallArgList Args; // Push the this ptr. @@ -2031,7 +2038,7 @@ void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D, /*ParamsToSkip*/ 0, Order); EmitCXXConstructorCall(D, Type, ForVirtualBase, Delegating, This, Args, - Overlap, E->getExprLoc()); + Overlap, E->getExprLoc(), NewPointerIsChecked); } static bool canEmitDelegateCallArgs(CodeGenFunction &CGF, @@ -2065,14 +2072,13 @@ void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D, Address This, CallArgList &Args, AggValueSlot::Overlap_t Overlap, - SourceLocation Loc) { + SourceLocation Loc, + bool NewPointerIsChecked) { const CXXRecordDecl *ClassDecl = D->getParent(); - // C++11 [class.mfct.non-static]p2: - // If a non-static member function of a class X is called for an object that - // is not of type X, or of a type derived from X, the behavior is undefined. - EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall, Loc, - This.getPointer(), getContext().getRecordType(ClassDecl)); + if (!NewPointerIsChecked) + EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall, Loc, This.getPointer(), + getContext().getRecordType(ClassDecl), CharUnits::Zero()); if (D->isTrivial() && D->isDefaultConstructor()) { assert(Args.size() == 1 && "trivial default ctor with args"); @@ -2181,7 +2187,7 @@ void CodeGenFunction::EmitInheritedCXXConstructorCall( EmitCXXConstructorCall(D, Ctor_Base, ForVirtualBase, /*Delegating*/false, This, Args, AggValueSlot::MayOverlap, - E->getLocation()); + E->getLocation(), /*NewPointerIsChecked*/true); } void CodeGenFunction::EmitInlinedInheritingCXXConstructorCall( @@ -2277,8 +2283,10 @@ CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D, EmitCallArgs(Args, FPT, drop_begin(E->arguments(), 1), E->getConstructor(), /*ParamsToSkip*/ 1); - EmitCXXConstructorCall(D, Ctor_Complete, false, false, This, Args, - AggValueSlot::MayOverlap, E->getExprLoc()); + EmitCXXConstructorCall(D, Ctor_Complete, /*ForVirtualBase*/false, + /*Delegating*/false, This, Args, + AggValueSlot::MayOverlap, E->getExprLoc(), + /*NewPointerIsChecked*/false); } void @@ -2314,7 +2322,8 @@ CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor, EmitCXXConstructorCall(Ctor, CtorType, /*ForVirtualBase=*/false, /*Delegating=*/true, This, DelegateArgs, - AggValueSlot::MayOverlap, Loc); + AggValueSlot::MayOverlap, Loc, + /*NewPointerIsChecked=*/true); } namespace { @@ -2346,7 +2355,10 @@ CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor AggValueSlot::IsDestructed, AggValueSlot::DoesNotNeedGCBarriers, AggValueSlot::IsNotAliased, - AggValueSlot::MayOverlap); + AggValueSlot::MayOverlap, + AggValueSlot::IsNotZeroed, + // Checks are made by the code that calls constructor. + AggValueSlot::IsSanitizerChecked); EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot); diff --git a/lib/CodeGen/CGCleanup.cpp b/lib/CodeGen/CGCleanup.cpp index cfd230997ed0..0a766d176200 100644 --- a/lib/CodeGen/CGCleanup.cpp +++ b/lib/CodeGen/CGCleanup.cpp @@ -319,7 +319,7 @@ static llvm::LoadInst *createLoadInstBefore(Address addr, const Twine &name, auto load = new llvm::LoadInst(addr.getPointer(), name, beforeInst); load->setAlignment(addr.getAlignment().getQuantity()); return load; -} +} /// All the branch fixups on the EH stack have propagated out past the /// outermost normal cleanup; resolve them all by adding cases to the @@ -621,7 +621,7 @@ static void destroyOptimisticNormalEntry(CodeGenFunction &CGF, ++i; use.set(unreachableBB); - + // The only uses should be fixup switches. llvm::SwitchInst *si = cast<llvm::SwitchInst>(use.getUser()); if (si->getNumCases() == 1 && si->getDefaultDest() == unreachableBB) { @@ -640,7 +640,7 @@ static void destroyOptimisticNormalEntry(CodeGenFunction &CGF, condition->eraseFromParent(); } } - + assert(entry->use_empty()); delete entry; } @@ -659,7 +659,7 @@ void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) { Address NormalActiveFlag = Scope.shouldTestFlagInNormalCleanup() ? Scope.getActiveFlag() : Address::invalid(); - Address EHActiveFlag = + Address EHActiveFlag = Scope.shouldTestFlagInEHCleanup() ? Scope.getActiveFlag() : Address::invalid(); @@ -708,7 +708,7 @@ void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) { // cleanup, rewrite it so that it leads to the appropriate place. if (Scope.isNormalCleanup() && HasPrebranchedFallthrough && !IsActive) { llvm::BasicBlock *prebranchDest; - + // If the prebranch is semantically branching through the next // cleanup, just forward it to the next block, leaving the // insertion point in the prebranched block. @@ -922,7 +922,7 @@ void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) { } // V. Set up the fallthrough edge out. - + // Case 1: a fallthrough source exists but doesn't branch to the // cleanup because the cleanup is inactive. if (!HasFallthrough && FallthroughSource) { @@ -1025,11 +1025,11 @@ void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) { bool CodeGenFunction::isObviouslyBranchWithoutCleanups(JumpDest Dest) const { assert(Dest.getScopeDepth().encloses(EHStack.stable_begin()) && "stale jump destination"); - + // Calculate the innermost active normal cleanup. EHScopeStack::stable_iterator TopCleanup = EHStack.getInnermostActiveNormalCleanup(); - + // If we're not in an active normal cleanup scope, or if the // destination scope is within the innermost active normal cleanup // scope, we don't need to worry about fixups. @@ -1119,7 +1119,7 @@ void CodeGenFunction::EmitBranchThroughCleanup(JumpDest Dest) { break; } } - + Builder.ClearInsertionPoint(); } diff --git a/lib/CodeGen/CGCleanup.h b/lib/CodeGen/CGCleanup.h index 93be3e6c1502..15d6f46dcb56 100644 --- a/lib/CodeGen/CGCleanup.h +++ b/lib/CodeGen/CGCleanup.h @@ -509,7 +509,7 @@ class EHScopeStack::iterator { public: iterator() : Ptr(nullptr) {} - EHScope *get() const { + EHScope *get() const { return reinterpret_cast<EHScope*>(Ptr); } diff --git a/lib/CodeGen/CGDebugInfo.cpp b/lib/CodeGen/CGDebugInfo.cpp index 097a1e043047..5be6fb3e4245 100644 --- a/lib/CodeGen/CGDebugInfo.cpp +++ b/lib/CodeGen/CGDebugInfo.cpp @@ -971,22 +971,27 @@ llvm::DIType *CGDebugInfo::CreateType(const BlockPointerType *Ty, auto *DescTy = DBuilder.createPointerType(EltTy, Size); FieldOffset = 0; - FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); - EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset)); - FType = CGM.getContext().IntTy; - EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset)); - EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset)); - FType = CGM.getContext().getPointerType(Ty->getPointeeType()); - EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset)); - - FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); - FieldSize = CGM.getContext().getTypeSize(Ty); - FieldAlign = CGM.getContext().getTypeAlign(Ty); - EltTys.push_back(DBuilder.createMemberType( - Unit, "__descriptor", nullptr, LineNo, FieldSize, FieldAlign, FieldOffset, - llvm::DINode::FlagZero, DescTy)); + if (CGM.getLangOpts().OpenCL) { + FType = CGM.getContext().IntTy; + EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset)); + EltTys.push_back(CreateMemberType(Unit, FType, "__align", &FieldOffset)); + } else { + FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); + EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset)); + FType = CGM.getContext().IntTy; + EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset)); + EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset)); + FType = CGM.getContext().getPointerType(Ty->getPointeeType()); + EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset)); + FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); + FieldSize = CGM.getContext().getTypeSize(Ty); + FieldAlign = CGM.getContext().getTypeAlign(Ty); + EltTys.push_back(DBuilder.createMemberType( + Unit, "__descriptor", nullptr, LineNo, FieldSize, FieldAlign, FieldOffset, + llvm::DINode::FlagZero, DescTy)); + FieldOffset += FieldSize; + } - FieldOffset += FieldSize; Elements = DBuilder.getOrCreateArray(EltTys); // The __block_literal_generic structs are marked with a special @@ -3847,26 +3852,35 @@ void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block, CGM.getDataLayout().getStructLayout(block.StructureType); SmallVector<llvm::Metadata *, 16> fields; - fields.push_back(createFieldType("__isa", C.VoidPtrTy, loc, AS_public, - blockLayout->getElementOffsetInBits(0), - tunit, tunit)); - fields.push_back(createFieldType("__flags", C.IntTy, loc, AS_public, - blockLayout->getElementOffsetInBits(1), - tunit, tunit)); - fields.push_back(createFieldType("__reserved", C.IntTy, loc, AS_public, - blockLayout->getElementOffsetInBits(2), - tunit, tunit)); - auto *FnTy = block.getBlockExpr()->getFunctionType(); - auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar()); - fields.push_back(createFieldType("__FuncPtr", FnPtrType, loc, AS_public, - blockLayout->getElementOffsetInBits(3), - tunit, tunit)); - fields.push_back(createFieldType( - "__descriptor", - C.getPointerType(block.NeedsCopyDispose - ? C.getBlockDescriptorExtendedType() - : C.getBlockDescriptorType()), - loc, AS_public, blockLayout->getElementOffsetInBits(4), tunit, tunit)); + if (CGM.getLangOpts().OpenCL) { + fields.push_back(createFieldType("__size", C.IntTy, loc, AS_public, + blockLayout->getElementOffsetInBits(0), + tunit, tunit)); + fields.push_back(createFieldType("__align", C.IntTy, loc, AS_public, + blockLayout->getElementOffsetInBits(1), + tunit, tunit)); + } else { + fields.push_back(createFieldType("__isa", C.VoidPtrTy, loc, AS_public, + blockLayout->getElementOffsetInBits(0), + tunit, tunit)); + fields.push_back(createFieldType("__flags", C.IntTy, loc, AS_public, + blockLayout->getElementOffsetInBits(1), + tunit, tunit)); + fields.push_back(createFieldType("__reserved", C.IntTy, loc, AS_public, + blockLayout->getElementOffsetInBits(2), + tunit, tunit)); + auto *FnTy = block.getBlockExpr()->getFunctionType(); + auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar()); + fields.push_back(createFieldType("__FuncPtr", FnPtrType, loc, AS_public, + blockLayout->getElementOffsetInBits(3), + tunit, tunit)); + fields.push_back(createFieldType( + "__descriptor", + C.getPointerType(block.NeedsCopyDispose + ? C.getBlockDescriptorExtendedType() + : C.getBlockDescriptorType()), + loc, AS_public, blockLayout->getElementOffsetInBits(4), tunit, tunit)); + } // We want to sort the captures by offset, not because DWARF // requires this, but because we're paranoid about debuggers. diff --git a/lib/CodeGen/CGDeclCXX.cpp b/lib/CodeGen/CGDeclCXX.cpp index 5e237d7e0b69..510863f68eff 100644 --- a/lib/CodeGen/CGDeclCXX.cpp +++ b/lib/CodeGen/CGDeclCXX.cpp @@ -27,9 +27,9 @@ using namespace CodeGen; static void EmitDeclInit(CodeGenFunction &CGF, const VarDecl &D, ConstantAddress DeclPtr) { assert(D.hasGlobalStorage() && "VarDecl must have global storage!"); - assert(!D.getType()->isReferenceType() && + assert(!D.getType()->isReferenceType() && "Should not call EmitDeclInit on a reference!"); - + QualType type = D.getType(); LValue lv = CGF.MakeAddrLValue(DeclPtr, type); @@ -67,7 +67,7 @@ static void EmitDeclDestroy(CodeGenFunction &CGF, const VarDecl &D, CodeGenModule &CGM = CGF.CGM; // FIXME: __attribute__((cleanup)) ? - + QualType type = D.getType(); QualType::DestructionKind dtorKind = type.isDestructedType(); @@ -219,7 +219,7 @@ llvm::Constant *CodeGenFunction::createAtExitStub(const VarDecl &VD, CGF.StartFunction(&VD, CGM.getContext().VoidTy, fn, FI, FunctionArgList()); llvm::CallInst *call = CGF.Builder.CreateCall(dtor, addr); - + // Make sure the call and the callee agree on calling convention. if (llvm::Function *dtorFn = dyn_cast<llvm::Function>(dtor->stripPointerCasts())) @@ -488,7 +488,7 @@ CodeGenModule::EmitCXXGlobalInitFunc() { // Create our global initialization function. if (!PrioritizedCXXGlobalInits.empty()) { SmallVector<llvm::Function *, 8> LocalCXXGlobalInits; - llvm::array_pod_sort(PrioritizedCXXGlobalInits.begin(), + llvm::array_pod_sort(PrioritizedCXXGlobalInits.begin(), PrioritizedCXXGlobalInits.end()); // Iterate over "chunks" of ctors with same priority and emit each chunk // into separate function. Note - everything is sorted first by priority, @@ -684,8 +684,8 @@ llvm::Function *CodeGenFunction::generateDestroyHelper( StartFunction(VD, getContext().VoidTy, fn, FI, args); emitDestroy(addr, type, destroyer, useEHCleanupForArray); - + FinishFunction(); - + return fn; } diff --git a/lib/CodeGen/CGException.cpp b/lib/CodeGen/CGException.cpp index c9820c242554..a2ff102e1ab4 100644 --- a/lib/CodeGen/CGException.cpp +++ b/lib/CodeGen/CGException.cpp @@ -335,7 +335,7 @@ void CodeGenModule::SimplifyPersonality() { // Nothing to do if it's unused. if (!Fn || Fn->use_empty()) return; - + // Can't do the optimization if it has non-C++ uses. if (!PersonalityHasOnlyCXXUses(Fn)) return; @@ -443,7 +443,7 @@ void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E, void CodeGenFunction::EmitStartEHSpec(const Decl *D) { if (!CGM.getLangOpts().CXXExceptions) return; - + const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D); if (!FD) { // Check if CapturedDecl is nothrow and create terminate scope for it. @@ -520,7 +520,7 @@ static void emitFilterDispatchBlock(CodeGenFunction &CGF, void CodeGenFunction::EmitEndEHSpec(const Decl *D) { if (!CGM.getLangOpts().CXXExceptions) return; - + const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D); if (!FD) { // Check if CapturedDecl is nothrow and pop terminate scope for it. @@ -1345,7 +1345,7 @@ namespace { CGF.PopCleanupBlock(); CGF.Builder.restoreIP(SavedIP); } - + // Now make sure we actually have an insertion point or the // cleanup gods will hate us. CGF.EnsureInsertPoint(); diff --git a/lib/CodeGen/CGExpr.cpp b/lib/CodeGen/CGExpr.cpp index 3097caacb31c..f168dd02ead1 100644 --- a/lib/CodeGen/CGExpr.cpp +++ b/lib/CodeGen/CGExpr.cpp @@ -1820,14 +1820,14 @@ Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) { const VectorType *ExprVT = LV.getType()->getAs<VectorType>(); QualType EQT = ExprVT->getElementType(); llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT); - + Address CastToPointerElement = Builder.CreateElementBitCast(VectorAddress, VectorElementTy, "conv.ptr.element"); - + const llvm::Constant *Elts = LV.getExtVectorElts(); unsigned ix = getAccessedFieldNo(0, Elts); - + Address VectorBasePtrPlusIx = Builder.CreateConstInBoundsGEP(CastToPointerElement, ix, getContext().getTypeSizeInChars(EQT), @@ -3282,7 +3282,7 @@ static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr, for (auto idx : indices.drop_back()) assert(isa<llvm::ConstantInt>(idx) && cast<llvm::ConstantInt>(idx)->isZero()); -#endif +#endif // Determine the element size of the statically-sized base. This is // the thing that the indices are expressed in terms of. @@ -3764,7 +3764,7 @@ LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) { static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base, const FieldDecl *field) { const RecordDecl *rec = field->getParent(); - + unsigned idx = CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field); diff --git a/lib/CodeGen/CGExprAgg.cpp b/lib/CodeGen/CGExprAgg.cpp index 291740478329..62641102861c 100644 --- a/lib/CodeGen/CGExprAgg.cpp +++ b/lib/CodeGen/CGExprAgg.cpp @@ -650,7 +650,7 @@ AggExprEmitter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { EmitAggLoadOfLValue(E); return; } - + AggValueSlot Slot = EnsureSlot(E->getType()); CGF.EmitAggExpr(E->getInitializer(), Slot); } @@ -766,7 +766,7 @@ void AggExprEmitter::VisitCastExpr(CastExpr *E) { AggValueSlot::DoesNotOverlap, AggValueSlot::IsZeroed); } - + CGF.EmitAggExpr(E->getSubExpr(), valueDest); return; } @@ -801,7 +801,7 @@ void AggExprEmitter::VisitCastExpr(CastExpr *E) { "Implicit cast types must be compatible"); Visit(E->getSubExpr()); break; - + case CK_LValueBitCast: llvm_unreachable("should not be emitting lvalue bitcast as rvalue"); @@ -1140,7 +1140,7 @@ void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) { Dest); return; } - + LValue LHS = CGF.EmitLValue(E->getLHS()); // If we have an atomic type, evaluate into the destination and then @@ -1155,7 +1155,7 @@ void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) { // Codegen the RHS so that it stores directly into the LHS. AggValueSlot LHSSlot = - AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed, + AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed, needsGC(E->getLHS()->getType()), AggValueSlot::IsAliased, AggValueSlot::MayOverlap); @@ -1163,7 +1163,7 @@ void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) { if (!LHSSlot.isVolatile() && CGF.hasVolatileMember(E->getLHS()->getType())) LHSSlot.setVolatile(true); - + CGF.EmitAggExpr(E->getRHS(), LHSSlot); // Copy into the destination if the assignment isn't ignored. @@ -1303,13 +1303,13 @@ static bool isSimpleZero(const Expr *E, CodeGenFunction &CGF) { // '\0' if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) return CL->getValue() == 0; - + // Otherwise, hard case: conservatively return false. return false; } -void +void AggExprEmitter::EmitInitializationToLValue(Expr *E, LValue LV) { QualType type = LV.getType(); // FIXME: Ignore result? @@ -1326,7 +1326,7 @@ AggExprEmitter::EmitInitializationToLValue(Expr *E, LValue LV) { RValue RV = CGF.EmitReferenceBindingToExpr(E); return CGF.EmitStoreThroughLValue(RV, LV); } - + switch (CGF.getEvaluationKind(type)) { case TEK_Complex: CGF.EmitComplexExprIntoLValue(E, LV, /*isInit*/ true); @@ -1357,7 +1357,7 @@ void AggExprEmitter::EmitNullInitializationToLValue(LValue lv) { // copied into it, we don't have to emit any zeros here. if (Dest.isZeroed() && CGF.getTypes().isZeroInitializable(type)) return; - + if (CGF.hasScalarEvaluationKind(type)) { // For non-aggregates, we can store the appropriate null constant. llvm::Value *null = CGF.CGM.EmitNullConstant(type); @@ -1501,12 +1501,12 @@ void AggExprEmitter::VisitInitListExpr(InitListExpr *E) { if (curInitIndex == NumInitElements && Dest.isZeroed() && CGF.getTypes().isZeroInitializable(E->getType())) break; - + LValue LV = CGF.EmitLValueForFieldInitialization(DestLV, field); // We never generate write-barries for initialized fields. LV.setNonGC(true); - + if (curInitIndex < NumInitElements) { // Store the initializer into the field. EmitInitializationToLValue(E->getInit(curInitIndex++), LV); @@ -1535,10 +1535,10 @@ void AggExprEmitter::VisitInitListExpr(InitListExpr *E) { pushedCleanup = true; } } - + // If the GEP didn't get used because of a dead zero init or something // else, clean it up for -O0 builds and general tidiness. - if (!pushedCleanup && LV.isSimple()) + if (!pushedCleanup && LV.isSimple()) if (llvm::GetElementPtrInst *GEP = dyn_cast<llvm::GetElementPtrInst>(LV.getPointer())) if (GEP->use_empty()) @@ -1677,7 +1677,7 @@ static CharUnits GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF) { ILE = dyn_cast<InitListExpr>(ILE->getInit(0)); if (!ILE || !CGF.getTypes().isZeroInitializable(ILE->getType())) return CGF.getContext().getTypeSizeInChars(E->getType()); - + // InitListExprs for structs have to be handled carefully. If there are // reference members, we need to consider the size of the reference, not the // referencee. InitListExprs for unions and arrays can't have references. @@ -1685,7 +1685,7 @@ static CharUnits GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF) { if (!RT->isUnionType()) { RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl(); CharUnits NumNonZeroBytes = CharUnits::Zero(); - + unsigned ILEElement = 0; if (auto *CXXRD = dyn_cast<CXXRecordDecl>(SD)) while (ILEElement != CXXRD->getNumBases()) @@ -1701,7 +1701,7 @@ static CharUnits GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF) { continue; const Expr *E = ILE->getInit(ILEElement++); - + // Reference values are always non-null and have the width of a pointer. if (Field->getType()->isReferenceType()) NumNonZeroBytes += CGF.getContext().toCharUnitsFromBits( @@ -1709,12 +1709,12 @@ static CharUnits GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF) { else NumNonZeroBytes += GetNumNonZeroBytesInInit(E, CGF); } - + return NumNonZeroBytes; } } - - + + CharUnits NumNonZeroBytes = CharUnits::Zero(); for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) NumNonZeroBytes += GetNumNonZeroBytesInInit(ILE->getInit(i), CGF); @@ -1750,14 +1750,14 @@ static void CheckAggExprForMemSetUse(AggValueSlot &Slot, const Expr *E, CharUnits NumNonZeroBytes = GetNumNonZeroBytesInInit(E, CGF); if (NumNonZeroBytes*4 > Size) return; - + // Okay, it seems like a good idea to use an initial memset, emit the call. llvm::Constant *SizeVal = CGF.Builder.getInt64(Size.getQuantity()); - Address Loc = Slot.getAddress(); + Address Loc = Slot.getAddress(); Loc = CGF.Builder.CreateElementBitCast(Loc, CGF.Int8Ty); CGF.Builder.CreateMemSet(Loc, CGF.Builder.getInt8(0), SizeVal, false); - + // Tell the AggExprEmitter that the slot is known zero. Slot.setZeroed(); } @@ -1777,7 +1777,7 @@ void CodeGenFunction::EmitAggExpr(const Expr *E, AggValueSlot Slot) { // Optimize the slot if possible. CheckAggExprForMemSetUse(Slot, E, *this); - + AggExprEmitter(*this, Slot, Slot.isIgnored()).Visit(const_cast<Expr*>(E)); } @@ -1826,7 +1826,7 @@ void CodeGenFunction::EmitAggregateCopy(LValue Dest, LValue Src, QualType Ty, if (getLangOpts().CPlusPlus) { if (const RecordType *RT = Ty->getAs<RecordType>()) { CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl()); - assert((Record->hasTrivialCopyConstructor() || + assert((Record->hasTrivialCopyConstructor() || Record->hasTrivialCopyAssignment() || Record->hasTrivialMoveConstructor() || Record->hasTrivialMoveAssignment() || @@ -1899,7 +1899,7 @@ void CodeGenFunction::EmitAggregateCopy(LValue Dest, LValue Src, QualType Ty, } else if (const RecordType *RecordTy = Ty->getAs<RecordType>()) { RecordDecl *Record = RecordTy->getDecl(); if (Record->hasObjectMember()) { - CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr, + CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr, SizeVal); return; } @@ -1907,7 +1907,7 @@ void CodeGenFunction::EmitAggregateCopy(LValue Dest, LValue Src, QualType Ty, QualType BaseType = getContext().getBaseElementType(Ty); if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { if (RecordTy->getDecl()->hasObjectMember()) { - CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr, + CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr, SizeVal); return; } diff --git a/lib/CodeGen/CGExprCXX.cpp b/lib/CodeGen/CGExprCXX.cpp index 8955d8a4a83c..f29ef754c03f 100644 --- a/lib/CodeGen/CGExprCXX.cpp +++ b/lib/CodeGen/CGExprCXX.cpp @@ -255,7 +255,7 @@ RValue CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr( if (MD->isTrivial() || (MD->isDefaulted() && MD->getParent()->isUnion())) { if (isa<CXXDestructorDecl>(MD)) return RValue::get(nullptr); - if (isa<CXXConstructorDecl>(MD) && + if (isa<CXXConstructorDecl>(MD) && cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) return RValue::get(nullptr); @@ -337,7 +337,7 @@ RValue CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr( // We also don't emit a virtual call if the base expression has a record type // because then we know what the type is. bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod; - + if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) { assert(CE->arg_begin() == CE->arg_end() && "Destructor shouldn't have explicit parameters"); @@ -367,7 +367,7 @@ RValue CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr( } return RValue::get(nullptr); } - + CGCallee Callee; if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { Callee = CGCallee::forDirect( @@ -416,20 +416,20 @@ CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E, cast<BinaryOperator>(E->getCallee()->IgnoreParens()); const Expr *BaseExpr = BO->getLHS(); const Expr *MemFnExpr = BO->getRHS(); - - const MemberPointerType *MPT = + + const MemberPointerType *MPT = MemFnExpr->getType()->castAs<MemberPointerType>(); - const FunctionProtoType *FPT = + const FunctionProtoType *FPT = MPT->getPointeeType()->castAs<FunctionProtoType>(); - const CXXRecordDecl *RD = + const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl()); // Emit the 'this' pointer. Address This = Address::invalid(); if (BO->getOpcode() == BO_PtrMemI) This = EmitPointerWithAlignment(BaseExpr); - else + else This = EmitLValue(BaseExpr).getAddress(); EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This.getPointer(), @@ -443,10 +443,10 @@ CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E, CGCallee Callee = CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This, ThisPtrForCall, MemFnPtr, MPT); - + CallArgList Args; - QualType ThisType = + QualType ThisType = getContext().getPointerType(getContext().getTagDeclType(RD)); // Push the this ptr. @@ -570,7 +570,7 @@ CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest) { assert(!Dest.isIgnored() && "Must have a destination!"); const CXXConstructorDecl *CD = E->getConstructor(); - + // If we require zero initialization before (or instead of) calling the // constructor, as can be the case with a non-user-provided default // constructor, emit the zero initialization now, unless destination is @@ -588,11 +588,11 @@ CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E, break; } } - + // If this is a call to a trivial default constructor, do nothing. if (CD->isTrivial() && CD->isDefaultConstructor()) return; - + // Elide the constructor if we're constructing from a temporary. // The temporary check is required because Sema sets this on NRVO // returns. @@ -604,15 +604,16 @@ CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E, return; } } - + if (const ArrayType *arrayType = getContext().getAsArrayType(E->getType())) { - EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddress(), E); + EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddress(), E, + Dest.isSanitizerChecked()); } else { CXXCtorType Type = Ctor_Complete; bool ForVirtualBase = false; bool Delegating = false; - + switch (E->getConstructionKind()) { case CXXConstructExpr::CK_Delegating: // We should be emitting a constructor; GlobalDecl will assert this @@ -631,10 +632,11 @@ CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E, case CXXConstructExpr::CK_NonVirtualBase: Type = Ctor_Base; } - + // Call the constructor. EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating, - Dest.getAddress(), E, Dest.mayOverlap()); + Dest.getAddress(), E, Dest.mayOverlap(), + Dest.isSanitizerChecked()); } } @@ -642,19 +644,19 @@ void CodeGenFunction::EmitSynthesizedCXXCopyCtor(Address Dest, Address Src, const Expr *Exp) { if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp)) Exp = E->getSubExpr(); - assert(isa<CXXConstructExpr>(Exp) && + assert(isa<CXXConstructExpr>(Exp) && "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr"); const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp); const CXXConstructorDecl *CD = E->getConstructor(); RunCleanupsScope Scope(*this); - + // If we require zero initialization before (or instead of) calling the // constructor, as can be the case with a non-user-provided default // constructor, emit the zero initialization now. // FIXME. Do I still need this for a copy ctor synthesis? if (E->requiresZeroInitialization()) EmitNullInitialization(Dest, E->getType()); - + assert(!getContext().getAsConstantArrayType(E->getType()) && "EmitSynthesizedCXXCopyCtor - Copied-in Array"); EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E); @@ -709,7 +711,7 @@ static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF, // size_t. That's just a gloss, though, and it's wrong in one // important way: if the count is negative, it's an error even if // the cookie size would bring the total size >= 0. - bool isSigned + bool isSigned = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType(); llvm::IntegerType *numElementsType = cast<llvm::IntegerType>(numElements->getType()); @@ -729,7 +731,7 @@ static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF, // This will be a size_t. llvm::Value *size; - + // If someone is doing 'new int[42]' there is no need to do a dynamic check. // Don't bloat the -O0 code. if (llvm::ConstantInt *numElementsC = @@ -820,7 +822,7 @@ static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF, } else if (isSigned) { if (numElementsWidth < sizeWidth) numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy); - + // If there's a non-1 type size multiplier, then we can do the // signedness check at the same time as we do the multiply // because a negative number times anything will cause an @@ -897,7 +899,7 @@ static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF, // numElements doesn't need to be scaled. assert(arraySizeMultiplier == 1); } - + // Add in the cookie size if necessary. if (cookieSize != 0) { sizeWithoutCookie = size; @@ -954,7 +956,8 @@ static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init, AggValueSlot::IsDestructed, AggValueSlot::DoesNotNeedGCBarriers, AggValueSlot::IsNotAliased, - MayOverlap); + MayOverlap, AggValueSlot::IsNotZeroed, + AggValueSlot::IsSanitizerChecked); CGF.EmitAggExpr(Init, Slot); return; } @@ -1024,7 +1027,9 @@ void CodeGenFunction::EmitNewArrayInitializer( AggValueSlot::IsDestructed, AggValueSlot::DoesNotNeedGCBarriers, AggValueSlot::IsNotAliased, - AggValueSlot::DoesNotOverlap); + AggValueSlot::DoesNotOverlap, + AggValueSlot::IsNotZeroed, + AggValueSlot::IsSanitizerChecked); EmitAggExpr(ILE->getInit(0), Slot); // Move past these elements. @@ -1154,6 +1159,7 @@ void CodeGenFunction::EmitNewArrayInitializer( NumElements, llvm::ConstantInt::get(NumElements->getType(), InitListElements)); EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE, + /*NewPointerIsChecked*/true, CCE->requiresZeroInitialization()); return; } @@ -1230,7 +1236,7 @@ void CodeGenFunction::EmitNewArrayInitializer( CurPtr = Address(CurPtrPhi, ElementAlign); // Store the new Cleanup position for irregular Cleanups. - if (EndOfInit.isValid()) + if (EndOfInit.isValid()) Builder.CreateStore(CurPtr.getPointer(), EndOfInit); // Enter a partial-destruction Cleanup if necessary. @@ -1705,6 +1711,12 @@ llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) { result = Address(Builder.CreateLaunderInvariantGroup(result.getPointer()), result.getAlignment()); + // Emit sanitizer checks for pointer value now, so that in the case of an + // array it was checked only once and not at each constructor call. + EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall, + E->getAllocatedTypeSourceInfo()->getTypeLoc().getBeginLoc(), + result.getPointer(), allocType); + EmitNewInitializer(*this, E, allocType, elementTy, result, numElements, allocSizeWithoutCookie); if (E->isArray()) { @@ -1737,7 +1749,7 @@ llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) { resultPtr = PHI; } - + return resultPtr; } @@ -1901,13 +1913,13 @@ static void EmitObjectDelete(CodeGenFunction &CGF, case Qualifiers::OCL_Strong: CGF.EmitARCDestroyStrong(Ptr, ARCPreciseLifetime); break; - + case Qualifiers::OCL_Weak: CGF.EmitARCDestroyWeak(Ptr); break; } } - + CGF.PopCleanupBlock(); } @@ -2110,9 +2122,9 @@ static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E, } llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) { - llvm::Type *StdTypeInfoPtrTy = + llvm::Type *StdTypeInfoPtrTy = ConvertType(E->getType())->getPointerTo(); - + if (E->isTypeOperand()) { llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext())); @@ -2125,7 +2137,7 @@ llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) { // representing the type of the most derived object (that is, the dynamic // type) to which the glvalue refers. if (E->isPotentiallyEvaluated()) - return EmitTypeidFromVTable(*this, E->getExprOperand(), + return EmitTypeidFromVTable(*this, E->getExprOperand(), StdTypeInfoPtrTy); QualType OperandTy = E->getExprOperand()->getType(); @@ -2187,7 +2199,7 @@ llvm::Value *CodeGenFunction::EmitDynamicCast(Address ThisAddr, assert(SrcRecordTy->isRecordType() && "source type must be a record type!"); - // C++ [expr.dynamic.cast]p4: + // C++ [expr.dynamic.cast]p4: // If the value of v is a null pointer value in the pointer case, the result // is the null pointer value of type T. bool ShouldNullCheckSrcValue = @@ -2197,7 +2209,7 @@ llvm::Value *CodeGenFunction::EmitDynamicCast(Address ThisAddr, llvm::BasicBlock *CastNull = nullptr; llvm::BasicBlock *CastNotNull = nullptr; llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end"); - + if (ShouldNullCheckSrcValue) { CastNull = createBasicBlock("dynamic_cast.null"); CastNotNull = createBasicBlock("dynamic_cast.notnull"); diff --git a/lib/CodeGen/CGExprConstant.cpp b/lib/CodeGen/CGExprConstant.cpp index cfd0b859233a..68766479a539 100644 --- a/lib/CodeGen/CGExprConstant.cpp +++ b/lib/CodeGen/CGExprConstant.cpp @@ -57,7 +57,7 @@ public: private: ConstStructBuilder(ConstantEmitter &emitter) - : CGM(emitter.CGM), Emitter(emitter), Packed(false), + : CGM(emitter.CGM), Emitter(emitter), Packed(false), NextFieldOffsetInChars(CharUnits::Zero()), LLVMStructAlignment(CharUnits::One()) { } @@ -244,11 +244,11 @@ void ConstStructBuilder::AppendBitField(const FieldDecl *Field, assert(AT->getElementType()->isIntegerTy(CharWidth) && AT->getNumElements() != 0 && "Expected non-empty array padding of undefs"); - + // Remove the padding array. NextFieldOffsetInChars -= CharUnits::fromQuantity(AT->getNumElements()); Elements.pop_back(); - + // Add the padding back in two chunks. AppendPadding(CharUnits::fromQuantity(AT->getNumElements()-1)); AppendPadding(CharUnits::One()); @@ -269,7 +269,7 @@ void ConstStructBuilder::AppendBitField(const FieldDecl *Field, if (CGM.getDataLayout().isBigEndian()) { // We want the high bits. - Tmp = + Tmp = FieldValue.lshr(FieldValue.getBitWidth() - CharWidth).trunc(CharWidth); } else { // We want the low bits. @@ -314,14 +314,14 @@ void ConstStructBuilder::AppendPadding(CharUnits PadSize) { llvm::Constant *C = llvm::UndefValue::get(Ty); Elements.push_back(C); - assert(getAlignment(C) == CharUnits::One() && + assert(getAlignment(C) == CharUnits::One() && "Padding must have 1 byte alignment!"); NextFieldOffsetInChars += getSizeInChars(C); } void ConstStructBuilder::AppendTailPadding(CharUnits RecordSize) { - assert(NextFieldOffsetInChars <= RecordSize && + assert(NextFieldOffsetInChars <= RecordSize && "Size mismatch!"); AppendPadding(RecordSize - NextFieldOffsetInChars); @@ -364,7 +364,7 @@ void ConstStructBuilder::ConvertStructToPacked() { LLVMStructAlignment = CharUnits::One(); Packed = true; } - + bool ConstStructBuilder::Build(InitListExpr *ILE) { RecordDecl *RD = ILE->getType()->getAs<RecordType>()->getDecl(); const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD); @@ -972,7 +972,7 @@ public: unsigned NumInitElements = Updater->getNumInits(); unsigned NumElements = AType->getNumElements(); - + std::vector<llvm::Constant *> Elts; Elts.reserve(NumElements); @@ -1006,7 +1006,7 @@ public: Elts[i] = EmitDesignatedInitUpdater(Elts[i], ChildILE, destElemType); else Elts[i] = Emitter.tryEmitPrivateForMemory(Init, destElemType); - + if (!Elts[i]) return nullptr; RewriteType |= (Elts[i]->getType() != ElemType); @@ -1037,17 +1037,17 @@ public: auto C = Visit(E->getBase(), destType); if (!C) return nullptr; return EmitDesignatedInitUpdater(C, E->getUpdater(), destType); - } + } llvm::Constant *VisitCXXConstructExpr(CXXConstructExpr *E, QualType Ty) { if (!E->getConstructor()->isTrivial()) return nullptr; // FIXME: We should not have to call getBaseElementType here. - const RecordType *RT = + const RecordType *RT = CGM.getContext().getBaseElementType(Ty)->getAs<RecordType>(); const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); - + // If the class doesn't have a trivial destructor, we can't emit it as a // constant expr. if (!RD->hasTrivialDestructor()) @@ -1482,7 +1482,7 @@ llvm::Constant * ConstantEmitter::tryEmitAbstractForMemory(const Expr *E, QualType destType) { auto nonMemoryDestType = getNonMemoryType(CGM, destType); auto C = tryEmitAbstract(E, nonMemoryDestType); - return (C ? emitForMemory(C, destType) : nullptr); + return (C ? emitForMemory(C, destType) : nullptr); } llvm::Constant * @@ -1490,7 +1490,7 @@ ConstantEmitter::tryEmitAbstractForMemory(const APValue &value, QualType destType) { auto nonMemoryDestType = getNonMemoryType(CGM, destType); auto C = tryEmitAbstract(value, nonMemoryDestType); - return (C ? emitForMemory(C, destType) : nullptr); + return (C ? emitForMemory(C, destType) : nullptr); } llvm::Constant *ConstantEmitter::tryEmitPrivateForMemory(const Expr *E, @@ -2064,8 +2064,7 @@ static llvm::Constant *EmitNullConstant(CodeGenModule &CGM, if (record->isUnion()) { if (Field->getIdentifier()) break; - if (const auto *FieldRD = - dyn_cast_or_null<RecordDecl>(Field->getType()->getAsTagDecl())) + if (const auto *FieldRD = Field->getType()->getAsRecordDecl()) if (FieldRD->findFirstNamedDataMember()) break; } @@ -2074,7 +2073,7 @@ static llvm::Constant *EmitNullConstant(CodeGenModule &CGM, // Fill in the virtual bases, if we're working with the complete object. if (CXXR && asCompleteObject) { for (const auto &I : CXXR->vbases()) { - const CXXRecordDecl *base = + const CXXRecordDecl *base = cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); // Ignore empty bases. @@ -2096,7 +2095,7 @@ static llvm::Constant *EmitNullConstant(CodeGenModule &CGM, if (!elements[i]) elements[i] = llvm::Constant::getNullValue(structure->getElementType(i)); } - + return llvm::ConstantStruct::get(structure, elements); } @@ -2126,7 +2125,7 @@ llvm::Constant *CodeGenModule::EmitNullConstant(QualType T) { if (getTypes().isZeroInitializable(T)) return llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(T)); - + if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T)) { llvm::ArrayType *ATy = cast<llvm::ArrayType>(getTypes().ConvertTypeForMem(T)); diff --git a/lib/CodeGen/CGExprScalar.cpp b/lib/CodeGen/CGExprScalar.cpp index 783f74c5026d..c62588c68272 100644 --- a/lib/CodeGen/CGExprScalar.cpp +++ b/lib/CodeGen/CGExprScalar.cpp @@ -299,13 +299,31 @@ public: Value *Src, QualType SrcType, QualType DstType, llvm::Type *DstTy, SourceLocation Loc); + /// Known implicit conversion check kinds. + /// Keep in sync with the enum of the same name in ubsan_handlers.h + enum ImplicitConversionCheckKind : unsigned char { + ICCK_IntegerTruncation = 0, + }; + + /// Emit a check that an [implicit] truncation of an integer does not + /// discard any bits. It is not UB, so we use the value after truncation. + void EmitIntegerTruncationCheck(Value *Src, QualType SrcType, Value *Dst, + QualType DstType, SourceLocation Loc); + /// Emit a conversion from the specified type to the specified destination /// type, both of which are LLVM scalar types. - Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy, - SourceLocation Loc); + struct ScalarConversionOpts { + bool TreatBooleanAsSigned; + bool EmitImplicitIntegerTruncationChecks; - Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy, - SourceLocation Loc, bool TreatBooleanAsSigned); + ScalarConversionOpts() + : TreatBooleanAsSigned(false), + EmitImplicitIntegerTruncationChecks(false) {} + }; + Value * + EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy, + SourceLocation Loc, + ScalarConversionOpts Opts = ScalarConversionOpts()); /// Emit a conversion from the specified complex type to the specified /// destination type, where the destination type is an LLVM scalar type. @@ -923,18 +941,59 @@ void ScalarExprEmitter::EmitFloatConversionCheck( SanitizerHandler::FloatCastOverflow, StaticArgs, OrigSrc); } -/// Emit a conversion from the specified type to the specified destination type, -/// both of which are LLVM scalar types. -Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType, - QualType DstType, - SourceLocation Loc) { - return EmitScalarConversion(Src, SrcType, DstType, Loc, false); +void ScalarExprEmitter::EmitIntegerTruncationCheck(Value *Src, QualType SrcType, + Value *Dst, QualType DstType, + SourceLocation Loc) { + if (!CGF.SanOpts.has(SanitizerKind::ImplicitIntegerTruncation)) + return; + + llvm::Type *SrcTy = Src->getType(); + llvm::Type *DstTy = Dst->getType(); + + // We only care about int->int conversions here. + // We ignore conversions to/from pointer and/or bool. + if (!(SrcType->isIntegerType() && DstType->isIntegerType())) + return; + + assert(isa<llvm::IntegerType>(SrcTy) && isa<llvm::IntegerType>(DstTy) && + "clang integer type lowered to non-integer llvm type"); + + unsigned SrcBits = SrcTy->getScalarSizeInBits(); + unsigned DstBits = DstTy->getScalarSizeInBits(); + // This must be truncation. Else we do not care. + if (SrcBits <= DstBits) + return; + + assert(!DstType->isBooleanType() && "we should not get here with booleans."); + + CodeGenFunction::SanitizerScope SanScope(&CGF); + + llvm::Value *Check = nullptr; + + // 1. Extend the truncated value back to the same width as the Src. + bool InputSigned = DstType->isSignedIntegerOrEnumerationType(); + Check = Builder.CreateIntCast(Dst, SrcTy, InputSigned, "anyext"); + // 2. Equality-compare with the original source value + Check = Builder.CreateICmpEQ(Check, Src, "truncheck"); + // If the comparison result is 'i1 false', then the truncation was lossy. + + llvm::Constant *StaticArgs[] = { + CGF.EmitCheckSourceLocation(Loc), CGF.EmitCheckTypeDescriptor(SrcType), + CGF.EmitCheckTypeDescriptor(DstType), + llvm::ConstantInt::get(Builder.getInt8Ty(), ICCK_IntegerTruncation)}; + CGF.EmitCheck(std::make_pair(Check, SanitizerKind::ImplicitIntegerTruncation), + SanitizerHandler::ImplicitConversion, StaticArgs, {Src, Dst}); } +/// Emit a conversion from the specified type to the specified destination type, +/// both of which are LLVM scalar types. Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType, QualType DstType, SourceLocation Loc, - bool TreatBooleanAsSigned) { + ScalarConversionOpts Opts) { + QualType NoncanonicalSrcType = SrcType; + QualType NoncanonicalDstType = DstType; + SrcType = CGF.getContext().getCanonicalType(SrcType); DstType = CGF.getContext().getCanonicalType(DstType); if (SrcType == DstType) return Src; @@ -1083,7 +1142,7 @@ Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType, if (isa<llvm::IntegerType>(SrcTy)) { bool InputSigned = SrcType->isSignedIntegerOrEnumerationType(); - if (SrcType->isBooleanType() && TreatBooleanAsSigned) { + if (SrcType->isBooleanType() && Opts.TreatBooleanAsSigned) { InputSigned = true; } if (isa<llvm::IntegerType>(DstTy)) @@ -1118,6 +1177,10 @@ Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType, } } + if (Opts.EmitImplicitIntegerTruncationChecks) + EmitIntegerTruncationCheck(Src, NoncanonicalSrcType, Res, + NoncanonicalDstType, Loc); + return Res; } @@ -1812,16 +1875,26 @@ Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) { return Builder.CreateVectorSplat(NumElements, Elt, "splat"); } - case CK_IntegralCast: + case CK_IntegralCast: { + ScalarConversionOpts Opts; + if (CGF.SanOpts.has(SanitizerKind::ImplicitIntegerTruncation)) { + if (auto *ICE = dyn_cast<ImplicitCastExpr>(CE)) + Opts.EmitImplicitIntegerTruncationChecks = !ICE->isPartOfExplicitCast(); + } + return EmitScalarConversion(Visit(E), E->getType(), DestTy, + CE->getExprLoc(), Opts); + } case CK_IntegralToFloating: case CK_FloatingToIntegral: case CK_FloatingCast: return EmitScalarConversion(Visit(E), E->getType(), DestTy, CE->getExprLoc()); - case CK_BooleanToSignedIntegral: + case CK_BooleanToSignedIntegral: { + ScalarConversionOpts Opts; + Opts.TreatBooleanAsSigned = true; return EmitScalarConversion(Visit(E), E->getType(), DestTy, - CE->getExprLoc(), - /*TreatBooleanAsSigned=*/true); + CE->getExprLoc(), Opts); + } case CK_IntegralToBoolean: return EmitIntToBoolConversion(Visit(E)); case CK_PointerToBoolean: @@ -2766,7 +2839,7 @@ static Value *emitPointerArithmetic(CodeGenFunction &CGF, // if (BinaryOperator::isNullPointerArithmeticExtension(CGF.getContext(), op.Opcode, - expr->getLHS(), + expr->getLHS(), expr->getRHS())) return CGF.Builder.CreateIntToPtr(index, pointer->getType()); diff --git a/lib/CodeGen/CGLoopInfo.cpp b/lib/CodeGen/CGLoopInfo.cpp index 28998ce8db44..21e2b8dd8c31 100644 --- a/lib/CodeGen/CGLoopInfo.cpp +++ b/lib/CodeGen/CGLoopInfo.cpp @@ -155,7 +155,7 @@ void LoopInfoStack::push(BasicBlock *Header, clang::ASTContext &Ctx, unsigned ValueInt = 1; // Translate opencl_unroll_hint attribute argument to // equivalent LoopHintAttr enums. - // OpenCL v2.0 s6.11.5: + // OpenCL v2.0 s6.11.5: // 0 - full unroll (no argument). // 1 - disable unroll. // other positive integer n - unroll by n. diff --git a/lib/CodeGen/CGObjC.cpp b/lib/CodeGen/CGObjC.cpp index 81c1201c0e06..b94bbf2a384f 100644 --- a/lib/CodeGen/CGObjC.cpp +++ b/lib/CodeGen/CGObjC.cpp @@ -45,7 +45,7 @@ static llvm::Constant *getNullForVariable(Address addr) { /// Emits an instance of NSConstantString representing the object. llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E) { - llvm::Constant *C = + llvm::Constant *C = CGM.getObjCRuntime().GenerateConstantString(E->getString()).getPointer(); // FIXME: This bitcast should just be made an invariant on the Runtime. return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType())); @@ -65,7 +65,7 @@ CodeGenFunction::EmitObjCBoxedExpr(const ObjCBoxedExpr *E) { assert(BoxingMethod && "BoxingMethod is null"); assert(BoxingMethod->isClassMethod() && "BoxingMethod must be a class method"); Selector Sel = BoxingMethod->getSelector(); - + // Generate a reference to the class pointer, which will be the receiver. // Assumes that the method was introduced in the class that should be // messaged (avoids pulling it out of the result type). @@ -76,8 +76,8 @@ CodeGenFunction::EmitObjCBoxedExpr(const ObjCBoxedExpr *E) { CallArgList Args; const ParmVarDecl *ArgDecl = *BoxingMethod->param_begin(); QualType ArgQT = ArgDecl->getType().getUnqualifiedType(); - - // ObjCBoxedExpr supports boxing of structs and unions + + // ObjCBoxedExpr supports boxing of structs and unions // via [NSValue valueWithBytes:objCType:] const QualType ValueType(SubExpr->getType().getCanonicalType()); if (ValueType->isObjCBoxableRecordType()) { @@ -92,7 +92,7 @@ CodeGenFunction::EmitObjCBoxedExpr(const ObjCBoxedExpr *E) { std::string Str; getContext().getObjCEncodingForType(ValueType, Str); llvm::Constant *GV = CGM.GetAddrOfConstantCString(Str).getPointer(); - + // Cast type encoding to correct type const ParmVarDecl *EncodingDecl = BoxingMethod->parameters()[1]; QualType EncodingQT = EncodingDecl->getType().getUnqualifiedType(); @@ -106,7 +106,7 @@ CodeGenFunction::EmitObjCBoxedExpr(const ObjCBoxedExpr *E) { RValue result = Runtime.GenerateMessageSend( *this, ReturnValueSlot(), BoxingMethod->getReturnType(), Sel, Receiver, Args, ClassDecl, BoxingMethod); - return Builder.CreateBitCast(result.getScalarVal(), + return Builder.CreateBitCast(result.getScalarVal(), ConvertType(E->getType())); } @@ -119,7 +119,7 @@ llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E, DLE = cast<ObjCDictionaryLiteral>(E); // Optimize empty collections by referencing constants, when available. - uint64_t NumElements = + uint64_t NumElements = ALE ? ALE->getNumElements() : DLE->getNumElements(); if (NumElements == 0 && CGM.getLangOpts().ObjCRuntime.hasEmptyCollections()) { StringRef ConstantName = ALE ? "__NSArray0__" : "__NSDictionary0__"; @@ -138,8 +138,8 @@ llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E, llvm::APInt APNumElements(Context.getTypeSize(Context.getSizeType()), NumElements); QualType ElementType = Context.getObjCIdType().withConst(); - QualType ElementArrayType - = Context.getConstantArrayType(ElementType, APNumElements, + QualType ElementArrayType + = Context.getConstantArrayType(ElementType, APNumElements, ArrayType::Normal, /*IndexTypeQuals=*/0); // Allocate the temporary array(s). @@ -147,7 +147,7 @@ llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E, Address Keys = Address::invalid(); if (DLE) Keys = CreateMemTemp(ElementArrayType, "keys"); - + // In ARC, we may need to do extra work to keep all the keys and // values alive until after the call. SmallVector<llvm::Value *, 16> NeededObjects; @@ -169,7 +169,7 @@ llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E, if (TrackNeededObjects) { NeededObjects.push_back(value); } - } else { + } else { // Emit the key and store it to the appropriate array slot. const Expr *Key = DLE->getKeyValueElement(i).Key; LValue KeyLV = MakeAddrLValue( @@ -191,9 +191,9 @@ llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E, } } } - + // Generate the argument list. - CallArgList Args; + CallArgList Args; ObjCMethodDecl::param_const_iterator PI = MethodWithObjects->param_begin(); const ParmVarDecl *argDecl = *PI++; QualType ArgQT = argDecl->getType().getUnqualifiedType(); @@ -205,7 +205,7 @@ llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E, } argDecl = *PI; ArgQT = argDecl->getType().getUnqualifiedType(); - llvm::Value *Count = + llvm::Value *Count = llvm::ConstantInt::get(CGM.getTypes().ConvertType(ArgQT), NumElements); Args.add(RValue::get(Count), ArgQT); @@ -214,7 +214,7 @@ llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E, QualType ResultType = E->getType(); const ObjCObjectPointerType *InterfacePointerType = ResultType->getAsObjCInterfacePointerType(); - ObjCInterfaceDecl *Class + ObjCInterfaceDecl *Class = InterfacePointerType->getObjectType()->getInterface(); CGObjCRuntime &Runtime = CGM.getObjCRuntime(); llvm::Value *Receiver = Runtime.GetClass(*this, Class); @@ -232,7 +232,7 @@ llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E, EmitARCIntrinsicUse(NeededObjects); } - return Builder.CreateBitCast(result.getScalarVal(), + return Builder.CreateBitCast(result.getScalarVal(), ConvertType(E->getType())); } @@ -557,7 +557,7 @@ void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD, if (CGM.getLangOpts().ObjCAutoRefCount && OMD->isInstanceMethod() && OMD->getSelector().isUnarySelector()) { - const IdentifierInfo *ident = + const IdentifierInfo *ident = OMD->getSelector().getIdentifierInfoForSlot(0); if (ident->isStr("dealloc")) EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind()); @@ -580,7 +580,7 @@ void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) { /// emitStructGetterCall - Call the runtime function to load a property /// into the return value slot. -static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar, +static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar, bool isAtomic, bool hasStrong) { ASTContext &Context = CGF.getContext(); @@ -588,7 +588,7 @@ static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar, CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0) .getAddress(); - // objc_copyStruct (ReturnValue, &structIvar, + // objc_copyStruct (ReturnValue, &structIvar, // sizeof (Type of Ivar), isAtomic, false); CallArgList args; @@ -844,30 +844,30 @@ static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) { return false; } -/// emitCPPObjectAtomicGetterCall - Call the runtime function to +/// emitCPPObjectAtomicGetterCall - Call the runtime function to /// copy the ivar into the resturn slot. -static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF, +static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF, llvm::Value *returnAddr, ObjCIvarDecl *ivar, llvm::Constant *AtomicHelperFn) { // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar, // AtomicHelperFn); CallArgList args; - + // The 1st argument is the return Slot. args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy); - + // The 2nd argument is the address of the ivar. - llvm::Value *ivarAddr = - CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), + llvm::Value *ivarAddr = + CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0).getPointer(); ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy); args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy); - + // Third argument is the helper function. args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy); - - llvm::Constant *copyCppAtomicObjectFn = + + llvm::Constant *copyCppAtomicObjectFn = CGF.CGM.getObjCRuntime().GetCppAtomicObjectGetFunction(); CGCallee callee = CGCallee::forDirect(copyCppAtomicObjectFn); CGF.EmitCall( @@ -889,7 +889,7 @@ CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl, } else { ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl(); - emitCPPObjectAtomicGetterCall(*this, ReturnValue.getPointer(), + emitCPPObjectAtomicGetterCall(*this, ReturnValue.getPointer(), ivar, AtomicHelperFn); } return; @@ -899,7 +899,7 @@ CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl, QualType propType = prop->getType(); ObjCMethodDecl *getterMethod = prop->getGetterMethodDecl(); - ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl(); + ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl(); // Pick an implementation strategy. PropertyImplStrategy strategy(CGM, propImpl); @@ -1039,7 +1039,7 @@ CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl, value = Builder.CreateBitCast( value, ConvertType(GetterMethodDecl->getReturnType())); } - + EmitReturnOfRValue(RValue::get(value), propType); return; } @@ -1055,7 +1055,7 @@ CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl, /// from the first formal parameter into the given ivar. static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD, ObjCIvarDecl *ivar) { - // objc_copyStruct (&structIvar, &Arg, + // objc_copyStruct (&structIvar, &Arg, // sizeof (struct something), true, false); CallArgList args; @@ -1068,7 +1068,7 @@ static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD, // The second argument is the address of the parameter variable. ParmVarDecl *argVar = *OMD->param_begin(); - DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(), + DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(), VK_LValue, SourceLocation()); llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer(); argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy); @@ -1093,36 +1093,36 @@ static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD, callee, ReturnValueSlot(), args); } -/// emitCPPObjectAtomicSetterCall - Call the runtime function to store -/// the value from the first formal parameter into the given ivar, using +/// emitCPPObjectAtomicSetterCall - Call the runtime function to store +/// the value from the first formal parameter into the given ivar, using /// the Cpp API for atomic Cpp objects with non-trivial copy assignment. -static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF, +static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD, ObjCIvarDecl *ivar, llvm::Constant *AtomicHelperFn) { - // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg, + // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg, // AtomicHelperFn); CallArgList args; - + // The first argument is the address of the ivar. - llvm::Value *ivarAddr = - CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), + llvm::Value *ivarAddr = + CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0).getPointer(); ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy); args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy); - + // The second argument is the address of the parameter variable. ParmVarDecl *argVar = *OMD->param_begin(); - DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(), + DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(), VK_LValue, SourceLocation()); llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer(); argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy); args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy); - + // Third argument is the helper function. args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy); - - llvm::Constant *fn = + + llvm::Constant *fn = CGF.CGM.getObjCRuntime().GetCppAtomicObjectSetFunction(); CGCallee callee = CGCallee::forDirect(fn); CGF.EmitCall( @@ -1168,7 +1168,7 @@ CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl, const ObjCPropertyDecl *prop = propImpl->getPropertyDecl(); ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl(); ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl(); - + // Just use the setter expression if Sema gave us one and it's // non-trivial. if (!hasTrivialSetExpr(propImpl)) { @@ -1221,7 +1221,7 @@ CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl, llvm::Constant *setPropertyFn = nullptr; if (UseOptimizedSetter(CGM)) { // 10.8 and iOS 6.0 code and GC is off - setOptimizedPropertyFn = + setOptimizedPropertyFn = CGM.getObjCRuntime() .GetOptimizedPropertySetFunction(strategy.isAtomic(), strategy.isCopy()); @@ -1237,7 +1237,7 @@ CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl, return; } } - + // Emit objc_setProperty((id) self, _cmd, offset, arg, // <is-atomic>, <is-copy>). llvm::Value *cmd = @@ -1272,7 +1272,7 @@ CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl, EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args), callee, ReturnValueSlot(), args); } - + return; } @@ -1301,7 +1301,7 @@ CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl, ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack, argType.getUnqualifiedType(), CK_LValueToRValue, &arg, VK_RValue); - + // The property type can differ from the ivar type in some situations with // Objective-C pointer types, we can always bit cast the RHS in these cases. // The following absurdity is just to ensure well-formed IR. @@ -1435,7 +1435,7 @@ void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP, for (const auto *IvarInit : IMP->inits()) { FieldDecl *Field = IvarInit->getAnyMember(); ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field); - LValue LV = EmitLValueForIvar(TypeOfSelfObject(), + LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), Ivar, 0); EmitAggExpr(IvarInit->getInit(), AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed, @@ -2015,7 +2015,7 @@ static void emitAutoreleasedReturnValueMarker(CodeGenFunction &CGF) { } else if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) { llvm::FunctionType *type = llvm::FunctionType::get(CGF.VoidTy, /*variadic*/false); - + marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true); // If we're at -O1 and above, we don't want to litter the code @@ -2368,10 +2368,10 @@ llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() { IdentifierInfo *II = &CGM.getContext().Idents.get("alloc"); Selector AllocSel = getContext().Selectors.getSelector(0, &II); CallArgList Args; - RValue AllocRV = - Runtime.GenerateMessageSend(*this, ReturnValueSlot(), + RValue AllocRV = + Runtime.GenerateMessageSend(*this, ReturnValueSlot(), getContext().getObjCIdType(), - AllocSel, Receiver, Args); + AllocSel, Receiver, Args); // [Receiver init] Receiver = AllocRV.getScalarVal(); @@ -2380,7 +2380,7 @@ llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() { RValue InitRV = Runtime.GenerateMessageSend(*this, ReturnValueSlot(), getContext().getObjCIdType(), - InitSel, Receiver, Args); + InitSel, Receiver, Args); return InitRV.getScalarVal(); } @@ -2391,7 +2391,7 @@ void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) { Selector DrainSel = getContext().Selectors.getSelector(0, &II); CallArgList Args; CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(), - getContext().VoidTy, DrainSel, Arg, Args); + getContext().VoidTy, DrainSel, Arg, Args); } void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF, @@ -2471,7 +2471,7 @@ static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF, e = e->IgnoreParens(); QualType type = e->getType(); - // If we're loading retained from a __strong xvalue, we can avoid + // If we're loading retained from a __strong xvalue, we can avoid // an extra retain/release pair by zeroing out the source of this // "move" operation. if (e->isXValue() && @@ -2479,14 +2479,14 @@ static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF, type.getObjCLifetime() == Qualifiers::OCL_Strong) { // Emit the lvalue. LValue lv = CGF.EmitLValue(e); - + // Load the object pointer. llvm::Value *result = CGF.EmitLoadOfLValue(lv, SourceLocation()).getScalarVal(); - + // Set the source pointer to NULL. CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv); - + return TryEmitResult(result, true); } @@ -3225,7 +3225,7 @@ CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction( assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null"); if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty))) return HelperFn; - + ASTContext &C = getContext(); IdentifierInfo *II = &CGM.getContext().Idents.get("__assign_helper_atomic_property_"); @@ -3241,7 +3241,7 @@ CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction( QualType SrcTy = Ty; SrcTy.addConst(); SrcTy = C.getPointerType(SrcTy); - + FunctionArgList args; ImplicitParamDecl DstDecl(getContext(), FD, SourceLocation(), /*Id=*/nullptr, DestTy, ImplicitParamDecl::Other); @@ -3254,7 +3254,7 @@ CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction( CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args); llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI); - + llvm::Function *Fn = llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage, "__assign_helper_atomic_property_", @@ -3263,23 +3263,23 @@ CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction( CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI); StartFunction(FD, C.VoidTy, Fn, FI, args); - + DeclRefExpr DstExpr(&DstDecl, false, DestTy, VK_RValue, SourceLocation()); UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(), VK_LValue, OK_Ordinary, SourceLocation(), false); - + DeclRefExpr SrcExpr(&SrcDecl, false, SrcTy, VK_RValue, SourceLocation()); UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(), VK_LValue, OK_Ordinary, SourceLocation(), false); - + Expr *Args[2] = { &DST, &SRC }; CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment()); CXXOperatorCallExpr TheCall(C, OO_Equal, CalleeExp->getCallee(), Args, DestTy->getPointeeType(), VK_LValue, SourceLocation(), FPOptions()); - + EmitStmt(&TheCall); FinishFunction(); @@ -3307,8 +3307,8 @@ CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction( assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null"); if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty))) return HelperFn; - - + + ASTContext &C = getContext(); IdentifierInfo *II = &CGM.getContext().Idents.get("__copy_helper_atomic_property_"); @@ -3324,7 +3324,7 @@ CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction( QualType SrcTy = Ty; SrcTy.addConst(); SrcTy = C.getPointerType(SrcTy); - + FunctionArgList args; ImplicitParamDecl DstDecl(getContext(), FD, SourceLocation(), /*Id=*/nullptr, DestTy, ImplicitParamDecl::Other); @@ -3337,7 +3337,7 @@ CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction( CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args); llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI); - + llvm::Function *Fn = llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage, "__copy_helper_atomic_property_", &CGM.getModule()); @@ -3345,16 +3345,16 @@ CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction( CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI); StartFunction(FD, C.VoidTy, Fn, FI, args); - + DeclRefExpr SrcExpr(&SrcDecl, false, SrcTy, VK_RValue, SourceLocation()); - + UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(), VK_LValue, OK_Ordinary, SourceLocation(), false); - - CXXConstructExpr *CXXConstExpr = + + CXXConstructExpr *CXXConstExpr = cast<CXXConstructExpr>(PID->getGetterCXXConstructor()); - + SmallVector<Expr*, 4> ConstructorArgs; ConstructorArgs.push_back(&SRC); ConstructorArgs.append(std::next(CXXConstExpr->arg_begin()), @@ -3371,21 +3371,21 @@ CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction( CXXConstExpr->requiresZeroInitialization(), CXXConstExpr->getConstructionKind(), SourceRange()); - + DeclRefExpr DstExpr(&DstDecl, false, DestTy, VK_RValue, SourceLocation()); - + RValue DV = EmitAnyExpr(&DstExpr); CharUnits Alignment = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType()); - EmitAggExpr(TheCXXConstructExpr, + EmitAggExpr(TheCXXConstructExpr, AggValueSlot::forAddr(Address(DV.getScalarVal(), Alignment), Qualifiers(), AggValueSlot::IsDestructed, AggValueSlot::DoesNotNeedGCBarriers, AggValueSlot::IsNotAliased, AggValueSlot::DoesNotOverlap)); - + FinishFunction(); HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy); CGM.setAtomicGetterHelperFnMap(Ty, HelperFn); diff --git a/lib/CodeGen/CGObjCGNU.cpp b/lib/CodeGen/CGObjCGNU.cpp index 6a0554b46b1c..3e994edc976b 100644 --- a/lib/CodeGen/CGObjCGNU.cpp +++ b/lib/CodeGen/CGObjCGNU.cpp @@ -114,7 +114,7 @@ protected: /// contains the receiver (object) and the expected class. llvm::StructType *ObjCSuperTy; /// struct objc_super*. The type of the argument to the superclass message - /// lookup functions. + /// lookup functions. llvm::PointerType *PtrToObjCSuperTy; /// LLVM type for selectors. Opaque pointer (i8*) unless a header declaring /// SEL is included in a header somewhere, in which case it will be whatever @@ -159,7 +159,7 @@ protected: llvm::IntegerType *LongTy; /// LLVM type for C size_t. Used in various runtime data structures. llvm::IntegerType *SizeTy; - /// LLVM type for C intptr_t. + /// LLVM type for C intptr_t. llvm::IntegerType *IntPtrTy; /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions. llvm::IntegerType *PtrDiffTy; @@ -197,7 +197,7 @@ protected: /// Helper function that generates a constant string and returns a pointer to /// the start of the string. The result of this function can be used anywhere - /// where the C code specifies const char*. + /// where the C code specifies const char*. llvm::Constant *MakeConstantString(StringRef Str, const char *Name = "") { ConstantAddress Array = CGM.GetAddrOfConstantCString(Str, Name); return llvm::ConstantExpr::getGetElementPtr(Array.getElementType(), @@ -243,7 +243,7 @@ protected: return MakeConstantString(PD->getNameAsString()); } - /// Push the property attributes into two structure fields. + /// Push the property attributes into two structure fields. void PushPropertyAttributes(ConstantStructBuilder &Fields, const ObjCPropertyDecl *property, bool isSynthesized=true, bool isDynamic=true) { @@ -377,7 +377,7 @@ protected: /// Runtime functions used for memory management in GC mode. Note that clang /// supports code generation for calling these functions, but neither GNU /// runtime actually supports this API properly yet. - LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn, + LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn, WeakAssignFn, GlobalAssignFn; typedef std::pair<std::string, std::string> ClassAliasPair; @@ -554,7 +554,7 @@ protected: /// stored in a 64-bit value with the low bit set to 1 and the remaining 63 /// bits set to their values, LSB first, while larger ones are stored in a /// structure of this / form: - /// + /// /// struct { int32_t length; int32_t values[length]; }; /// /// The values in the array are stored in host-endian format, with the least @@ -810,7 +810,7 @@ class CGObjCGNUstep : public CGObjCGNU { // Slot_t objc_slot_lookup_super(struct objc_super*, SEL); SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy, PtrToObjCSuperTy, SelectorTy); - // If we're in ObjC++ mode, then we want to make + // If we're in ObjC++ mode, then we want to make if (CGM.getLangOpts().CPlusPlus) { llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext); // void *__cxa_begin_catch(void *e) @@ -892,7 +892,7 @@ class CGObjCGNUstep2 : public CGObjCGNUstep { static constexpr const char *const SelSection = "__objc_selectors"; /// The section for classes. static constexpr const char *const ClsSection = "__objc_classes"; - /// The section for references to classes. + /// The section for references to classes. static constexpr const char *const ClsRefSection = "__objc_class_refs"; /// The section for categories. static constexpr const char *const CatSection = "__objc_cats"; @@ -956,8 +956,8 @@ class CGObjCGNUstep2 : public CGObjCGNUstep { bool isNonASCII = SL->containsNonAscii(); - auto LiteralLength = SL->getLength(); - + auto LiteralLength = SL->getLength(); + if ((CGM.getTarget().getPointerWidth(0) == 64) && (LiteralLength < 9) && !isNonASCII) { // Tiny strings are only used on 64-bit platforms. They store 8 7-bit @@ -1224,7 +1224,7 @@ class CGObjCGNUstep2 : public CGObjCGNUstep { std::string Name = SymbolForProtocol(ProtocolName); auto *GV = TheModule.getGlobalVariable(Name); if (!GV) { - // Emit a placeholder symbol. + // Emit a placeholder symbol. GV = new llvm::GlobalVariable(TheModule, ProtocolTy, false, llvm::GlobalValue::ExternalLinkage, nullptr, Name); GV->setAlignment(CGM.getPointerAlign().getQuantity()); @@ -1281,7 +1281,7 @@ class CGObjCGNUstep2 : public CGObjCGNUstep { return Protocol; EmittedProtocol = true; - + // Use the protocol definition, if there is one. if (const ObjCProtocolDecl *Def = PD->getDefinition()) PD = Def; @@ -1680,7 +1680,7 @@ class CGObjCGNUstep2 : public CGObjCGNUstep { OffsetVar = new llvm::GlobalVariable(TheModule, IntTy, false, llvm::GlobalValue::ExternalLinkage, OffsetValue, OffsetName); - auto ivarVisibility = + auto ivarVisibility = (IVD->getAccessControl() == ObjCIvarDecl::Private || IVD->getAccessControl() == ObjCIvarDecl::Package || classDecl->getVisibility() == HiddenVisibility) ? @@ -1700,14 +1700,14 @@ class CGObjCGNUstep2 : public CGObjCGNUstep { // Bits 0-1 are ownership. // Bit 2 indicates an extended type encoding // Bits 3-8 contain log2(aligment) - ivarBuilder.addInt(Int32Ty, + ivarBuilder.addInt(Int32Ty, (align << 3) | (1<<2) | FlagsForOwnership(ivarTy.getQualifiers().getObjCLifetime())); ivarBuilder.finishAndAddTo(ivarArrayBuilder); } ivarArrayBuilder.finishAndAddTo(ivarListBuilder); auto ivarList = ivarListBuilder.finishAndCreateGlobal(".objc_ivar_list", - CGM.getPointerAlign(), /*constant*/ false, + CGM.getPointerAlign(), /*constant*/ false, llvm::GlobalValue::PrivateLinkage); classFields.add(ivarList); } @@ -2448,7 +2448,7 @@ CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF, // returns. With GCC, this generates a random return value (whatever happens // to be on the stack / in those registers at the time) on most platforms, // and generates an illegal instruction trap on SPARC. With LLVM it corrupts - // the stack. + // the stack. bool isPointerSizedReturn = (ResultType->isAnyPointerType() || ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType()); @@ -2461,7 +2461,7 @@ CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF, messageBB = CGF.createBasicBlock("msgSend"); continueBB = CGF.createBasicBlock("continue"); - llvm::Value *isNil = Builder.CreateICmpEQ(Receiver, + llvm::Value *isNil = Builder.CreateICmpEQ(Receiver, llvm::Constant::getNullValue(Receiver->getType())); Builder.CreateCondBr(isNil, continueBB, messageBB); CGF.EmitBlock(messageBB); @@ -2495,7 +2495,7 @@ CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF, // If we have non-legacy dispatch specified, we try using the objc_msgSend() // functions. These are not supported on all platforms (or all runtimes on a - // given platform), so we + // given platform), so we switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) { case CodeGenOptions::Legacy: imp = LookupIMP(CGF, Receiver, cmd, node, MSI); @@ -2720,7 +2720,7 @@ llvm::Constant *CGObjCGNU::GenerateClassStructure( // Fill in the structure - // isa + // isa Elements.addBitCast(MetaClass, PtrToInt8Ty); // super_class Elements.add(SuperClass); @@ -2869,7 +2869,7 @@ CGObjCGNU::GenerateEmptyProtocol(StringRef ProtocolName) { void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) { std::string ProtocolName = PD->getNameAsString(); - + // Use the protocol definition, if there is one. if (const ObjCProtocolDecl *Def = PD->getDefinition()) PD = Def; @@ -2977,7 +2977,7 @@ void CGObjCGNU::GenerateProtocolHolderCategory() { /// stored in a 64-bit value with the low bit set to 1 and the remaining 63 /// bits set to their values, LSB first, while larger ones are stored in a /// structure of this / form: -/// +/// /// struct { int32_t length; int32_t values[length]; }; /// /// The values in the array are stored in host-endian format, with the least @@ -3200,7 +3200,7 @@ void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) { } // Get the size of instances. - int instanceSize = + int instanceSize = Context.getASTObjCImplementationLayout(OID).getSize().getQuantity(); // Collect information about instance variables. @@ -3291,7 +3291,7 @@ void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) { // Collect the same information about synthesized properties, which don't // show up in the instance method lists. for (auto *propertyImpl : OID->property_impls()) - if (propertyImpl->getPropertyImplementation() == + if (propertyImpl->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { ObjCPropertyDecl *property = propertyImpl->getPropertyDecl(); auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) { @@ -3718,7 +3718,7 @@ void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF, // interoperate very well with foreign exceptions. // // In Objective-C++ mode, we actually emit something equivalent to the C++ - // exception handler. + // exception handler. EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn); } diff --git a/lib/CodeGen/CGObjCMac.cpp b/lib/CodeGen/CGObjCMac.cpp index 0c766575dc21..2b54e7bd67af 100644 --- a/lib/CodeGen/CGObjCMac.cpp +++ b/lib/CodeGen/CGObjCMac.cpp @@ -57,7 +57,7 @@ private: // should always bitcast before calling them. /// id objc_msgSend (id, SEL, ...) - /// + /// /// The default messenger, used for sends whose ABI is unchanged from /// the all-integer/pointer case. llvm::Constant *getMessageSendFn() const { @@ -184,12 +184,12 @@ public: /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL)) llvm::PointerType *SelectorPtrTy; - + private: /// ProtocolPtrTy - LLVM type for external protocol handles /// (typeof(Protocol)) llvm::Type *ExternalProtocolPtrTy; - + public: llvm::Type *getExternalProtocolPtrTy() { if (!ExternalProtocolPtrTy) { @@ -200,10 +200,10 @@ public: llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType()); ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T); } - + return ExternalProtocolPtrTy; } - + // SuperCTy - clang type for struct objc_super. QualType SuperCTy; // SuperPtrCTy - clang type for struct objc_super *. @@ -231,7 +231,7 @@ public: llvm::Type *CacheTy; /// CachePtrTy - LLVM type for struct objc_cache *. llvm::PointerType *CachePtrTy; - + llvm::Constant *getGetPropertyFn() { CodeGen::CodeGenTypes &Types = CGM.getTypes(); ASTContext &Ctx = CGM.getContext(); @@ -269,15 +269,15 @@ public: llvm::Constant *getOptimizedSetPropertyFn(bool atomic, bool copy) { CodeGen::CodeGenTypes &Types = CGM.getTypes(); ASTContext &Ctx = CGM.getContext(); - // void objc_setProperty_atomic(id self, SEL _cmd, + // void objc_setProperty_atomic(id self, SEL _cmd, // id newValue, ptrdiff_t offset); - // void objc_setProperty_nonatomic(id self, SEL _cmd, + // void objc_setProperty_nonatomic(id self, SEL _cmd, // id newValue, ptrdiff_t offset); - // void objc_setProperty_atomic_copy(id self, SEL _cmd, + // void objc_setProperty_atomic_copy(id self, SEL _cmd, // id newValue, ptrdiff_t offset); - // void objc_setProperty_nonatomic_copy(id self, SEL _cmd, + // void objc_setProperty_nonatomic_copy(id self, SEL _cmd, // id newValue, ptrdiff_t offset); - + SmallVector<CanQualType,4> Params; CanQualType IdType = Ctx.getCanonicalParamType(Ctx.getObjCIdType()); CanQualType SelType = Ctx.getCanonicalParamType(Ctx.getObjCSelType()); @@ -297,10 +297,10 @@ public: name = "objc_setProperty_nonatomic_copy"; else name = "objc_setProperty_nonatomic"; - + return CGM.CreateRuntimeFunction(FTy, name); } - + llvm::Constant *getCopyStructFn() { CodeGen::CodeGenTypes &Types = CGM.getTypes(); ASTContext &Ctx = CGM.getContext(); @@ -316,10 +316,10 @@ public: Types.arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Params)); return CGM.CreateRuntimeFunction(FTy, "objc_copyStruct"); } - + /// This routine declares and returns address of: /// void objc_copyCppObjectAtomic( - /// void *dest, const void *src, + /// void *dest, const void *src, /// void (*copyHelper) (void *dest, const void *source)); llvm::Constant *getCppAtomicObjectFunction() { CodeGen::CodeGenTypes &Types = CGM.getTypes(); @@ -334,7 +334,7 @@ public: Types.arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Params)); return CGM.CreateRuntimeFunction(FTy, "objc_copyCppObjectAtomic"); } - + llvm::Constant *getEnumerationMutationFn() { CodeGen::CodeGenTypes &Types = CGM.getTypes(); ASTContext &Ctx = CGM.getContext(); @@ -396,7 +396,7 @@ public: llvm::FunctionType::get(ObjectPtrTy, args, false); return CGM.CreateRuntimeFunction(FTy, "objc_assign_threadlocal"); } - + /// GcAssignIvarFn -- LLVM objc_assign_ivar function. llvm::Constant *getGcAssignIvarFn() { // id objc_assign_ivar(id, id *, ptrdiff_t) @@ -439,7 +439,7 @@ public: llvm::FunctionType *FTy = llvm::FunctionType::get(CGM.VoidTy, false); return CGM.CreateRuntimeFunction(FTy, "objc_exception_rethrow"); } - + /// SyncEnterFn - LLVM object_sync_enter function. llvm::Constant *getSyncEnterFn() { // int objc_sync_enter (id) @@ -550,7 +550,7 @@ public: /// ExceptionDataTy - LLVM type for struct _objc_exception_data. llvm::StructType *ExceptionDataTy; - + /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function. llvm::Constant *getExceptionTryEnterFn() { llvm::Type *params[] = { ExceptionDataTy->getPointerTo() }; @@ -727,7 +727,7 @@ public: llvm::StructType *EHTypeTy; llvm::Type *EHTypePtrTy; - + ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm); }; @@ -760,33 +760,33 @@ public: /// to '\0'. /// I != 0: Currently unused. BLOCK_LAYOUT_OPERATOR = 0, - + /// The next I+1 bytes do not contain a value of object pointer type. /// Note that this can leave the stream unaligned, meaning that /// subsequent word-size instructions do not begin at a multiple of /// the pointer size. BLOCK_LAYOUT_NON_OBJECT_BYTES = 1, - + /// The next I+1 words do not contain a value of object pointer type. /// This is simply an optimized version of BLOCK_LAYOUT_BYTES for /// when the required skip quantity is a multiple of the pointer size. BLOCK_LAYOUT_NON_OBJECT_WORDS = 2, - + /// The next I+1 words are __strong pointers to Objective-C /// objects or blocks. BLOCK_LAYOUT_STRONG = 3, - + /// The next I+1 words are pointers to __block variables. BLOCK_LAYOUT_BYREF = 4, - + /// The next I+1 words are __weak pointers to Objective-C /// objects or blocks. BLOCK_LAYOUT_WEAK = 5, - + /// The next I+1 words are __unsafe_unretained pointers to /// Objective-C objects or blocks. BLOCK_LAYOUT_UNRETAINED = 6 - + /// The next I+1 words are block or object pointers with some /// as-yet-unspecified ownership semantics. If we add more /// flavors of ownership semantics, values will be taken from @@ -795,11 +795,11 @@ public: /// This is included so that older tools can at least continue /// processing the layout past such things. //BLOCK_LAYOUT_OWNERSHIP_UNKNOWN = 7..10, - + /// All other opcodes are reserved. Halt interpretation and /// treat everything else as opaque. }; - + class RUN_SKIP { public: enum BLOCK_LAYOUT_OPCODE opcode; @@ -809,13 +809,13 @@ public: CharUnits BytePos = CharUnits::Zero(), CharUnits Size = CharUnits::Zero()) : opcode(Opcode), block_var_bytepos(BytePos), block_var_size(Size) {} - + // Allow sorting based on byte pos. bool operator<(const RUN_SKIP &b) const { return block_var_bytepos < b.block_var_bytepos; } }; - + protected: llvm::LLVMContext &VMContext; // FIXME! May not be needing this after all. @@ -871,7 +871,7 @@ protected: /// DefinedClasses - List of defined classes. SmallVector<llvm::GlobalValue*, 16> DefinedClasses; - + /// ImplementedClasses - List of @implemented classes. SmallVector<const ObjCInterfaceDecl*, 16> ImplementedClasses; @@ -952,28 +952,28 @@ protected: bool hasMRCWeakIvars) { return BuildIvarLayout(OI, beginOffset, endOffset, false, hasMRCWeakIvars); } - + Qualifiers::ObjCLifetime getBlockCaptureLifetime(QualType QT, bool ByrefLayout); - + void UpdateRunSkipBlockVars(bool IsByref, Qualifiers::ObjCLifetime LifeTime, CharUnits FieldOffset, CharUnits FieldSize); - + void BuildRCBlockVarRecordLayout(const RecordType *RT, CharUnits BytePos, bool &HasUnion, bool ByrefLayout=false); - + void BuildRCRecordLayout(const llvm::StructLayout *RecLayout, const RecordDecl *RD, ArrayRef<const FieldDecl*> RecFields, CharUnits BytePos, bool &HasUnion, bool ByrefLayout); - + uint64_t InlineLayoutInstruction(SmallVectorImpl<unsigned char> &Layout); - + llvm::Constant *getBitmapBlockLayout(bool ComputeByrefLayout); - + /// GetIvarLayoutName - Returns a unique constant for the given /// ivar layout bitmap. llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident, @@ -987,9 +987,9 @@ protected: const ObjCCommonTypesHelper &ObjCTypes, bool IsClassProperty); - /// EmitProtocolMethodTypes - Generate the array of extended method type + /// EmitProtocolMethodTypes - Generate the array of extended method type /// strings. The return value has type Int8PtrPtrTy. - llvm::Constant *EmitProtocolMethodTypes(Twine Name, + llvm::Constant *EmitProtocolMethodTypes(Twine Name, ArrayRef<llvm::Constant*> MethodTypes, const ObjCCommonTypesHelper &ObjCTypes); @@ -1205,7 +1205,7 @@ private: /// for the given class. llvm::Value *EmitClassRef(CodeGenFunction &CGF, const ObjCInterfaceDecl *ID); - + llvm::Value *EmitClassRefFromId(CodeGenFunction &CGF, IdentifierInfo *II); @@ -1382,7 +1382,7 @@ private: /// DefinedMetaClasses - List of defined meta-classes. std::vector<llvm::GlobalValue*> DefinedMetaClasses; - + /// isVTableDispatchedSelector - Returns true if SEL is a /// vtable-based selector. bool isVTableDispatchedSelector(Selector Sel); @@ -1453,7 +1453,7 @@ private: bool IsSuper, const CallArgList &CallArgs, const ObjCMethodDecl *Method); - + /// GetClassGlobal - Return the global variable for the Objective-C /// class of the given name. llvm::Constant *GetClassGlobal(StringRef Name, @@ -1467,7 +1467,7 @@ private: /// for the given class reference. llvm::Value *EmitClassRef(CodeGenFunction &CGF, const ObjCInterfaceDecl *ID); - + llvm::Value *EmitClassRefFromId(CodeGenFunction &CGF, IdentifierInfo *II, const ObjCInterfaceDecl *ID); @@ -1700,7 +1700,7 @@ struct NullReturnState { // Okay, start emitting the null-receiver block. CGF.EmitBlock(NullBB); - + // Release any consumed arguments we've got. if (Method) { CallArgList::const_iterator I = CallArgs.begin(); @@ -1709,7 +1709,7 @@ struct NullReturnState { const ParmVarDecl *ParamDecl = (*i); if (ParamDecl->hasAttr<NSConsumedAttr>()) { RValue RV = I->getRValue(CGF); - assert(RV.isScalar() && + assert(RV.isScalar() && "NullReturnState::complete - arg not on object"); CGF.EmitARCRelease(RV.getScalarVal(), ARCImpreciseLifetime); } @@ -1839,7 +1839,7 @@ llvm::Constant *CGObjCMac::GetEHType(QualType T) { } if (T->isObjCObjectPointerType()) return CGM.GetAddrOfRTTIDescriptor(T, /*ForEH=*/true); - + llvm_unreachable("asking for catch type for ObjC type in fragile runtime"); } @@ -1898,8 +1898,8 @@ llvm::Constant *CGObjCNonFragileABIMac::getNSConstantStringClassRef() { return cast<llvm::Constant>(V); auto &StringClass = CGM.getLangOpts().ObjCConstantStringClass; - std::string str = - StringClass.empty() ? "OBJC_CLASS_$_NSConstantString" + std::string str = + StringClass.empty() ? "OBJC_CLASS_$_NSConstantString" : "OBJC_CLASS_$_" + StringClass; auto GV = GetClassGlobal(str, NotForDefinition); @@ -2162,7 +2162,7 @@ CGObjCCommonMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF, if (RequiresNullCheck) { nullReturn.init(CGF, Arg0); } - + llvm::Instruction *CallSite; Fn = llvm::ConstantExpr::getBitCast(Fn, MSI.MessengerType); CGCallee Callee = CGCallee::forDirect(Fn); @@ -2202,17 +2202,17 @@ static Qualifiers::GC GetGCAttrTypeForType(ASTContext &Ctx, QualType FQT, } llvm_unreachable("bad objc ownership"); } - + // Treat unqualified retainable pointers as strong. if (FQT->isObjCObjectPointerType() || FQT->isBlockPointerType()) return Qualifiers::Strong; - + // Walk into C pointer types, but only in GC. if (Ctx.getLangOpts().getGC() != LangOptions::NonGC) { if (const PointerType *PT = FQT->getAs<PointerType>()) return GetGCAttrTypeForType(Ctx, PT->getPointeeType(), /*pointee*/ true); } - + return Qualifiers::GCNone; } @@ -2258,7 +2258,7 @@ namespace { void visitRecord(const RecordType *RT, CharUnits offset); template <class Iterator, class GetOffsetFn> - void visitAggregate(Iterator begin, Iterator end, + void visitAggregate(Iterator begin, Iterator end, CharUnits aggrOffset, const GetOffsetFn &getOffset); @@ -2287,7 +2287,7 @@ namespace { llvm::Constant *CGObjCCommonMac::BuildGCBlockLayout(CodeGenModule &CGM, const CGBlockInfo &blockInfo) { - + llvm::Constant *nullPtr = llvm::Constant::getNullValue(CGM.Int8PtrTy); if (CGM.getLangOpts().getGC() == LangOptions::NonGC) return nullPtr; @@ -2306,7 +2306,7 @@ llvm::Constant *CGObjCCommonMac::BuildGCBlockLayout(CodeGenModule &CGM, printf("\n block variable layout for block: "); builder.dump(buffer); } - + return C; } @@ -2351,7 +2351,7 @@ void IvarLayoutBuilder::visitBlock(const CGBlockInfo &blockInfo) { visitRecord(record, fieldOffset); continue; } - + Qualifiers::GC GCAttr = GetGCAttrTypeForType(CGM.getContext(), type); if (GCAttr == Qualifiers::Strong) { @@ -2374,11 +2374,11 @@ Qualifiers::ObjCLifetime CGObjCCommonMac::getBlockCaptureLifetime(QualType FQT, // If it doesn't, and this is ARC, it has no ownership. if (CGM.getLangOpts().ObjCAutoRefCount) return Qualifiers::OCL_None; - + // In MRC, retainable pointers are owned by non-__block variables. if (FQT->isObjCObjectPointerType() || FQT->isBlockPointerType()) return ByrefLayout ? Qualifiers::OCL_ExplicitNone : Qualifiers::OCL_Strong; - + return Qualifiers::OCL_None; } @@ -2416,11 +2416,11 @@ void CGObjCCommonMac::BuildRCRecordLayout(const llvm::StructLayout *RecLayout, const FieldDecl *LastFieldBitfieldOrUnnamed = nullptr; CharUnits MaxFieldOffset = CharUnits::Zero(); CharUnits LastBitfieldOrUnnamedOffset = CharUnits::Zero(); - + if (RecFields.empty()) return; unsigned ByteSizeInBits = CGM.getTarget().getCharWidth(); - + for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { const FieldDecl *Field = RecFields[i]; // Note that 'i' here is actually the field index inside RD of Field, @@ -2428,7 +2428,7 @@ void CGObjCCommonMac::BuildRCRecordLayout(const llvm::StructLayout *RecLayout, const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); CharUnits FieldOffset = CGM.getContext().toCharUnitsFromBits(RL.getFieldOffset(i)); - + // Skip over unnamed or bitfields if (!Field->getIdentifier() || Field->isBitField()) { LastFieldBitfieldOrUnnamed = Field; @@ -2441,12 +2441,12 @@ void CGObjCCommonMac::BuildRCRecordLayout(const llvm::StructLayout *RecLayout, if (FQT->isRecordType() || FQT->isUnionType()) { if (FQT->isUnionType()) HasUnion = true; - + BuildRCBlockVarRecordLayout(FQT->getAs<RecordType>(), BytePos + FieldOffset, HasUnion); continue; } - + if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) { const ConstantArrayType *CArray = dyn_cast_or_null<ConstantArrayType>(Array); @@ -2464,7 +2464,7 @@ void CGObjCCommonMac::BuildRCRecordLayout(const llvm::StructLayout *RecLayout, const RecordType *RT = FQT->getAs<RecordType>(); BuildRCBlockVarRecordLayout(RT, BytePos + FieldOffset, HasUnion); - + // Replicate layout information for each array element. Note that // one element is already done. uint64_t ElIx = 1; @@ -2494,7 +2494,7 @@ void CGObjCCommonMac::BuildRCRecordLayout(const llvm::StructLayout *RecLayout, FieldSize); } } - + if (LastFieldBitfieldOrUnnamed) { if (LastFieldBitfieldOrUnnamed->isBitField()) { // Last field was a bitfield. Must update the info. @@ -2521,7 +2521,7 @@ void CGObjCCommonMac::BuildRCRecordLayout(const llvm::StructLayout *RecLayout, FieldSize); } } - + if (MaxField) UpdateRunSkipBlockVars(false, getBlockCaptureLifetime(MaxField->getType(), ByrefLayout), @@ -2538,7 +2538,7 @@ void CGObjCCommonMac::BuildRCBlockVarRecordLayout(const RecordType *RT, llvm::Type *Ty = CGM.getTypes().ConvertType(QualType(RT, 0)); const llvm::StructLayout *RecLayout = CGM.getDataLayout().getStructLayout(cast<llvm::StructType>(Ty)); - + BuildRCRecordLayout(RecLayout, RD, Fields, BytePos, HasUnion, ByrefLayout); } @@ -2580,7 +2580,7 @@ uint64_t CGObjCCommonMac::InlineLayoutInstruction( else return 0; break; - + case 2: inst = Layout[0]; opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4); @@ -2607,7 +2607,7 @@ uint64_t CGObjCCommonMac::InlineLayoutInstruction( else return 0; break; - + case 1: inst = Layout[0]; opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4); @@ -2620,20 +2620,20 @@ uint64_t CGObjCCommonMac::InlineLayoutInstruction( else return 0; break; - + default: return 0; } - + // Cannot inline when any of the word counts is 15. Because this is one less // than the actual work count (so 15 means 16 actual word counts), // and we can only display 0 thru 15 word counts. if (strong_word_count == 16 || byref_word_count == 16 || weak_word_count == 16) return 0; - + unsigned count = (strong_word_count != 0) + (byref_word_count != 0) + (weak_word_count != 0); - + if (size == count) { if (strong_word_count) Result = strong_word_count; @@ -2655,12 +2655,12 @@ llvm::Constant *CGObjCCommonMac::getBitmapBlockLayout(bool ComputeByrefLayout) { unsigned WordSizeInBits = CGM.getTarget().getPointerWidth(0); unsigned ByteSizeInBits = CGM.getTarget().getCharWidth(); unsigned WordSizeInBytes = WordSizeInBits/ByteSizeInBits; - + // Sort on byte position; captures might not be allocated in order, // and unions can do funny things. llvm::array_pod_sort(RunSkipBlockVars.begin(), RunSkipBlockVars.end()); SmallVector<unsigned char, 16> Layout; - + unsigned size = RunSkipBlockVars.size(); for (unsigned i = 0; i < size; i++) { enum BLOCK_LAYOUT_OPCODE opcode = RunSkipBlockVars[i].opcode; @@ -2689,7 +2689,7 @@ llvm::Constant *CGObjCCommonMac::getBitmapBlockLayout(bool ComputeByrefLayout) { size_in_bytes -= residue_in_bytes; opcode = BLOCK_LAYOUT_NON_OBJECT_WORDS; } - + unsigned size_in_words = size_in_bytes.getQuantity() / WordSizeInBytes; while (size_in_words >= 16) { // Note that value in imm. is one less that the actual @@ -2710,7 +2710,7 @@ llvm::Constant *CGObjCCommonMac::getBitmapBlockLayout(bool ComputeByrefLayout) { Layout.push_back(inst); } } - + while (!Layout.empty()) { unsigned char inst = Layout.back(); enum BLOCK_LAYOUT_OPCODE opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4); @@ -2719,7 +2719,7 @@ llvm::Constant *CGObjCCommonMac::getBitmapBlockLayout(bool ComputeByrefLayout) { else break; } - + uint64_t Result = InlineLayoutInstruction(Layout); if (Result != 0) { // Block variable layout instruction has been inlined. @@ -2739,13 +2739,13 @@ llvm::Constant *CGObjCCommonMac::getBitmapBlockLayout(bool ComputeByrefLayout) { } return llvm::ConstantInt::get(CGM.IntPtrTy, Result); } - + unsigned char inst = (BLOCK_LAYOUT_OPERATOR << 4) | 0; Layout.push_back(inst); std::string BitMap; for (unsigned i = 0, e = Layout.size(); i != e; i++) BitMap += Layout[i]; - + if (CGM.getLangOpts().ObjCGCBitmapPrint) { if (ComputeByrefLayout) printf("\n Byref variable layout: "); @@ -2798,20 +2798,20 @@ llvm::Constant *CGObjCCommonMac::getBitmapBlockLayout(bool ComputeByrefLayout) { llvm::Constant *CGObjCCommonMac::BuildRCBlockLayout(CodeGenModule &CGM, const CGBlockInfo &blockInfo) { assert(CGM.getLangOpts().getGC() == LangOptions::NonGC); - + RunSkipBlockVars.clear(); bool hasUnion = false; - + unsigned WordSizeInBits = CGM.getTarget().getPointerWidth(0); unsigned ByteSizeInBits = CGM.getTarget().getCharWidth(); unsigned WordSizeInBytes = WordSizeInBits/ByteSizeInBits; - + const BlockDecl *blockDecl = blockInfo.getBlockDecl(); - + // Calculate the basic layout of the block structure. const llvm::StructLayout *layout = CGM.getDataLayout().getStructLayout(blockInfo.StructureType); - + // Ignore the optional 'this' capture: C++ objects are not assumed // to be GC'ed. if (blockInfo.BlockHeaderForcedGapSize != CharUnits::Zero()) @@ -2822,15 +2822,15 @@ llvm::Constant *CGObjCCommonMac::BuildRCBlockLayout(CodeGenModule &CGM, for (const auto &CI : blockDecl->captures()) { const VarDecl *variable = CI.getVariable(); QualType type = variable->getType(); - + const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable); - + // Ignore constant captures. if (capture.isConstant()) continue; - + CharUnits fieldOffset = CharUnits::fromQuantity(layout->getElementOffset(capture.getIndex())); - + assert(!type->isArrayType() && "array variable should not be caught"); if (!CI.isByRef()) if (const RecordType *record = type->getAs<RecordType>()) { @@ -2891,7 +2891,7 @@ void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) { llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) { if (DefinedProtocols.count(PD->getIdentifier())) return GetOrEmitProtocol(PD); - + return GetOrEmitProtocolRef(PD); } @@ -3094,12 +3094,12 @@ CGObjCMac::EmitProtocolList(Twine name, return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy); } -static void +static void PushProtocolProperties(llvm::SmallPtrSet<const IdentifierInfo*,16> &PropertySet, SmallVectorImpl<const ObjCPropertyDecl *> &Properties, const ObjCProtocolDecl *Proto, bool IsClassProperty) { - for (const auto *P : Proto->protocols()) + for (const auto *P : Proto->protocols()) PushProtocolProperties(PropertySet, Properties, P, IsClassProperty); for (const auto *PD : Proto->properties()) { @@ -3679,7 +3679,7 @@ llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID, auto countSlot = ivarList.addPlaceholder(); auto ivars = ivarList.beginArray(ObjCTypes.IvarTy); - for (const ObjCIvarDecl *IVD = OID->all_declared_ivar_begin(); + for (const ObjCIvarDecl *IVD = OID->all_declared_ivar_begin(); IVD; IVD = IVD->getNextIvar()) { // Ignore unnamed bit-fields. if (!IVD->getDeclName()) @@ -3964,7 +3964,7 @@ llvm::Constant *CGObjCMac::GetPropertySetFunction() { return ObjCTypes.getSetPropertyFn(); } -llvm::Constant *CGObjCMac::GetOptimizedPropertySetFunction(bool atomic, +llvm::Constant *CGObjCMac::GetOptimizedPropertySetFunction(bool atomic, bool copy) { return ObjCTypes.getOptimizedSetPropertyFn(atomic, copy); } @@ -4959,9 +4959,9 @@ llvm::Constant *CGObjCMac::EmitModuleSymbols() { llvm::Value *CGObjCMac::EmitClassRefFromId(CodeGenFunction &CGF, IdentifierInfo *II) { LazySymbols.insert(II); - + llvm::GlobalVariable *&Entry = ClassReferences[II]; - + if (!Entry) { llvm::Constant *Casted = llvm::ConstantExpr::getBitCast(GetClassName(II->getName()), @@ -4971,7 +4971,7 @@ llvm::Value *CGObjCMac::EmitClassRefFromId(CodeGenFunction &CGF, "__OBJC,__cls_refs,literal_pointers,no_dead_strip", CGM.getPointerAlign(), true); } - + return CGF.Builder.CreateAlignedLoad(Entry, CGF.getPointerAlign()); } @@ -5056,7 +5056,7 @@ void IvarLayoutBuilder::visitRecord(const RecordType *RT, } template <class Iterator, class GetOffsetFn> -void IvarLayoutBuilder::visitAggregate(Iterator begin, Iterator end, +void IvarLayoutBuilder::visitAggregate(Iterator begin, Iterator end, CharUnits aggregateOffset, const GetOffsetFn &getOffset) { for (; begin != end; ++begin) { @@ -5317,7 +5317,7 @@ CGObjCCommonMac::BuildIvarLayout(const ObjCImplementationDecl *OMD, // MRC weak layout strings follow the ARC style. CharUnits baseOffset; if (CGM.getLangOpts().getGC() == LangOptions::NonGC) { - for (const ObjCIvarDecl *IVD = OI->all_declared_ivar_begin(); + for (const ObjCIvarDecl *IVD = OI->all_declared_ivar_begin(); IVD; IVD = IVD->getNextIvar()) ivars.push_back(IVD); @@ -5353,7 +5353,7 @@ CGObjCCommonMac::BuildIvarLayout(const ObjCImplementationDecl *OMD, llvm::SmallVector<unsigned char, 4> buffer; llvm::Constant *C = builder.buildBitmap(*this, buffer); - + if (CGM.getLangOpts().ObjCGCBitmapPrint && !buffer.empty()) { printf("\n%s ivar layout for class '%s': ", ForStrongLayout ? "strong" : "weak", @@ -5903,7 +5903,7 @@ ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModul // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t* SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy); - + // struct objc_typeinfo { // const void** vtable; // objc_ehtype_vtable + 2 @@ -6033,7 +6033,7 @@ bool CGObjCNonFragileABIMac::isVTableDispatchedSelector(Selector Sel) { if (CGM.getLangOpts().getGC() != LangOptions::NonGC) { VTableDispatchMethods.insert(GetNullarySelector("hash")); VTableDispatchMethods.insert(GetUnarySelector("addObject")); - + // "countByEnumeratingWithState:objects:count" IdentifierInfo *KeyIdents[] = { &CGM.getContext().Idents.get("countByEnumeratingWithState"), @@ -6418,12 +6418,12 @@ llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CodeGenFunction &CGF, void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) { const ObjCInterfaceDecl *Interface = OCD->getClassInterface(); const char *Prefix = "\01l_OBJC_$_CATEGORY_"; - + llvm::SmallString<64> ExtCatName(Prefix); ExtCatName += Interface->getObjCRuntimeNameAsString(); ExtCatName += "_$_"; ExtCatName += OCD->getNameAsString(); - + ConstantInitBuilder builder(CGM); auto values = builder.beginStruct(ObjCTypes.CategorynfABITy); values.add(GetClassName(OCD->getIdentifier()->getName())); @@ -6684,7 +6684,7 @@ llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList( // FIXME. Consolidate this with similar code in GenerateClass. - for (const ObjCIvarDecl *IVD = OID->all_declared_ivar_begin(); + for (const ObjCIvarDecl *IVD = OID->all_declared_ivar_begin(); IVD; IVD = IVD->getNextIvar()) { // Ignore unnamed bit-fields. if (!IVD->getDeclName()) @@ -6785,7 +6785,7 @@ llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol( // Use the protocol definition, if there is one. if (const ObjCProtocolDecl *Def = PD->getDefinition()) PD = Def; - + auto methodLists = ProtocolMethodLists::get(PD); ConstantInitBuilder builder(CGM); @@ -6824,7 +6824,7 @@ llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol( values.add(EmitPropertyList( "\01l_OBJC_$_CLASS_PROP_LIST_" + PD->getObjCRuntimeNameAsString(), nullptr, PD, ObjCTypes, true)); - + if (Entry) { // Already created, fix the linkage and update the initializer. Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage); @@ -7058,7 +7058,7 @@ CGObjCNonFragileABIMac::EmitVTableMessageSend(CodeGenFunction &CGF, messageRef->setVisibility(llvm::GlobalValue::HiddenVisibility); messageRef->setSection(GetSectionName("__objc_msgrefs", "coalesced")); } - + bool requiresnullCheck = false; if (CGM.getLangOpts().ObjCAutoRefCount && method) for (const auto *ParamDecl : method->parameters()) { @@ -7069,7 +7069,7 @@ CGObjCNonFragileABIMac::EmitVTableMessageSend(CodeGenFunction &CGF, break; } } - + Address mref = Address(CGF.Builder.CreateBitCast(messageRef, ObjCTypes.MessageRefPtrTy), CGF.getPointerAlign()); @@ -7153,7 +7153,7 @@ CGObjCNonFragileABIMac::EmitClassRefFromId(CodeGenFunction &CGF, const ObjCInterfaceDecl *ID) { CharUnits Align = CGF.getPointerAlign(); llvm::GlobalVariable *&Entry = ClassReferences[II]; - + if (!Entry) { llvm::Constant *ClassGV; if (ID) { @@ -7243,7 +7243,7 @@ llvm::Value *CGObjCNonFragileABIMac::GetClass(CodeGenFunction &CGF, assert(!isa<llvm::GlobalVariable>(ClassGV) || cast<llvm::GlobalVariable>(ClassGV)->hasExternalWeakLinkage()); } - + return EmitClassRef(CGF, ID); } @@ -7304,7 +7304,7 @@ llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CodeGenFunction &CGF, Address Addr = EmitSelectorAddr(CGF, Sel); llvm::LoadInst* LI = CGF.Builder.CreateLoad(Addr); - LI->setMetadata(CGM.getModule().getMDKindID("invariant.load"), + LI->setMetadata(CGM.getModule().getMDKindID("invariant.load"), llvm::MDNode::get(VMContext, None)); return LI; } diff --git a/lib/CodeGen/CGObjCRuntime.cpp b/lib/CodeGen/CGObjCRuntime.cpp index 2f886fd82caa..a43885c0f9a2 100644 --- a/lib/CodeGen/CGObjCRuntime.cpp +++ b/lib/CodeGen/CGObjCRuntime.cpp @@ -181,7 +181,7 @@ void CGObjCRuntime::EmitTryCatchStmt(CodeGenFunction &CGF, for (unsigned I = 0, E = Handlers.size(); I != E; ++I) Catch->setHandler(I, Handlers[I].TypeInfo, Handlers[I].Block); } - + // Emit the try body. CGF.EmitStmt(S.getTryBody()); @@ -232,7 +232,7 @@ void CGObjCRuntime::EmitTryCatchStmt(CodeGenFunction &CGF, cleanups.ForceCleanup(); CGF.EmitBranchThroughCleanup(Cont); - } + } // Go back to the try-statement fallthrough. CGF.Builder.restoreIP(SavedIP); diff --git a/lib/CodeGen/CGObjCRuntime.h b/lib/CodeGen/CGObjCRuntime.h index a14b44abf413..ce082a61eb5e 100644 --- a/lib/CodeGen/CGObjCRuntime.h +++ b/lib/CodeGen/CGObjCRuntime.h @@ -143,7 +143,7 @@ public: /// Generate a constant string object. virtual ConstantAddress GenerateConstantString(const StringLiteral *) = 0; - + /// Generate a category. A category contains a list of methods (and /// accompanying metadata) and a list of protocols. virtual void GenerateCategory(const ObjCCategoryImplDecl *OCD) = 0; @@ -211,7 +211,7 @@ public: virtual llvm::Constant *GetPropertySetFunction() = 0; /// Return the runtime function for optimized setting properties. - virtual llvm::Constant *GetOptimizedPropertySetFunction(bool atomic, + virtual llvm::Constant *GetOptimizedPropertySetFunction(bool atomic, bool copy) = 0; // API for atomic copying of qualified aggregates in getter. @@ -224,17 +224,17 @@ public: /// API for atomic copying of qualified aggregates with non-trivial copy /// assignment (c++) in getter. virtual llvm::Constant *GetCppAtomicObjectGetFunction() = 0; - + /// GetClass - Return a reference to the class for the given /// interface decl. virtual llvm::Value *GetClass(CodeGenFunction &CGF, const ObjCInterfaceDecl *OID) = 0; - - + + virtual llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) { llvm_unreachable("autoreleasepool unsupported in this ABI"); } - + /// EnumerationMutationFunction - Return the function that's called by the /// compiler when a mutation is detected during foreach iteration. virtual llvm::Constant *EnumerationMutationFunction() = 0; diff --git a/lib/CodeGen/CGOpenMPRuntime.cpp b/lib/CodeGen/CGOpenMPRuntime.cpp index 3730b9af12fa..fa850155df4f 100644 --- a/lib/CodeGen/CGOpenMPRuntime.cpp +++ b/lib/CodeGen/CGOpenMPRuntime.cpp @@ -3750,11 +3750,13 @@ CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() { StringRef T = Device.getTriple(); std::string BeginName = getName({"omp_offloading", "img_start", ""}); auto *ImgBegin = new llvm::GlobalVariable( - M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage, + M, CGM.Int8Ty, /*isConstant=*/true, + llvm::GlobalValue::ExternalWeakLinkage, /*Initializer=*/nullptr, Twine(BeginName).concat(T)); std::string EndName = getName({"omp_offloading", "img_end", ""}); auto *ImgEnd = new llvm::GlobalVariable( - M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage, + M, CGM.Int8Ty, /*isConstant=*/true, + llvm::GlobalValue::ExternalWeakLinkage, /*Initializer=*/nullptr, Twine(EndName).concat(T)); llvm::Constant *Data[] = {ImgBegin, ImgEnd, HostEntriesBegin, @@ -8109,6 +8111,19 @@ void CGOpenMPRuntime::registerTargetGlobalVariable(const VarDecl *VD, VarName = CGM.getMangledName(VD); VarSize = CGM.getContext().getTypeSizeInChars(VD->getType()); Linkage = CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false); + // Temp solution to prevent optimizations of the internal variables. + if (CGM.getLangOpts().OpenMPIsDevice && !VD->isExternallyVisible()) { + std::string RefName = getName({VarName, "ref"}); + if (!CGM.GetGlobalValue(RefName)) { + llvm::Constant *AddrRef = + getOrCreateInternalVariable(Addr->getType(), RefName); + auto *GVAddrRef = cast<llvm::GlobalVariable>(AddrRef); + GVAddrRef->setConstant(/*Val=*/true); + GVAddrRef->setLinkage(llvm::GlobalValue::InternalLinkage); + GVAddrRef->setInitializer(Addr); + CGM.addCompilerUsedGlobal(GVAddrRef); + } + } break; case OMPDeclareTargetDeclAttr::MT_Link: Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryLink; diff --git a/lib/CodeGen/CGRecordLayoutBuilder.cpp b/lib/CodeGen/CGRecordLayoutBuilder.cpp index 4ee6c8e71457..58aaae692552 100644 --- a/lib/CodeGen/CGRecordLayoutBuilder.cpp +++ b/lib/CodeGen/CGRecordLayoutBuilder.cpp @@ -166,7 +166,7 @@ struct CGRecordLowering { return Layout.getFieldOffset(FD->getFieldIndex()); } // Layout routines. - void setBitFieldInfo(const FieldDecl *FD, CharUnits StartOffset, + void setBitFieldInfo(const FieldDecl *FD, CharUnits StartOffset, llvm::Type *StorageType); /// Lowers an ASTRecordLayout to a llvm type. void lower(bool NonVirtualBaseType); @@ -246,7 +246,7 @@ void CGRecordLowering::lower(bool NVBaseType) { // 1) Store all members (fields and bases) in a list and sort them by offset. // 2) Add a 1-byte capstone member at the Size of the structure. // 3) Clip bitfield storages members if their tail padding is or might be - // used by another field or base. The clipping process uses the capstone + // used by another field or base. The clipping process uses the capstone // by treating it as another object that occurs after the record. // 4) Determine if the llvm-struct requires packing. It's important that this // phase occur after clipping, because clipping changes the llvm type. @@ -313,9 +313,8 @@ void CGRecordLowering::lowerUnion() { if (!SeenNamedMember) { SeenNamedMember = Field->getIdentifier(); if (!SeenNamedMember) - if (const auto *FieldRD = - dyn_cast_or_null<RecordDecl>(Field->getType()->getAsTagDecl())) - SeenNamedMember = FieldRD->findFirstNamedDataMember(); + if (const auto *FieldRD = Field->getType()->getAsRecordDecl()) + SeenNamedMember = FieldRD->findFirstNamedDataMember(); if (SeenNamedMember && !isZeroInitializable(Field)) { IsZeroInitializable = IsZeroInitializableAsBase = false; StorageType = FieldType; @@ -437,7 +436,7 @@ CGRecordLowering::accumulateBitFields(RecordDecl::field_iterator Field, StartBitOffset = getFieldBitOffset(*Field); Tail = StartBitOffset + Field->getBitWidthValue(Context); StartFieldAsSingleRun = IsBetterAsSingleFieldRun(Tail - StartBitOffset, - StartBitOffset); + StartBitOffset); } ++Field; continue; @@ -687,7 +686,7 @@ CGBitFieldInfo CGBitFieldInfo::MakeInfo(CodeGenTypes &Types, uint64_t Offset, uint64_t Size, uint64_t StorageSize, CharUnits StorageOffset) { - // This function is vestigial from CGRecordLayoutBuilder days but is still + // This function is vestigial from CGRecordLayoutBuilder days but is still // used in GCObjCRuntime.cpp. That usage has a "fixme" attached to it that // when addressed will allow for the removal of this function. llvm::Type *Ty = Types.ConvertTypeForMem(FD->getType()); @@ -782,14 +781,14 @@ CGRecordLayout *CodeGenTypes::ComputeRecordLayout(const RecordDecl *D, if (BaseTy) { CharUnits NonVirtualSize = Layout.getNonVirtualSize(); - uint64_t AlignedNonVirtualTypeSizeInBits = + uint64_t AlignedNonVirtualTypeSizeInBits = getContext().toBits(NonVirtualSize); - assert(AlignedNonVirtualTypeSizeInBits == + assert(AlignedNonVirtualTypeSizeInBits == getDataLayout().getTypeAllocSizeInBits(BaseTy) && "Type size mismatch!"); } - + // Verify that the LLVM and AST field offsets agree. llvm::StructType *ST = RL->getLLVMType(); const llvm::StructLayout *SL = getDataLayout().getStructLayout(ST); @@ -807,7 +806,7 @@ CGRecordLayout *CodeGenTypes::ComputeRecordLayout(const RecordDecl *D, "Invalid field offset!"); continue; } - + // Ignore unnamed bit-fields. if (!FD->getDeclName()) continue; @@ -854,7 +853,7 @@ void CGRecordLayout::print(raw_ostream &OS) const { OS << "<CGRecordLayout\n"; OS << " LLVMType:" << *CompleteObjectType << "\n"; if (BaseSubobjectType) - OS << " NonVirtualBaseLLVMType:" << *BaseSubobjectType << "\n"; + OS << " NonVirtualBaseLLVMType:" << *BaseSubobjectType << "\n"; OS << " IsZeroInitializable:" << IsZeroInitializable << "\n"; OS << " BitFields:[\n"; diff --git a/lib/CodeGen/CGVTT.cpp b/lib/CodeGen/CGVTT.cpp index 41c8c943f54d..b0a3a0bffa2e 100644 --- a/lib/CodeGen/CGVTT.cpp +++ b/lib/CodeGen/CGVTT.cpp @@ -30,8 +30,8 @@ GetAddrOfVTTVTable(CodeGenVTables &CGVT, CodeGenModule &CGM, // This is a regular vtable. return CGM.getCXXABI().getAddrOfVTable(MostDerivedClass, CharUnits()); } - - return CGVT.GenerateConstructionVTable(MostDerivedClass, + + return CGVT.GenerateConstructionVTable(MostDerivedClass, VTable.getBaseSubobject(), VTable.isVirtual(), Linkage, @@ -45,7 +45,7 @@ CodeGenVTables::EmitVTTDefinition(llvm::GlobalVariable *VTT, VTTBuilder Builder(CGM.getContext(), RD, /*GenerateDefinition=*/true); llvm::Type *Int8PtrTy = CGM.Int8PtrTy, *Int32Ty = CGM.Int32Ty; - llvm::ArrayType *ArrayType = + llvm::ArrayType *ArrayType = llvm::ArrayType::get(Int8PtrTy, Builder.getVTTComponents().size()); SmallVector<llvm::GlobalVariable *, 8> VTables; @@ -117,42 +117,42 @@ llvm::GlobalVariable *CodeGenVTables::GetAddrOfVTT(const CXXRecordDecl *RD) { VTTBuilder Builder(CGM.getContext(), RD, /*GenerateDefinition=*/false); - llvm::ArrayType *ArrayType = + llvm::ArrayType *ArrayType = llvm::ArrayType::get(CGM.Int8PtrTy, Builder.getVTTComponents().size()); llvm::GlobalVariable *GV = - CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType, + CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType, llvm::GlobalValue::ExternalLinkage); GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); return GV; } -uint64_t CodeGenVTables::getSubVTTIndex(const CXXRecordDecl *RD, +uint64_t CodeGenVTables::getSubVTTIndex(const CXXRecordDecl *RD, BaseSubobject Base) { BaseSubobjectPairTy ClassSubobjectPair(RD, Base); SubVTTIndiciesMapTy::iterator I = SubVTTIndicies.find(ClassSubobjectPair); if (I != SubVTTIndicies.end()) return I->second; - + VTTBuilder Builder(CGM.getContext(), RD, /*GenerateDefinition=*/false); for (llvm::DenseMap<BaseSubobject, uint64_t>::const_iterator I = - Builder.getSubVTTIndicies().begin(), + Builder.getSubVTTIndicies().begin(), E = Builder.getSubVTTIndicies().end(); I != E; ++I) { // Insert all indices. BaseSubobjectPairTy ClassSubobjectPair(RD, I->first); - + SubVTTIndicies.insert(std::make_pair(ClassSubobjectPair, I->second)); } - + I = SubVTTIndicies.find(ClassSubobjectPair); assert(I != SubVTTIndicies.end() && "Did not find index!"); - + return I->second; } -uint64_t +uint64_t CodeGenVTables::getSecondaryVirtualPointerIndex(const CXXRecordDecl *RD, BaseSubobject Base) { SecondaryVirtualPointerIndicesMapTy::iterator I = @@ -164,17 +164,17 @@ CodeGenVTables::getSecondaryVirtualPointerIndex(const CXXRecordDecl *RD, VTTBuilder Builder(CGM.getContext(), RD, /*GenerateDefinition=*/false); // Insert all secondary vpointer indices. - for (llvm::DenseMap<BaseSubobject, uint64_t>::const_iterator I = + for (llvm::DenseMap<BaseSubobject, uint64_t>::const_iterator I = Builder.getSecondaryVirtualPointerIndices().begin(), E = Builder.getSecondaryVirtualPointerIndices().end(); I != E; ++I) { std::pair<const CXXRecordDecl *, BaseSubobject> Pair = std::make_pair(RD, I->first); - + SecondaryVirtualPointerIndices.insert(std::make_pair(Pair, I->second)); } I = SecondaryVirtualPointerIndices.find(std::make_pair(RD, Base)); assert(I != SecondaryVirtualPointerIndices.end() && "Did not find index!"); - + return I->second; } diff --git a/lib/CodeGen/CGVTables.cpp b/lib/CodeGen/CGVTables.cpp index 5a2ec65f7763..cc334637a831 100644 --- a/lib/CodeGen/CGVTables.cpp +++ b/lib/CodeGen/CGVTables.cpp @@ -110,7 +110,7 @@ static RValue PerformReturnAdjustment(CodeGenFunction &CGF, return RValue::get(ReturnValue); } -/// This function clones a function's DISubprogram node and enters it into +/// This function clones a function's DISubprogram node and enters it into /// a value map with the intent that the map can be utilized by the cloner /// to short-circuit Metadata node mapping. /// Furthermore, the function resolves any DILocalVariable nodes referenced diff --git a/lib/CodeGen/CGVTables.h b/lib/CodeGen/CGVTables.h index a11474a15ea4..6377659e4cb3 100644 --- a/lib/CodeGen/CGVTables.h +++ b/lib/CodeGen/CGVTables.h @@ -40,7 +40,7 @@ class CodeGenVTables { typedef std::pair<const CXXRecordDecl *, BaseSubobject> BaseSubobjectPairTy; typedef llvm::DenseMap<BaseSubobjectPairTy, uint64_t> SubVTTIndiciesMapTy; - + /// SubVTTIndicies - Contains indices into the various sub-VTTs. SubVTTIndiciesMapTy SubVTTIndicies; @@ -87,21 +87,21 @@ public: /// getSubVTTIndex - Return the index of the sub-VTT for the base class of the /// given record decl. uint64_t getSubVTTIndex(const CXXRecordDecl *RD, BaseSubobject Base); - + /// getSecondaryVirtualPointerIndex - Return the index in the VTT where the /// virtual pointer for the given subobject is located. uint64_t getSecondaryVirtualPointerIndex(const CXXRecordDecl *RD, BaseSubobject Base); - /// GenerateConstructionVTable - Generate a construction vtable for the given + /// GenerateConstructionVTable - Generate a construction vtable for the given /// base subobject. llvm::GlobalVariable * - GenerateConstructionVTable(const CXXRecordDecl *RD, const BaseSubobject &Base, - bool BaseIsVirtual, + GenerateConstructionVTable(const CXXRecordDecl *RD, const BaseSubobject &Base, + bool BaseIsVirtual, llvm::GlobalVariable::LinkageTypes Linkage, VTableAddressPointsMapTy& AddressPoints); - + /// GetAddrOfVTT - Get the address of the VTT for the given record decl. llvm::GlobalVariable *GetAddrOfVTT(const CXXRecordDecl *RD); @@ -112,7 +112,7 @@ public: /// EmitThunks - Emit the associated thunks for the given global decl. void EmitThunks(GlobalDecl GD); - + /// GenerateClassData - Generate all the class data required to be /// generated upon definition of a KeyFunction. This includes the /// vtable, the RTTI data structure (if RTTI is enabled) and the VTT diff --git a/lib/CodeGen/CGValue.h b/lib/CodeGen/CGValue.h index 418bda1f41bb..0dcbea423ad7 100644 --- a/lib/CodeGen/CGValue.h +++ b/lib/CodeGen/CGValue.h @@ -197,7 +197,7 @@ class LValue { // objective-c's ivar bool Ivar:1; - + // objective-c's ivar is an array bool ObjIsArray:1; @@ -207,7 +207,7 @@ class LValue { // Lvalue is a global reference of an objective-c object bool GlobalObjCRef : 1; - + // Lvalue is a thread local reference bool ThreadLocalRef : 1; @@ -301,7 +301,7 @@ public: bool isVolatile() const { return Quals.hasVolatile(); } - + Expr *getBaseIvarExp() const { return BaseIvarExp; } void setBaseIvarExp(Expr *V) { BaseIvarExp = V; } @@ -452,7 +452,7 @@ class AggValueSlot { /// slot might require calling an appropriate Objective-C GC /// barrier. The exact interaction here is unnecessarily mysterious. bool ObjCGCFlag : 1; - + /// ZeroedFlag - This is set to true if the memory in the slot is /// known to be zero before the assignment into it. This means that /// zero fields don't need to be set. @@ -472,19 +472,27 @@ class AggValueSlot { /// evaluating an expression which constructs such an object. bool AliasedFlag : 1; - /// This is set to true if the tail padding of this slot might overlap + /// This is set to true if the tail padding of this slot might overlap /// another object that may have already been initialized (and whose /// value must be preserved by this initialization). If so, we may only /// store up to the dsize of the type. Otherwise we can widen stores to /// the size of the type. bool OverlapFlag : 1; + /// If is set to true, sanitizer checks are already generated for this address + /// or not required. For instance, if this address represents an object + /// created in 'new' expression, sanitizer checks for memory is made as a part + /// of 'operator new' emission and object constructor should not generate + /// them. + bool SanitizerCheckedFlag : 1; + public: enum IsAliased_t { IsNotAliased, IsAliased }; enum IsDestructed_t { IsNotDestructed, IsDestructed }; enum IsZeroed_t { IsNotZeroed, IsZeroed }; enum Overlap_t { DoesNotOverlap, MayOverlap }; enum NeedsGCBarriers_t { DoesNotNeedGCBarriers, NeedsGCBarriers }; + enum IsSanitizerChecked_t { IsNotSanitizerChecked, IsSanitizerChecked }; /// ignored - Returns an aggregate value slot indicating that the /// aggregate value is being ignored. @@ -509,7 +517,8 @@ public: NeedsGCBarriers_t needsGC, IsAliased_t isAliased, Overlap_t mayOverlap, - IsZeroed_t isZeroed = IsNotZeroed) { + IsZeroed_t isZeroed = IsNotZeroed, + IsSanitizerChecked_t isChecked = IsNotSanitizerChecked) { AggValueSlot AV; if (addr.isValid()) { AV.Addr = addr.getPointer(); @@ -524,6 +533,7 @@ public: AV.ZeroedFlag = isZeroed; AV.AliasedFlag = isAliased; AV.OverlapFlag = mayOverlap; + AV.SanitizerCheckedFlag = isChecked; return AV; } @@ -532,9 +542,10 @@ public: NeedsGCBarriers_t needsGC, IsAliased_t isAliased, Overlap_t mayOverlap, - IsZeroed_t isZeroed = IsNotZeroed) { + IsZeroed_t isZeroed = IsNotZeroed, + IsSanitizerChecked_t isChecked = IsNotSanitizerChecked) { return forAddr(LV.getAddress(), LV.getQuals(), isDestructed, needsGC, - isAliased, mayOverlap, isZeroed); + isAliased, mayOverlap, isZeroed, isChecked); } IsDestructed_t isExternallyDestructed() const { @@ -553,7 +564,7 @@ public: void setVolatile(bool flag) { Quals.setVolatile(flag); } - + Qualifiers::ObjCLifetime getObjCLifetime() const { return Quals.getObjCLifetime(); } @@ -586,6 +597,10 @@ public: return Overlap_t(OverlapFlag); } + bool isSanitizerChecked() const { + return SanitizerCheckedFlag; + } + RValue asRValue() const { if (isIgnored()) { return RValue::getIgnored(); diff --git a/lib/CodeGen/CodeGenAction.cpp b/lib/CodeGen/CodeGenAction.cpp index 7ca55070d4a0..d499364002f0 100644 --- a/lib/CodeGen/CodeGenAction.cpp +++ b/lib/CodeGen/CodeGenAction.cpp @@ -51,7 +51,7 @@ namespace clang { public: ClangDiagnosticHandler(const CodeGenOptions &CGOpts, BackendConsumer *BCon) : CodeGenOpts(CGOpts), BackendCon(BCon) {} - + bool handleDiagnostics(const DiagnosticInfo &DI) override; bool isAnalysisRemarkEnabled(StringRef PassName) const override { diff --git a/lib/CodeGen/CodeGenFunction.h b/lib/CodeGen/CodeGenFunction.h index 79870ed59c96..f9e284232972 100644 --- a/lib/CodeGen/CodeGenFunction.h +++ b/lib/CodeGen/CodeGenFunction.h @@ -116,6 +116,7 @@ enum TypeEvaluationKind { SANITIZER_CHECK(DynamicTypeCacheMiss, dynamic_type_cache_miss, 0) \ SANITIZER_CHECK(FloatCastOverflow, float_cast_overflow, 0) \ SANITIZER_CHECK(FunctionTypeMismatch, function_type_mismatch, 0) \ + SANITIZER_CHECK(ImplicitConversion, implicit_conversion, 0) \ SANITIZER_CHECK(InvalidBuiltin, invalid_builtin, 0) \ SANITIZER_CHECK(LoadInvalidValue, load_invalid_value, 0) \ SANITIZER_CHECK(MissingReturn, missing_return, 0) \ @@ -2490,13 +2491,15 @@ public: void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type, bool ForVirtualBase, bool Delegating, Address This, const CXXConstructExpr *E, - AggValueSlot::Overlap_t Overlap); + AggValueSlot::Overlap_t Overlap, + bool NewPointerIsChecked); void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type, bool ForVirtualBase, bool Delegating, Address This, CallArgList &Args, AggValueSlot::Overlap_t Overlap, - SourceLocation Loc); + SourceLocation Loc, + bool NewPointerIsChecked); /// Emit assumption load for all bases. Requires to be be called only on /// most-derived class and not under construction of the object. @@ -2513,12 +2516,14 @@ public: const ArrayType *ArrayTy, Address ArrayPtr, const CXXConstructExpr *E, + bool NewPointerIsChecked, bool ZeroInitialization = false); void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D, llvm::Value *NumElements, Address ArrayPtr, const CXXConstructExpr *E, + bool NewPointerIsChecked, bool ZeroInitialization = false); static Destroyer destroyCXXObject; diff --git a/lib/CodeGen/CodeGenModule.cpp b/lib/CodeGen/CodeGenModule.cpp index ecdf78d4b347..8c5e0df0969b 100644 --- a/lib/CodeGen/CodeGenModule.cpp +++ b/lib/CodeGen/CodeGenModule.cpp @@ -1431,7 +1431,7 @@ void CodeGenModule::setNonAliasAttributes(GlobalDecl GD, F->addAttributes(llvm::AttributeList::FunctionIndex, Attrs); } } - + if (const auto *CSA = D->getAttr<CodeSegAttr>()) GO->setSection(CSA->getName()); else if (const auto *SA = D->getAttr<SectionAttr>()) @@ -3176,6 +3176,10 @@ LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) { return LangAS::cuda_constant; else if (D && D->hasAttr<CUDASharedAttr>()) return LangAS::cuda_shared; + else if (D && D->hasAttr<CUDADeviceAttr>()) + return LangAS::cuda_device; + else if (D && D->getType().isConstQualified()) + return LangAS::cuda_constant; else return LangAS::cuda_device; } diff --git a/lib/CodeGen/CodeGenModule.h b/lib/CodeGen/CodeGenModule.h index ee64ed4f2ae2..91f3d94330f1 100644 --- a/lib/CodeGen/CodeGenModule.h +++ b/lib/CodeGen/CodeGenModule.h @@ -280,14 +280,14 @@ private: llvm::LLVMContext &VMContext; std::unique_ptr<CodeGenTBAA> TBAA; - + mutable std::unique_ptr<TargetCodeGenInfo> TheTargetCodeGenInfo; - + // This should not be moved earlier, since its initialization depends on some // of the previous reference members being already initialized and also checks // if TheTargetCodeGenInfo is NULL CodeGenTypes Types; - + /// Holds information about C++ vtables. CodeGenVTables VTables; @@ -415,7 +415,7 @@ private: /// order. Once the decl is emitted, the index is replaced with ~0U to ensure /// that we don't re-emit the initializer. llvm::DenseMap<const Decl*, unsigned> DelayedCXXInitPosition; - + typedef std::pair<OrderGlobalInits, llvm::Function*> GlobalInitData; struct GlobalInitPriorityCmp { @@ -452,7 +452,7 @@ private: /// The type used to describe the state of a fast enumeration in /// Objective-C's for..in loop. QualType ObjCFastEnumerationStateType; - + /// @} /// Lazily create the Objective-C runtime @@ -576,7 +576,7 @@ public: llvm::Constant *getStaticLocalDeclAddress(const VarDecl *D) { return StaticLocalDeclMap[D]; } - void setStaticLocalDeclAddress(const VarDecl *D, + void setStaticLocalDeclAddress(const VarDecl *D, llvm::Constant *C) { StaticLocalDeclMap[D] = C; } @@ -588,7 +588,7 @@ public: llvm::GlobalVariable *getStaticLocalDeclGuardAddress(const VarDecl *D) { return StaticLocalDeclGuardMap[D]; } - void setStaticLocalDeclGuardAddress(const VarDecl *D, + void setStaticLocalDeclGuardAddress(const VarDecl *D, llvm::GlobalVariable *C) { StaticLocalDeclGuardMap[D] = C; } @@ -649,10 +649,10 @@ public: bool shouldUseTBAA() const { return TBAA != nullptr; } - const TargetCodeGenInfo &getTargetCodeGenInfo(); - + const TargetCodeGenInfo &getTargetCodeGenInfo(); + CodeGenTypes &getTypes() { return Types; } - + CodeGenVTables &getVTables() { return VTables; } ItaniumVTableContext &getItaniumVTableContext() { @@ -852,7 +852,7 @@ public: /// Fetches the global unique block count. int getUniqueBlockCount() { return ++Block.GlobalUniqueCount; } - + /// Fetches the type of a generic block descriptor. llvm::Type *getBlockDescriptorType(); @@ -871,7 +871,7 @@ public: /// Notes that BE's global block is available via Addr. Asserts that BE /// isn't already emitted. void setAddrOfGlobalBlock(const BlockExpr *BE, llvm::Constant *Addr); - + /// Return a pointer to a constant CFString object for the given string. ConstantAddress GetAddrOfConstantCFString(const StringLiteral *Literal); @@ -1139,7 +1139,7 @@ public: /// Return the store size, in character units, of the given LLVM type. CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const; - + /// Returns LLVM linkage for a declarator. llvm::GlobalValue::LinkageTypes getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage, @@ -1316,7 +1316,7 @@ private: void emitCPUDispatchDefinition(GlobalDecl GD); void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D); void EmitObjCIvarInitializations(ObjCImplementationDecl *D); - + // C++ related functions. void EmitDeclContext(const DeclContext *DC); diff --git a/lib/CodeGen/CodeGenTypes.cpp b/lib/CodeGen/CodeGenTypes.cpp index 16ec1dd301aa..1a1395e6ae74 100644 --- a/lib/CodeGen/CodeGenTypes.cpp +++ b/lib/CodeGen/CodeGenTypes.cpp @@ -54,7 +54,7 @@ void CodeGenTypes::addRecordTypeName(const RecordDecl *RD, SmallString<256> TypeName; llvm::raw_svector_ostream OS(TypeName); OS << RD->getKindName() << '.'; - + // Name the codegen type after the typedef name // if there is no tag type name available if (RD->getIdentifier()) { @@ -100,7 +100,7 @@ llvm::Type *CodeGenTypes::ConvertTypeForMem(QualType T) { /// isRecordLayoutComplete - Return true if the specified type is already /// completely laid out. bool CodeGenTypes::isRecordLayoutComplete(const Type *Ty) const { - llvm::DenseMap<const Type*, llvm::StructType *>::const_iterator I = + llvm::DenseMap<const Type*, llvm::StructType *>::const_iterator I = RecordDeclTypes.find(Ty); return I != RecordDeclTypes.end() && !I->second->isOpaque(); } @@ -113,7 +113,7 @@ isSafeToConvert(QualType T, CodeGenTypes &CGT, /// isSafeToConvert - Return true if it is safe to convert the specified record /// decl to IR and lay it out, false if doing so would cause us to get into a /// recursive compilation mess. -static bool +static bool isSafeToConvert(const RecordDecl *RD, CodeGenTypes &CGT, llvm::SmallPtrSet<const RecordDecl*, 16> &AlreadyChecked) { // If we have already checked this type (maybe the same type is used by-value @@ -122,14 +122,14 @@ isSafeToConvert(const RecordDecl *RD, CodeGenTypes &CGT, return true; const Type *Key = CGT.getContext().getTagDeclType(RD).getTypePtr(); - + // If this type is already laid out, converting it is a noop. if (CGT.isRecordLayoutComplete(Key)) return true; - + // If this type is currently being laid out, we can't recursively compile it. if (CGT.isRecordBeingLaidOut(Key)) return false; - + // If this type would require laying out bases that are currently being laid // out, don't do it. This includes virtual base classes which get laid out // when a class is translated, even though they aren't embedded by-value into @@ -140,13 +140,13 @@ isSafeToConvert(const RecordDecl *RD, CodeGenTypes &CGT, CGT, AlreadyChecked)) return false; } - + // If this type would require laying out members that are currently being laid // out, don't do it. for (const auto *I : RD->fields()) if (!isSafeToConvert(I->getType(), CGT, AlreadyChecked)) return false; - + // If there are no problems, lets do it. return true; } @@ -170,7 +170,7 @@ isSafeToConvert(QualType T, CodeGenTypes &CGT, return isSafeToConvert(AT->getElementType(), CGT, AlreadyChecked); // Otherwise, there is no concern about transforming this. We only care about - // things that are contained by-value in a structure that can have another + // things that are contained by-value in a structure that can have another // structure as a member. return true; } @@ -182,7 +182,7 @@ isSafeToConvert(QualType T, CodeGenTypes &CGT, static bool isSafeToConvert(const RecordDecl *RD, CodeGenTypes &CGT) { // If no structs are being laid out, we can certainly do this one. if (CGT.noRecordsBeingLaidOut()) return true; - + llvm::SmallPtrSet<const RecordDecl*, 16> AlreadyChecked; return isSafeToConvert(RD, CGT, AlreadyChecked); } @@ -229,7 +229,7 @@ bool CodeGenTypes::isFuncParamTypeConvertible(QualType Ty) { bool CodeGenTypes::isFuncTypeConvertible(const FunctionType *FT) { if (!isFuncParamTypeConvertible(FT->getReturnType())) return false; - + if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) for (unsigned i = 0, e = FPT->getNumParams(); i != e; i++) if (!isFuncParamTypeConvertible(FPT->getParamType(i))) @@ -259,7 +259,7 @@ void CodeGenTypes::UpdateCompletedType(const TagDecl *TD) { DI->completeType(ED); return; } - + // If we completed a RecordDecl that we previously used and converted to an // anonymous type, then go ahead and complete it now. const RecordDecl *RD = cast<RecordDecl>(TD); @@ -388,7 +388,7 @@ llvm::Type *CodeGenTypes::ConvertType(QualType T) { // RecordTypes are cached and processed specially. if (const RecordType *RT = dyn_cast<RecordType>(Ty)) return ConvertRecordDeclType(RT->getDecl()); - + // See if type is already cached. llvm::DenseMap<const Type *, llvm::Type *>::iterator TCI = TypeCache.find(Ty); // If type is found in map then use it. Otherwise, convert type T. @@ -494,7 +494,7 @@ llvm::Type *CodeGenTypes::ConvertType(QualType T) { // Model std::nullptr_t as i8* ResultType = llvm::Type::getInt8PtrTy(getLLVMContext()); break; - + case BuiltinType::UInt128: case BuiltinType::Int128: ResultType = llvm::IntegerType::get(getLLVMContext(), 128); @@ -510,7 +510,7 @@ llvm::Type *CodeGenTypes::ConvertType(QualType T) { case BuiltinType::OCLReserveID: ResultType = CGM.getOpenCLRuntime().convertOpenCLSpecificType(Ty); break; - + case BuiltinType::Dependent: #define BUILTIN_TYPE(Id, SingletonId) #define PLACEHOLDER_TYPE(Id, SingletonId) \ @@ -574,8 +574,8 @@ llvm::Type *CodeGenTypes::ConvertType(QualType T) { case Type::ConstantArray: { const ConstantArrayType *A = cast<ConstantArrayType>(Ty); llvm::Type *EltTy = ConvertTypeForMem(A->getElementType()); - - // Lower arrays of undefined struct type to arrays of i8 just to have a + + // Lower arrays of undefined struct type to arrays of i8 just to have a // concrete type. if (!EltTy->isSized()) { SkippedLayout = true; @@ -674,9 +674,9 @@ llvm::Type *CodeGenTypes::ConvertType(QualType T) { break; } } - + assert(ResultType && "Didn't convert a type?"); - + TypeCache[Ty] = ResultType; return ResultType; } @@ -709,7 +709,7 @@ llvm::StructType *CodeGenTypes::ConvertRecordDeclType(const RecordDecl *RD) { RD = RD->getDefinition(); if (!RD || !RD->isCompleteDefinition() || !Ty->isOpaque()) return Ty; - + // If converting this type would cause us to infinitely loop, don't do it! if (!isSafeToConvert(RD, *this)) { DeferredRecords.push_back(RD); @@ -720,12 +720,12 @@ llvm::StructType *CodeGenTypes::ConvertRecordDeclType(const RecordDecl *RD) { bool InsertResult = RecordsBeingLaidOut.insert(Key).second; (void)InsertResult; assert(InsertResult && "Recursively compiling a struct?"); - + // Force conversion of non-virtual base classes recursively. if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { for (const auto &I : CRD->bases()) { if (I.isVirtual()) continue; - + ConvertRecordDeclType(I.getType()->getAs<RecordType>()->getDecl()); } } @@ -737,13 +737,13 @@ llvm::StructType *CodeGenTypes::ConvertRecordDeclType(const RecordDecl *RD) { // We're done laying out this struct. bool EraseResult = RecordsBeingLaidOut.erase(Key); (void)EraseResult; assert(EraseResult && "struct not in RecordsBeingLaidOut set?"); - + // If this struct blocked a FunctionType conversion, then recompute whatever // was derived from that. // FIXME: This is hugely overconservative. if (SkippedLayout) TypeCache.clear(); - + // If we're done converting the outer-most record, then convert any deferred // structs as well. if (RecordsBeingLaidOut.empty()) @@ -799,7 +799,7 @@ bool CodeGenTypes::isZeroInitializable(QualType T) { // We have to ask the ABI about member pointers. if (const MemberPointerType *MPT = T->getAs<MemberPointerType>()) return getCXXABI().isZeroInitializable(MPT); - + // Everything else is okay. return true; } diff --git a/lib/CodeGen/CodeGenTypes.h b/lib/CodeGen/CodeGenTypes.h index fb8d31684290..626869f00021 100644 --- a/lib/CodeGen/CodeGenTypes.h +++ b/lib/CodeGen/CodeGenTypes.h @@ -140,7 +140,7 @@ class CodeGenTypes { /// Contains the LLVM IR type for any converted RecordDecl. llvm::DenseMap<const Type*, llvm::StructType *> RecordDeclTypes; - + /// Hold memoized CGFunctionInfo results. llvm::FoldingSet<CGFunctionInfo> FunctionInfos; @@ -149,15 +149,15 @@ class CodeGenTypes { /// struct A { struct B { int x; } } when processing 'x', the 'A' and 'B' /// types will be in this set. llvm::SmallPtrSet<const Type*, 4> RecordsBeingLaidOut; - + llvm::SmallPtrSet<const CGFunctionInfo*, 4> FunctionsBeingProcessed; - + /// True if we didn't layout a function due to a being inside /// a recursive struct conversion, set this to true. bool SkippedLayout; SmallVector<const RecordDecl *, 8> DeferredRecords; - + /// This map keeps cache of llvm::Types and maps clang::Type to /// corresponding llvm::Type. llvm::DenseMap<const Type *, llvm::Type *> TypeCache; @@ -343,7 +343,7 @@ public: /// optional suffix and name the given LLVM type using it. void addRecordTypeName(const RecordDecl *RD, llvm::StructType *Ty, StringRef suffix); - + public: // These are internal details of CGT that shouldn't be used externally. /// ConvertRecordDeclType - Lay out a tagged decl type like struct or union. @@ -365,7 +365,7 @@ public: // These are internal details of CGT that shouldn't be used externally. /// IsZeroInitializable - Return whether a record type can be /// zero-initialized (in the C++ sense) with an LLVM zeroinitializer. bool isZeroInitializable(const RecordDecl *RD); - + bool isRecordLayoutComplete(const Type *Ty) const; bool noRecordsBeingLaidOut() const { return RecordsBeingLaidOut.empty(); @@ -373,7 +373,7 @@ public: // These are internal details of CGT that shouldn't be used externally. bool isRecordBeingLaidOut(const Type *Ty) const { return RecordsBeingLaidOut.count(Ty); } - + }; } // end namespace CodeGen diff --git a/lib/CodeGen/ConstantInitBuilder.cpp b/lib/CodeGen/ConstantInitBuilder.cpp index 7f8d80985032..59e66b88fb01 100644 --- a/lib/CodeGen/ConstantInitBuilder.cpp +++ b/lib/CodeGen/ConstantInitBuilder.cpp @@ -166,7 +166,7 @@ void ConstantAggregateBuilderBase::getGEPIndicesTo( if (Parent) { Parent->getGEPIndicesTo(indices, Begin); - // Otherwise, add an index to drill into the first level of pointer. + // Otherwise, add an index to drill into the first level of pointer. } else { assert(indices.empty()); indices.push_back(llvm::ConstantInt::get(Builder.CGM.Int32Ty, 0)); diff --git a/lib/CodeGen/ItaniumCXXABI.cpp b/lib/CodeGen/ItaniumCXXABI.cpp index 16fdd1c16a1d..00fff144b597 100644 --- a/lib/CodeGen/ItaniumCXXABI.cpp +++ b/lib/CodeGen/ItaniumCXXABI.cpp @@ -3744,22 +3744,12 @@ static StructorCodegen getCodegenToUse(CodeGenModule &CGM, } llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl); - // All discardable structors can be RAUWed, but we don't want to do that in - // unoptimized code, as that makes complete structor symbol disappear - // completely, which degrades debugging experience. - // Symbols with private linkage can be safely aliased, so we special case them - // here. - if (llvm::GlobalValue::isLocalLinkage(Linkage)) - return CGM.getCodeGenOpts().OptimizationLevel > 0 ? StructorCodegen::RAUW - : StructorCodegen::Alias; + if (llvm::GlobalValue::isDiscardableIfUnused(Linkage)) + return StructorCodegen::RAUW; - // Linkonce structors cannot be aliased nor placed in a comdat, so these need - // to be emitted separately. // FIXME: Should we allow available_externally aliases? - if (llvm::GlobalValue::isDiscardableIfUnused(Linkage) || - !llvm::GlobalAlias::isValidLinkage(Linkage)) - return CGM.getCodeGenOpts().OptimizationLevel > 0 ? StructorCodegen::RAUW - : StructorCodegen::Emit; + if (!llvm::GlobalAlias::isValidLinkage(Linkage)) + return StructorCodegen::RAUW; if (llvm::GlobalValue::isWeakForLinker(Linkage)) { // Only ELF and wasm support COMDATs with arbitrary names (C5/D5). diff --git a/lib/CodeGen/MicrosoftCXXABI.cpp b/lib/CodeGen/MicrosoftCXXABI.cpp index 81ed05059546..059adb78ca30 100644 --- a/lib/CodeGen/MicrosoftCXXABI.cpp +++ b/lib/CodeGen/MicrosoftCXXABI.cpp @@ -165,7 +165,7 @@ public: llvm::BasicBlock * EmitCtorCompleteObjectHandler(CodeGenFunction &CGF, const CXXRecordDecl *RD) override; - + llvm::BasicBlock * EmitDtorCompleteObjectHandler(CodeGenFunction &CGF); @@ -1123,7 +1123,7 @@ MicrosoftCXXABI::EmitDtorCompleteObjectHandler(CodeGenFunction &CGF) { CGF.EmitBlock(CallVbaseDtorsBB); // CGF will put the base dtor calls in this basic block for us later. - + return SkipVbaseDtorsBB; } @@ -1393,7 +1393,7 @@ Address MicrosoftCXXABI::adjustThisArgumentForVirtualFunctionCall( Address Result = This; if (ML.VBase) { Result = CGF.Builder.CreateElementBitCast(Result, CGF.Int8Ty); - + const CXXRecordDecl *Derived = MD->getParent(); const CXXRecordDecl *VBase = ML.VBase; llvm::Value *VBaseOffset = @@ -1562,21 +1562,21 @@ void MicrosoftCXXABI::EmitDestructorCall(CodeGenFunction &CGF, This = adjustThisArgumentForVirtualFunctionCall(CGF, GlobalDecl(DD, Type), This, false); } - + llvm::BasicBlock *BaseDtorEndBB = nullptr; if (ForVirtualBase && isa<CXXConstructorDecl>(CGF.CurCodeDecl)) { BaseDtorEndBB = EmitDtorCompleteObjectHandler(CGF); - } + } CGF.EmitCXXDestructorCall(DD, Callee, This.getPointer(), /*ImplicitParam=*/nullptr, /*ImplicitParamTy=*/QualType(), nullptr, getFromDtorType(Type)); if (BaseDtorEndBB) { - // Complete object handler should continue to be the remaining + // Complete object handler should continue to be the remaining CGF.Builder.CreateBr(BaseDtorEndBB); CGF.EmitBlock(BaseDtorEndBB); - } + } } void MicrosoftCXXABI::emitVTableTypeMetadata(const VPtrInfo &Info, diff --git a/lib/CodeGen/SwiftCallingConv.cpp b/lib/CodeGen/SwiftCallingConv.cpp index 3673a5597eac..b411a501ea81 100644 --- a/lib/CodeGen/SwiftCallingConv.cpp +++ b/lib/CodeGen/SwiftCallingConv.cpp @@ -163,7 +163,7 @@ void SwiftAggLowering::addTypedData(const RecordDecl *record, CharUnits begin, // - virtual bases for (auto &vbaseSpecifier : cxxRecord->vbases()) { auto baseRecord = vbaseSpecifier.getType()->getAsCXXRecordDecl(); - addTypedData(baseRecord, begin + layout.getVBaseClassOffset(baseRecord)); + addTypedData(baseRecord, begin + layout.getVBaseClassOffset(baseRecord)); } } } @@ -583,7 +583,7 @@ bool SwiftAggLowering::shouldPassIndirectly(bool asReturnValue) const { if (Entries.size() == 1) { return getSwiftABIInfo(CGM).shouldPassIndirectlyForSwift( Entries.back().Type, - asReturnValue); + asReturnValue); } SmallVector<llvm::Type*, 8> componentTys; diff --git a/lib/CodeGen/TargetInfo.cpp b/lib/CodeGen/TargetInfo.cpp index fa9b0a27af28..6f6c5f50c2e7 100644 --- a/lib/CodeGen/TargetInfo.cpp +++ b/lib/CodeGen/TargetInfo.cpp @@ -305,7 +305,7 @@ static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF, Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign), DirectAlign); } else { - Addr = Address(Ptr, SlotSize); + Addr = Address(Ptr, SlotSize); } // Advance the pointer past the argument, then store that back. @@ -369,7 +369,7 @@ static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr, } return Addr; - + } static Address emitMergePHI(CodeGenFunction &CGF, @@ -1014,7 +1014,7 @@ class X86_32ABIInfo : public SwiftABIInfo { ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const; ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const; - /// Updates the number of available free registers, returns + /// Updates the number of available free registers, returns /// true if any registers were allocated. bool updateFreeRegs(QualType Ty, CCState &State) const; @@ -1044,7 +1044,7 @@ public: bool RetSmallStructInRegABI, bool Win32StructABI, unsigned NumRegisterParameters, bool SoftFloatABI) : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI), - IsRetSmallStructInRegABI(RetSmallStructInRegABI), + IsRetSmallStructInRegABI(RetSmallStructInRegABI), IsWin32StructABI(Win32StructABI), IsSoftFloatABI(SoftFloatABI), IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()), @@ -1057,7 +1057,7 @@ public: // four vector registers for vectors, but those can overlap with the // scalar registers. return occupiesMoreThan(CGT, scalars, /*total*/ 3); - } + } bool isSwiftErrorInRegister() const override { // x86-32 lowering does not support passing swifterror in a register. @@ -1546,7 +1546,7 @@ bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const { return true; } -bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State, +bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg, bool &NeedsPadding) const { // On Windows, aggregates other than HFAs are never passed in registers, and @@ -1589,7 +1589,7 @@ bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const { if (getContext().getTypeSize(Ty) > 32) return false; - return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() || + return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() || Ty->isReferenceType()); } @@ -2185,7 +2185,7 @@ public: bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, bool asReturnValue) const override { return occupiesMoreThan(CGT, scalars, /*total*/ 4); - } + } bool isSwiftErrorInRegister() const override { return true; } @@ -3785,7 +3785,7 @@ Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false); RegAddr = Tmp; } - + } else if (neededSSE == 1) { RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset), CharUnits::fromQuantity(16)); @@ -4180,7 +4180,7 @@ Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList, } // Get the address of the saved value by scaling the number of - // registers we've used by the number of + // registers we've used by the number of CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8); llvm::Value *RegOffset = Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity())); @@ -4191,7 +4191,7 @@ Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList, // Increase the used-register count. NumRegs = - Builder.CreateAdd(NumRegs, + Builder.CreateAdd(NumRegs, Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1)); Builder.CreateStore(NumRegs, NumRegsAddr); @@ -4227,7 +4227,7 @@ Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList, OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align), Align); } - + MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy); // Increase the overflow area. @@ -5063,7 +5063,13 @@ ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const { if (getTarget().isRenderScriptTarget()) { return coerceToIntArray(Ty, getContext(), getVMContext()); } - unsigned Alignment = getContext().getTypeAlign(Ty); + unsigned Alignment; + if (Kind == AArch64ABIInfo::AAPCS) { + Alignment = getContext().getTypeUnadjustedAlign(Ty); + Alignment = Alignment < 128 ? 64 : 128; + } else { + Alignment = getContext().getTypeAlign(Ty); + } Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes // We use a pair of i64 for 16-byte aggregate with 8-byte alignment. @@ -5801,11 +5807,14 @@ ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, // most 8-byte. We realign the indirect argument if type alignment is bigger // than ABI alignment. uint64_t ABIAlign = 4; - uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8; + uint64_t TyAlign; if (getABIKind() == ARMABIInfo::AAPCS_VFP || - getABIKind() == ARMABIInfo::AAPCS) + getABIKind() == ARMABIInfo::AAPCS) { + TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity(); ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8); - + } else { + TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity(); + } if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) { assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval"); return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign), @@ -5824,7 +5833,7 @@ ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, unsigned SizeRegs; // FIXME: Try to match the types of the arguments more accurately where // we can. - if (getContext().getTypeAlign(Ty) <= 32) { + if (TyAlign <= 4) { ElemTy = llvm::Type::getInt32Ty(getVMContext()); SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32; } else { @@ -6985,8 +6994,14 @@ ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const { if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) RetTy = EnumTy->getDecl()->getIntegerType(); - return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy) - : ABIArgInfo::getDirect()); + if (RetTy->isPromotableIntegerType()) + return ABIArgInfo::getExtend(RetTy); + + if ((RetTy->isUnsignedIntegerOrEnumerationType() || + RetTy->isSignedIntegerOrEnumerationType()) && Size == 32 && !IsO32) + return ABIArgInfo::getSignExtend(RetTy); + + return ABIArgInfo::getDirect(); } void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const { diff --git a/lib/Driver/CMakeLists.txt b/lib/Driver/CMakeLists.txt index 471ffe0f1b00..2b03c9f7001f 100644 --- a/lib/Driver/CMakeLists.txt +++ b/lib/Driver/CMakeLists.txt @@ -57,6 +57,7 @@ add_clang_library(clangDriver ToolChains/NetBSD.cpp ToolChains/OpenBSD.cpp ToolChains/PS4CPU.cpp + ToolChains/RISCV.cpp ToolChains/Solaris.cpp ToolChains/TCE.cpp ToolChains/WebAssembly.cpp diff --git a/lib/Driver/Driver.cpp b/lib/Driver/Driver.cpp index 1dfcacc75ea5..952a716cb6e6 100644 --- a/lib/Driver/Driver.cpp +++ b/lib/Driver/Driver.cpp @@ -37,6 +37,7 @@ #include "ToolChains/NetBSD.h" #include "ToolChains/OpenBSD.h" #include "ToolChains/PS4CPU.h" +#include "ToolChains/RISCV.h" #include "ToolChains/Solaris.h" #include "ToolChains/TCE.h" #include "ToolChains/WebAssembly.h" @@ -4399,6 +4400,10 @@ const ToolChain &Driver::getToolChain(const ArgList &Args, case llvm::Triple::avr: TC = llvm::make_unique<toolchains::AVRToolChain>(*this, Target, Args); break; + case llvm::Triple::riscv32: + case llvm::Triple::riscv64: + TC = llvm::make_unique<toolchains::RISCVToolChain>(*this, Target, Args); + break; default: if (Target.getVendor() == llvm::Triple::Myriad) TC = llvm::make_unique<toolchains::MyriadToolChain>(*this, Target, diff --git a/lib/Driver/SanitizerArgs.cpp b/lib/Driver/SanitizerArgs.cpp index bdc17d11c92b..5d3e31567ce6 100644 --- a/lib/Driver/SanitizerArgs.cpp +++ b/lib/Driver/SanitizerArgs.cpp @@ -27,22 +27,22 @@ using namespace clang::driver; using namespace llvm::opt; enum : SanitizerMask { - NeedsUbsanRt = Undefined | Integer | Nullability | CFI, + NeedsUbsanRt = Undefined | Integer | ImplicitConversion | Nullability | CFI, NeedsUbsanCxxRt = Vptr | CFI, NotAllowedWithTrap = Vptr, NotAllowedWithMinimalRuntime = Vptr, RequiresPIE = DataFlow | HWAddress | Scudo, NeedsUnwindTables = Address | HWAddress | Thread | Memory | DataFlow, SupportsCoverage = Address | HWAddress | KernelAddress | KernelHWAddress | - Memory | Leak | Undefined | Integer | Nullability | - DataFlow | Fuzzer | FuzzerNoLink, - RecoverableByDefault = Undefined | Integer | Nullability, + Memory | Leak | Undefined | Integer | ImplicitConversion | + Nullability | DataFlow | Fuzzer | FuzzerNoLink, + RecoverableByDefault = Undefined | Integer | ImplicitConversion | Nullability, Unrecoverable = Unreachable | Return, AlwaysRecoverable = KernelAddress | KernelHWAddress, LegacyFsanitizeRecoverMask = Undefined | Integer, NeedsLTO = CFI, TrappingSupported = (Undefined & ~Vptr) | UnsignedIntegerOverflow | - Nullability | LocalBounds | CFI, + ImplicitConversion | Nullability | LocalBounds | CFI, TrappingDefault = CFI, CFIClasses = CFIVCall | CFINVCall | CFIMFCall | CFIDerivedCast | CFIUnrelatedCast, @@ -321,7 +321,7 @@ SanitizerArgs::SanitizerArgs(const ToolChain &TC, D.Diag(diag::err_drv_argument_not_allowed_with) << "-fsanitize=vptr" << NoRTTIArg->getAsString(Args); } else { - // The vptr sanitizer requires RTTI, but RTTI is disabled (by + // The vptr sanitizer requires RTTI, but RTTI is disabled (by // default). Warn that the vptr sanitizer is being disabled. D.Diag(diag::warn_drv_disabling_vptr_no_rtti_default); } diff --git a/lib/Driver/ToolChain.cpp b/lib/Driver/ToolChain.cpp index d62ba1253348..cf3db34688df 100644 --- a/lib/Driver/ToolChain.cpp +++ b/lib/Driver/ToolChain.cpp @@ -564,7 +564,7 @@ std::string ToolChain::ComputeLLVMTriple(const ArgList &Args, StringRef Suffix = tools::arm::getLLVMArchSuffixForARM(CPU, MArch, Triple); bool IsMProfile = ARM::parseArchProfile(Suffix) == ARM::ProfileKind::M; - bool ThumbDefault = IsMProfile || (ARM::parseArchVersion(Suffix) == 7 && + bool ThumbDefault = IsMProfile || (ARM::parseArchVersion(Suffix) == 7 && getTriple().isOSBinFormatMachO()); // FIXME: this is invalid for WindowsCE if (getTriple().isOSWindows()) @@ -803,8 +803,8 @@ SanitizerMask ToolChain::getSupportedSanitizers() const { using namespace SanitizerKind; SanitizerMask Res = (Undefined & ~Vptr & ~Function) | (CFI & ~CFIICall) | - CFICastStrict | UnsignedIntegerOverflow | Nullability | - LocalBounds; + CFICastStrict | UnsignedIntegerOverflow | + ImplicitConversion | Nullability | LocalBounds; if (getTriple().getArch() == llvm::Triple::x86 || getTriple().getArch() == llvm::Triple::x86_64 || getTriple().getArch() == llvm::Triple::arm || diff --git a/lib/Driver/ToolChains/Arch/RISCV.cpp b/lib/Driver/ToolChains/Arch/RISCV.cpp index 11ce8a1fd769..1321fedcec51 100644 --- a/lib/Driver/ToolChains/Arch/RISCV.cpp +++ b/lib/Driver/ToolChains/Arch/RISCV.cpp @@ -279,7 +279,7 @@ void riscv::getRISCVTargetFeatures(const Driver &D, const ArgList &Args, if (!getExtensionVersion(D, MArch, std::string(1, Baseline), Exts, Major, Minor)) return; - + // TODO: Use version number when setting target features // and consume the underscore '_' that might follow. diff --git a/lib/Driver/ToolChains/Clang.cpp b/lib/Driver/ToolChains/Clang.cpp index eaff940a1c2b..8e9c4c6aecb8 100644 --- a/lib/Driver/ToolChains/Clang.cpp +++ b/lib/Driver/ToolChains/Clang.cpp @@ -919,34 +919,46 @@ static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs, } } +static bool checkDebugInfoOption(const Arg *A, const ArgList &Args, + const Driver &D, const ToolChain &TC) { + assert(A && "Expected non-nullptr argument."); + if (TC.supportsDebugInfoOption(A)) + return true; + D.Diag(diag::warn_drv_unsupported_debug_info_opt_for_target) + << A->getAsString(Args) << TC.getTripleString(); + return false; +} + static void RenderDebugInfoCompressionArgs(const ArgList &Args, ArgStringList &CmdArgs, - const Driver &D) { + const Driver &D, + const ToolChain &TC) { const Arg *A = Args.getLastArg(options::OPT_gz, options::OPT_gz_EQ); if (!A) return; + if (checkDebugInfoOption(A, Args, D, TC)) { + if (A->getOption().getID() == options::OPT_gz) { + if (llvm::zlib::isAvailable()) + CmdArgs.push_back("-compress-debug-sections"); + else + D.Diag(diag::warn_debug_compression_unavailable); + return; + } - if (A->getOption().getID() == options::OPT_gz) { - if (llvm::zlib::isAvailable()) - CmdArgs.push_back("-compress-debug-sections"); - else - D.Diag(diag::warn_debug_compression_unavailable); - return; - } - - StringRef Value = A->getValue(); - if (Value == "none") { - CmdArgs.push_back("-compress-debug-sections=none"); - } else if (Value == "zlib" || Value == "zlib-gnu") { - if (llvm::zlib::isAvailable()) { - CmdArgs.push_back( - Args.MakeArgString("-compress-debug-sections=" + Twine(Value))); + StringRef Value = A->getValue(); + if (Value == "none") { + CmdArgs.push_back("-compress-debug-sections=none"); + } else if (Value == "zlib" || Value == "zlib-gnu") { + if (llvm::zlib::isAvailable()) { + CmdArgs.push_back( + Args.MakeArgString("-compress-debug-sections=" + Twine(Value))); + } else { + D.Diag(diag::warn_debug_compression_unavailable); + } } else { - D.Diag(diag::warn_debug_compression_unavailable); + D.Diag(diag::err_drv_unsupported_option_argument) + << A->getOption().getName() << Value; } - } else { - D.Diag(diag::err_drv_unsupported_option_argument) - << A->getOption().getName() << Value; } } @@ -2867,7 +2879,9 @@ static void RenderDebugOptions(const ToolChain &TC, const Driver &D, codegenoptions::DebugInfoKind &DebugInfoKind, const Arg *&SplitDWARFArg) { if (Args.hasFlag(options::OPT_fdebug_info_for_profiling, - options::OPT_fno_debug_info_for_profiling, false)) + options::OPT_fno_debug_info_for_profiling, false) && + checkDebugInfoOption( + Args.getLastArg(options::OPT_fdebug_info_for_profiling), Args, D, TC)) CmdArgs.push_back("-fdebug-info-for-profiling"); // The 'g' groups options involve a somewhat intricate sequence of decisions @@ -2890,29 +2904,38 @@ static void RenderDebugOptions(const ToolChain &TC, const Driver &D, SplitDWARFArg = Args.getLastArg(options::OPT_gsplit_dwarf); + if (SplitDWARFArg && !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) { + SplitDWARFArg = nullptr; + SplitDWARFInlining = false; + } + if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) { - // If the last option explicitly specified a debug-info level, use it. - if (A->getOption().matches(options::OPT_gN_Group)) { - DebugInfoKind = DebugLevelToInfoKind(*A); - // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses. - // But -gsplit-dwarf is not a g_group option, hence we have to check the - // order explicitly. If -gsplit-dwarf wins, we fix DebugInfoKind later. - // This gets a bit more complicated if you've disabled inline info in the - // skeleton CUs (SplitDWARFInlining) - then there's value in composing - // split-dwarf and line-tables-only, so let those compose naturally in - // that case. - // And if you just turned off debug info, (-gsplit-dwarf -g0) - do that. - if (SplitDWARFArg) { - if (A->getIndex() > SplitDWARFArg->getIndex()) { - if (DebugInfoKind == codegenoptions::NoDebugInfo || - (DebugInfoKind == codegenoptions::DebugLineTablesOnly && - SplitDWARFInlining)) - SplitDWARFArg = nullptr; - } else if (SplitDWARFInlining) - DebugInfoKind = codegenoptions::NoDebugInfo; + if (checkDebugInfoOption(A, Args, D, TC)) { + // If the last option explicitly specified a debug-info level, use it. + if (A->getOption().matches(options::OPT_gN_Group)) { + DebugInfoKind = DebugLevelToInfoKind(*A); + // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses. + // But -gsplit-dwarf is not a g_group option, hence we have to check the + // order explicitly. If -gsplit-dwarf wins, we fix DebugInfoKind later. + // This gets a bit more complicated if you've disabled inline info in + // the skeleton CUs (SplitDWARFInlining) - then there's value in + // composing split-dwarf and line-tables-only, so let those compose + // naturally in that case. And if you just turned off debug info, + // (-gsplit-dwarf -g0) - do that. + if (SplitDWARFArg) { + if (A->getIndex() > SplitDWARFArg->getIndex()) { + if (DebugInfoKind == codegenoptions::NoDebugInfo || + (DebugInfoKind == codegenoptions::DebugLineTablesOnly && + SplitDWARFInlining)) + SplitDWARFArg = nullptr; + } else if (SplitDWARFInlining) + DebugInfoKind = codegenoptions::NoDebugInfo; + } + } else { + // For any other 'g' option, use Limited. + DebugInfoKind = codegenoptions::LimitedDebugInfo; } } else { - // For any other 'g' option, use Limited. DebugInfoKind = codegenoptions::LimitedDebugInfo; } } @@ -2920,39 +2943,50 @@ static void RenderDebugOptions(const ToolChain &TC, const Driver &D, // If a debugger tuning argument appeared, remember it. if (const Arg *A = Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) { - if (A->getOption().matches(options::OPT_glldb)) - DebuggerTuning = llvm::DebuggerKind::LLDB; - else if (A->getOption().matches(options::OPT_gsce)) - DebuggerTuning = llvm::DebuggerKind::SCE; - else - DebuggerTuning = llvm::DebuggerKind::GDB; + if (checkDebugInfoOption(A, Args, D, TC)) { + if (A->getOption().matches(options::OPT_glldb)) + DebuggerTuning = llvm::DebuggerKind::LLDB; + else if (A->getOption().matches(options::OPT_gsce)) + DebuggerTuning = llvm::DebuggerKind::SCE; + else + DebuggerTuning = llvm::DebuggerKind::GDB; + } } // If a -gdwarf argument appeared, remember it. if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3, options::OPT_gdwarf_4, options::OPT_gdwarf_5)) - DWARFVersion = DwarfVersionNum(A->getSpelling()); + if (checkDebugInfoOption(A, Args, D, TC)) + DWARFVersion = DwarfVersionNum(A->getSpelling()); // Forward -gcodeview. EmitCodeView might have been set by CL-compatibility // argument parsing. if (EmitCodeView) { - // DWARFVersion remains at 0 if no explicit choice was made. - CmdArgs.push_back("-gcodeview"); - } else if (DWARFVersion == 0 && - DebugInfoKind != codegenoptions::NoDebugInfo) { - DWARFVersion = TC.GetDefaultDwarfVersion(); + if (const Arg *A = Args.getLastArg(options::OPT_gcodeview)) { + EmitCodeView = checkDebugInfoOption(A, Args, D, TC); + if (EmitCodeView) { + // DWARFVersion remains at 0 if no explicit choice was made. + CmdArgs.push_back("-gcodeview"); + } + } } + if (!EmitCodeView && DWARFVersion == 0 && + DebugInfoKind != codegenoptions::NoDebugInfo) + DWARFVersion = TC.GetDefaultDwarfVersion(); + // We ignore flag -gstrict-dwarf for now. // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags. Args.ClaimAllArgs(options::OPT_g_flags_Group); - // Column info is included by default for everything except SCE and CodeView. - // Clang doesn't track end columns, just starting columns, which, in theory, - // is fine for CodeView (and PDB). In practice, however, the Microsoft - // debuggers don't handle missing end columns well, so it's better not to - // include any column info. + // Column info is included by default for everything except SCE and + // CodeView. Clang doesn't track end columns, just starting columns, which, + // in theory, is fine for CodeView (and PDB). In practice, however, the + // Microsoft debuggers don't handle missing end columns well, so it's better + // not to include any column info. + if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info)) + (void)checkDebugInfoOption(A, Args, D, TC); if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info, /*Default=*/!EmitCodeView && DebuggerTuning != llvm::DebuggerKind::SCE)) @@ -2960,12 +2994,14 @@ static void RenderDebugOptions(const ToolChain &TC, const Driver &D, // FIXME: Move backend command line options to the module. // If -gline-tables-only is the last option it wins. - if (DebugInfoKind != codegenoptions::DebugLineTablesOnly && - Args.hasArg(options::OPT_gmodules)) { - DebugInfoKind = codegenoptions::LimitedDebugInfo; - CmdArgs.push_back("-dwarf-ext-refs"); - CmdArgs.push_back("-fmodule-format=obj"); - } + if (const Arg *A = Args.getLastArg(options::OPT_gmodules)) + if (checkDebugInfoOption(A, Args, D, TC)) { + if (DebugInfoKind != codegenoptions::DebugLineTablesOnly) { + DebugInfoKind = codegenoptions::LimitedDebugInfo; + CmdArgs.push_back("-dwarf-ext-refs"); + CmdArgs.push_back("-fmodule-format=obj"); + } + } // -gsplit-dwarf should turn on -g and enable the backend dwarf // splitting and extraction. @@ -2989,19 +3025,23 @@ static void RenderDebugOptions(const ToolChain &TC, const Driver &D, bool NeedFullDebug = Args.hasFlag(options::OPT_fstandalone_debug, options::OPT_fno_standalone_debug, TC.GetDefaultStandaloneDebug()); + if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug)) + (void)checkDebugInfoOption(A, Args, D, TC); if (DebugInfoKind == codegenoptions::LimitedDebugInfo && NeedFullDebug) DebugInfoKind = codegenoptions::FullDebugInfo; - if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source, false)) { + if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source, + false)) { // Source embedding is a vendor extension to DWARF v5. By now we have // checked if a DWARF version was stated explicitly, and have otherwise - // fallen back to the target default, so if this is still not at least 5 we - // emit an error. + // fallen back to the target default, so if this is still not at least 5 + // we emit an error. + const Arg *A = Args.getLastArg(options::OPT_gembed_source); if (DWARFVersion < 5) D.Diag(diag::err_drv_argument_only_allowed_with) - << Args.getLastArg(options::OPT_gembed_source)->getAsString(Args) - << "-gdwarf-5"; - CmdArgs.push_back("-gembed-source"); + << A->getAsString(Args) << "-gdwarf-5"; + else if (checkDebugInfoOption(A, Args, D, TC)) + CmdArgs.push_back("-gembed-source"); } RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DWARFVersion, @@ -3010,31 +3050,41 @@ static void RenderDebugOptions(const ToolChain &TC, const Driver &D, // -fdebug-macro turns on macro debug info generation. if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro, false)) - CmdArgs.push_back("-debug-info-macro"); + if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args, + D, TC)) + CmdArgs.push_back("-debug-info-macro"); // -ggnu-pubnames turns on gnu style pubnames in the backend. if (Args.hasFlag(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames, false)) - CmdArgs.push_back("-ggnu-pubnames"); + if (checkDebugInfoOption(Args.getLastArg(options::OPT_ggnu_pubnames), Args, + D, TC)) + CmdArgs.push_back("-ggnu-pubnames"); // -gdwarf-aranges turns on the emission of the aranges section in the // backend. // Always enabled for SCE tuning. - if (Args.hasArg(options::OPT_gdwarf_aranges) || - DebuggerTuning == llvm::DebuggerKind::SCE) { + bool NeedAranges = DebuggerTuning == llvm::DebuggerKind::SCE; + if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges)) + NeedAranges = checkDebugInfoOption(A, Args, D, TC) || NeedAranges; + if (NeedAranges) { CmdArgs.push_back("-mllvm"); CmdArgs.push_back("-generate-arange-section"); } if (Args.hasFlag(options::OPT_fdebug_types_section, options::OPT_fno_debug_types_section, false)) { - if (!T.isOSBinFormatELF()) + if (!T.isOSBinFormatELF()) { D.Diag(diag::err_drv_unsupported_opt_for_target) << Args.getLastArg(options::OPT_fdebug_types_section) ->getAsString(Args) << T.getTriple(); - CmdArgs.push_back("-mllvm"); - CmdArgs.push_back("-generate-type-units"); + } else if (checkDebugInfoOption( + Args.getLastArg(options::OPT_fdebug_types_section), Args, D, + TC)) { + CmdArgs.push_back("-mllvm"); + CmdArgs.push_back("-generate-type-units"); + } } // Decide how to render forward declarations of template instantiations. @@ -3042,11 +3092,12 @@ static void RenderDebugOptions(const ToolChain &TC, const Driver &D, if (DebuggerTuning == llvm::DebuggerKind::SCE) CmdArgs.push_back("-debug-forward-template-params"); - // Do we need to explicitly import anonymous namespaces into the parent scope? + // Do we need to explicitly import anonymous namespaces into the parent + // scope? if (DebuggerTuning == llvm::DebuggerKind::SCE) CmdArgs.push_back("-dwarf-explicit-import"); - RenderDebugInfoCompressionArgs(Args, CmdArgs, D); + RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC); } void Clang::ConstructJob(Compilation &C, const JobAction &JA, @@ -5388,7 +5439,7 @@ void ClangAs::ConstructJob(Compilation &C, const JobAction &JA, } RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion, llvm::DebuggerKind::Default); - RenderDebugInfoCompressionArgs(Args, CmdArgs, D); + RenderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain()); // Handle -fPIC et al -- the relocation-model affects the assembler diff --git a/lib/Driver/ToolChains/Cuda.cpp b/lib/Driver/ToolChains/Cuda.cpp index d17c4c39532a..7fb4ae4ea9cf 100644 --- a/lib/Driver/ToolChains/Cuda.cpp +++ b/lib/Driver/ToolChains/Cuda.cpp @@ -679,6 +679,18 @@ void CudaToolChain::addClangTargetOptions( } } +bool CudaToolChain::supportsDebugInfoOption(const llvm::opt::Arg *A) const { + const Option &O = A->getOption(); + return (O.matches(options::OPT_gN_Group) && + !O.matches(options::OPT_gmodules)) || + O.matches(options::OPT_g_Flag) || + O.matches(options::OPT_ggdbN_Group) || O.matches(options::OPT_ggdb) || + O.matches(options::OPT_gdwarf) || O.matches(options::OPT_gdwarf_2) || + O.matches(options::OPT_gdwarf_3) || O.matches(options::OPT_gdwarf_4) || + O.matches(options::OPT_gdwarf_5) || + O.matches(options::OPT_gcolumn_info); +} + void CudaToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs, ArgStringList &CC1Args) const { // Check our CUDA version if we're going to include the CUDA headers. diff --git a/lib/Driver/ToolChains/Cuda.h b/lib/Driver/ToolChains/Cuda.h index 99d5a4a628ce..01580cb66920 100644 --- a/lib/Driver/ToolChains/Cuda.h +++ b/lib/Driver/ToolChains/Cuda.h @@ -158,6 +158,7 @@ public: bool isPIEDefault() const override { return false; } bool isPICDefaultForced() const override { return false; } bool SupportsProfiling() const override { return false; } + bool supportsDebugInfoOption(const llvm::opt::Arg *A) const override; bool IsMathErrnoDefault() const override { return false; } void AddCudaIncludeArgs(const llvm::opt::ArgList &DriverArgs, diff --git a/lib/Driver/ToolChains/Darwin.cpp b/lib/Driver/ToolChains/Darwin.cpp index 95ec8d64c2c7..9205dd52de0b 100644 --- a/lib/Driver/ToolChains/Darwin.cpp +++ b/lib/Driver/ToolChains/Darwin.cpp @@ -916,26 +916,13 @@ unsigned DarwinClang::GetDefaultDwarfVersion() const { return 4; } -SmallString<128> MachO::runtimeLibDir(bool IsEmbedded) const { - SmallString<128> Dir(getDriver().ResourceDir); - llvm::sys::path::append( - Dir, "lib", IsEmbedded ? "macho_embedded" : "darwin"); - return Dir; -} - -std::string Darwin::getFileNameForSanitizerLib(StringRef SanitizerName, - bool Shared) const { - return (Twine("libclang_rt.") + SanitizerName + "_" + - getOSLibraryNameSuffix() + - (Shared ? "_dynamic.dylib" : ".a")).str(); - -} - void MachO::AddLinkRuntimeLib(const ArgList &Args, ArgStringList &CmdArgs, StringRef DarwinLibName, RuntimeLinkOptions Opts) const { + SmallString<128> Dir(getDriver().ResourceDir); + llvm::sys::path::append( + Dir, "lib", (Opts & RLO_IsEmbedded) ? "macho_embedded" : "darwin"); - SmallString<128> Dir = runtimeLibDir(Opts & RLO_IsEmbedded); SmallString<128> P(Dir); llvm::sys::path::append(P, DarwinLibName); @@ -1055,9 +1042,12 @@ void DarwinClang::AddLinkSanitizerLibArgs(const ArgList &Args, StringRef Sanitizer, bool Shared) const { auto RLO = RuntimeLinkOptions(RLO_AlwaysLink | (Shared ? RLO_AddRPath : 0U)); - std::string SanitizerRelFilename = - getFileNameForSanitizerLib(Sanitizer, Shared); - AddLinkRuntimeLib(Args, CmdArgs, SanitizerRelFilename, RLO); + AddLinkRuntimeLib(Args, CmdArgs, + (Twine("libclang_rt.") + Sanitizer + "_" + + getOSLibraryNameSuffix() + + (Shared ? "_dynamic.dylib" : ".a")) + .str(), + RLO); } ToolChain::RuntimeLibType DarwinClang::GetRuntimeLibType( @@ -2295,43 +2285,24 @@ void Darwin::CheckObjCARC() const { SanitizerMask Darwin::getSupportedSanitizers() const { const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64; SanitizerMask Res = ToolChain::getSupportedSanitizers(); - - { - using namespace SanitizerKind; - assert(!(Res & (Address | Leak | Fuzzer | FuzzerNoLink | Thread)) && - "Sanitizer is already registered as supported"); - } - - if (sanitizerRuntimeExists("asan")) - Res |= SanitizerKind::Address; - if (sanitizerRuntimeExists("lsan")) - Res |= SanitizerKind::Leak; - if (sanitizerRuntimeExists("fuzzer", /*Shared=*/false)) { - Res |= SanitizerKind::Fuzzer; - Res |= SanitizerKind::FuzzerNoLink; - } + Res |= SanitizerKind::Address; + Res |= SanitizerKind::Leak; + Res |= SanitizerKind::Fuzzer; + Res |= SanitizerKind::FuzzerNoLink; Res |= SanitizerKind::Function; - if (isTargetMacOS() && !isMacosxVersionLT(10, 9)) - Res |= SanitizerKind::Vptr; - if (isTargetMacOS()) + if (isTargetMacOS()) { + if (!isMacosxVersionLT(10, 9)) + Res |= SanitizerKind::Vptr; Res |= SanitizerKind::SafeStack; - - if (sanitizerRuntimeExists("tsan") && IsX86_64 && - (isTargetMacOS() || isTargetIOSSimulator() || isTargetTvOSSimulator())) - Res |= SanitizerKind::Thread; - + if (IsX86_64) + Res |= SanitizerKind::Thread; + } else if (isTargetIOSSimulator() || isTargetTvOSSimulator()) { + if (IsX86_64) + Res |= SanitizerKind::Thread; + } return Res; } void Darwin::printVerboseInfo(raw_ostream &OS) const { CudaInstallation.print(OS); } - -bool Darwin::sanitizerRuntimeExists(StringRef SanitizerName, - bool Shared) const { - std::string RelName = getFileNameForSanitizerLib(SanitizerName, Shared); - SmallString<128> Dir = runtimeLibDir(); - SmallString<128> AbsName(Dir); - llvm::sys::path::append(AbsName, RelName); - return getVFS().exists(AbsName); -} diff --git a/lib/Driver/ToolChains/Darwin.h b/lib/Driver/ToolChains/Darwin.h index eee6e966718b..87d553bd7e0b 100644 --- a/lib/Driver/ToolChains/Darwin.h +++ b/lib/Driver/ToolChains/Darwin.h @@ -130,9 +130,6 @@ protected: Tool *buildLinker() const override; Tool *getTool(Action::ActionClass AC) const override; - /// \return Directory to find the runtime library in. - SmallString<128> runtimeLibDir(bool IsEmbedded=false) const; - private: mutable std::unique_ptr<tools::darwin::Lipo> Lipo; mutable std::unique_ptr<tools::darwin::Dsymutil> Dsymutil; @@ -254,6 +251,7 @@ public: GetExceptionModel(const llvm::opt::ArgList &Args) const override { return llvm::ExceptionHandling::None; } + /// } }; @@ -422,11 +420,6 @@ protected: StringRef getPlatformFamily() const; StringRef getOSLibraryNameSuffix() const; - /// \return Relative path to the filename for the library - /// containing the sanitizer {@code SanitizerName}. - std::string getFileNameForSanitizerLib(StringRef SanitizerName, - bool Shared = true) const; - public: static StringRef getSDKName(StringRef isysroot); @@ -480,12 +473,6 @@ public: SanitizerMask getSupportedSanitizers() const override; void printVerboseInfo(raw_ostream &OS) const override; - -private: - /// \return Whether the runtime corresponding to the given - /// sanitizer exists in the toolchain. - bool sanitizerRuntimeExists(StringRef SanitizerName, - bool Shared = true) const; }; /// DarwinClang - The Darwin toolchain used by Clang. diff --git a/lib/Driver/ToolChains/Gnu.cpp b/lib/Driver/ToolChains/Gnu.cpp index 2c83598f3d77..3755673250b2 100644 --- a/lib/Driver/ToolChains/Gnu.cpp +++ b/lib/Driver/ToolChains/Gnu.cpp @@ -1877,7 +1877,8 @@ void Generic_GCC::GCCInstallationDetector::AddDefaultGCCPrefixes( static const char *const RISCV32LibDirs[] = {"/lib", "/lib32"}; static const char *const RISCVTriples[] = {"riscv32-unknown-linux-gnu", - "riscv64-unknown-linux-gnu"}; + "riscv64-unknown-linux-gnu", + "riscv32-unknown-elf"}; static const char *const SPARCv8LibDirs[] = {"/lib32", "/lib"}; static const char *const SPARCv8Triples[] = {"sparc-linux-gnu", @@ -2188,7 +2189,8 @@ void Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple( // this on Freescale triples, though, since some systems put a *lot* of // files in that location, not just GCC installation data. {CandidateTriple.str(), "..", - TargetTriple.getVendor() == llvm::Triple::Freescale}, + TargetTriple.getVendor() == llvm::Triple::Freescale || + TargetTriple.getVendor() == llvm::Triple::OpenEmbedded}, // Natively multiarch systems sometimes put the GCC triple-specific // directory within their multiarch lib directory, resulting in the diff --git a/lib/Driver/ToolChains/Linux.cpp b/lib/Driver/ToolChains/Linux.cpp index d27f994d32ab..f8f36239180c 100644 --- a/lib/Driver/ToolChains/Linux.cpp +++ b/lib/Driver/ToolChains/Linux.cpp @@ -376,7 +376,14 @@ Linux::Linux(const Driver &D, const llvm::Triple &Triple, const ArgList &Args) } addPathIfExists(D, SysRoot + "/usr/lib/" + MultiarchTriple, Paths); - addPathIfExists(D, SysRoot + "/usr/lib/../" + OSLibDir, Paths); + // 64-bit OpenEmbedded sysroots may not have a /usr/lib dir. So they cannot + // find /usr/lib64 as it is referenced as /usr/lib/../lib64. So we handle + // this here. + if (Triple.getVendor() == llvm::Triple::OpenEmbedded && + Triple.isArch64Bit()) + addPathIfExists(D, SysRoot + "/usr/" + OSLibDir, Paths); + else + addPathIfExists(D, SysRoot + "/usr/lib/../" + OSLibDir, Paths); if (IsRISCV) { StringRef ABIName = tools::riscv::getRISCVABI(Args, Triple); addPathIfExists(D, SysRoot + "/" + OSLibDir + "/" + ABIName, Paths); diff --git a/lib/Driver/ToolChains/RISCV.cpp b/lib/Driver/ToolChains/RISCV.cpp new file mode 100644 index 000000000000..31996fc588f1 --- /dev/null +++ b/lib/Driver/ToolChains/RISCV.cpp @@ -0,0 +1,117 @@ +//===--- RISCV.cpp - RISCV ToolChain Implementations ------------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#include "RISCV.h" +#include "CommonArgs.h" +#include "InputInfo.h" +#include "clang/Driver/Compilation.h" +#include "clang/Driver/Options.h" +#include "llvm/Option/ArgList.h" +#include "llvm/Support/Path.h" +#include "llvm/Support/raw_ostream.h" + +using namespace clang::driver; +using namespace clang::driver::toolchains; +using namespace clang::driver::tools; +using namespace clang; +using namespace llvm::opt; + +/// RISCV Toolchain +RISCVToolChain::RISCVToolChain(const Driver &D, const llvm::Triple &Triple, + const ArgList &Args) + : Generic_ELF(D, Triple, Args) { + GCCInstallation.init(Triple, Args); + getFilePaths().push_back(D.SysRoot + "/lib"); + if (GCCInstallation.isValid()) { + getFilePaths().push_back(GCCInstallation.getInstallPath().str()); + getProgramPaths().push_back( + (GCCInstallation.getParentLibPath() + "/../bin").str()); + } +} + +Tool *RISCVToolChain::buildLinker() const { + return new tools::RISCV::Linker(*this); +} + +void RISCVToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs, + ArgStringList &CC1Args) const { + if (DriverArgs.hasArg(options::OPT_nostdinc)) + return; + + if (!DriverArgs.hasArg(options::OPT_nostdlibinc)) { + SmallString<128> Dir(getDriver().SysRoot); + llvm::sys::path::append(Dir, "include"); + addSystemInclude(DriverArgs, CC1Args, Dir.str()); + } +} + +void RISCVToolChain::addLibStdCxxIncludePaths( + const llvm::opt::ArgList &DriverArgs, + llvm::opt::ArgStringList &CC1Args) const { + StringRef LibDir = GCCInstallation.getParentLibPath(); + const GCCVersion &Version = GCCInstallation.getVersion(); + StringRef TripleStr = GCCInstallation.getTriple().str(); + const Multilib &Multilib = GCCInstallation.getMultilib(); + addLibStdCXXIncludePaths( + LibDir.str() + "/../" + TripleStr.str() + "/include/c++/" + Version.Text, + "", TripleStr, "", "", Multilib.includeSuffix(), DriverArgs, CC1Args); +} + +void RISCV::Linker::ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &Args, + const char *LinkingOutput) const { + const ToolChain &ToolChain = getToolChain(); + const Driver &D = ToolChain.getDriver(); + ArgStringList CmdArgs; + + if (!D.SysRoot.empty()) + CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot)); + + std::string Linker = getToolChain().GetProgramPath(getShortName()); + + bool WantCRTs = + !Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles); + + if (WantCRTs) { + CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o"))); + CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtbegin.o"))); + } + + Args.AddAllArgs(CmdArgs, options::OPT_L); + ToolChain.AddFilePathLibArgs(Args, CmdArgs); + Args.AddAllArgs(CmdArgs, + {options::OPT_T_Group, options::OPT_e, options::OPT_s, + options::OPT_t, options::OPT_Z_Flag, options::OPT_r}); + + AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA); + + // TODO: add C++ includes and libs if compiling C++. + + if (!Args.hasArg(options::OPT_nostdlib) && + !Args.hasArg(options::OPT_nodefaultlibs)) { + if (ToolChain.ShouldLinkCXXStdlib(Args)) + ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs); + CmdArgs.push_back("--start-group"); + CmdArgs.push_back("-lc"); + CmdArgs.push_back("-lgloss"); + CmdArgs.push_back("--end-group"); + CmdArgs.push_back("-lgcc"); + } + + if (WantCRTs) + CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o"))); + + CmdArgs.push_back("-o"); + CmdArgs.push_back(Output.getFilename()); + C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker), + CmdArgs, Inputs)); +} +// RISCV tools end. diff --git a/lib/Driver/ToolChains/RISCV.h b/lib/Driver/ToolChains/RISCV.h new file mode 100644 index 000000000000..6f59d84020d8 --- /dev/null +++ b/lib/Driver/ToolChains/RISCV.h @@ -0,0 +1,57 @@ +//===--- RISCV.h - RISCV ToolChain Implementations --------------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_LIB_DRIVER_TOOLCHAINS_RISCV_H +#define LLVM_CLANG_LIB_DRIVER_TOOLCHAINS_RISCV_H + +#include "Gnu.h" +#include "clang/Driver/ToolChain.h" + +namespace clang { +namespace driver { +namespace toolchains { + +class LLVM_LIBRARY_VISIBILITY RISCVToolChain : public Generic_ELF { +public: + RISCVToolChain(const Driver &D, const llvm::Triple &Triple, + const llvm::opt::ArgList &Args); + + bool IsIntegratedAssemblerDefault() const override { return true; } + void + AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs, + llvm::opt::ArgStringList &CC1Args) const override; + void + addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs, + llvm::opt::ArgStringList &CC1Args) const override; + +protected: + Tool *buildLinker() const override; +}; + +} // end namespace toolchains + +namespace tools { +namespace RISCV { +class LLVM_LIBRARY_VISIBILITY Linker : public GnuTool { +public: + Linker(const ToolChain &TC) : GnuTool("RISCV::Linker", "ld", TC) {} + bool hasIntegratedCPP() const override { return false; } + bool isLinkJob() const override { return true; } + void ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, const InputInfoList &Inputs, + const llvm::opt::ArgList &TCArgs, + const char *LinkingOutput) const override; +}; +} // end namespace RISCV +} // end namespace tools + +} // end namespace driver +} // end namespace clang + +#endif // LLVM_CLANG_LIB_DRIVER_TOOLCHAINS_RISCV_H diff --git a/lib/Edit/Commit.cpp b/lib/Edit/Commit.cpp index afc1a131eb25..e72b13cf8198 100644 --- a/lib/Edit/Commit.cpp +++ b/lib/Edit/Commit.cpp @@ -147,7 +147,7 @@ bool Commit::replaceWithInner(CharSourceRange range, } FileOffset OuterEnd = OuterBegin.getWithOffset(OuterLen); - FileOffset InnerEnd = InnerBegin.getWithOffset(InnerLen); + FileOffset InnerEnd = InnerBegin.getWithOffset(InnerLen); if (OuterBegin.getFID() != InnerBegin.getFID() || InnerBegin < OuterBegin || InnerBegin > OuterEnd || @@ -300,7 +300,7 @@ bool Commit::canRemoveRange(CharSourceRange range, range = Lexer::makeFileCharRange(range, SM, LangOpts); if (range.isInvalid()) return false; - + if (range.getBegin().isMacroID() || range.getEnd().isMacroID()) return false; if (SM.isInSystemHeader(range.getBegin()) || diff --git a/lib/Edit/RewriteObjCFoundationAPI.cpp b/lib/Edit/RewriteObjCFoundationAPI.cpp index f89526a71da2..b53a70d87582 100644 --- a/lib/Edit/RewriteObjCFoundationAPI.cpp +++ b/lib/Edit/RewriteObjCFoundationAPI.cpp @@ -82,7 +82,7 @@ bool edit::rewriteObjCRedundantCallWithLiteral(const ObjCMessageExpr *Msg, (NS.getNSDictionarySelector( NSAPI::NSDict_dictionaryWithDictionary) == Sel || NS.getNSDictionarySelector(NSAPI::NSDict_initWithDictionary) == Sel))) { - + commit.replaceWithInner(Msg->getSourceRange(), Msg->getArg(0)->getSourceRange()); return true; @@ -726,7 +726,7 @@ static bool getLiteralInfo(SourceRange literalRange, } else break; } - + if (!UpperU.hasValue() && !UpperL.hasValue()) UpperU = UpperL = true; else if (UpperU.hasValue() && !UpperL.hasValue()) @@ -738,7 +738,7 @@ static bool getLiteralInfo(SourceRange literalRange, Info.L = *UpperL ? "L" : "l"; Info.LL = *UpperL ? "LL" : "ll"; Info.F = UpperF ? "F" : "f"; - + Info.Hex = Info.Octal = false; if (text.startswith("0x")) Info.Hex = true; @@ -851,7 +851,7 @@ static bool rewriteToNumberLiteral(const ObjCMessageExpr *Msg, // Try to modify the literal make it the same type as the method call. // -Modify the suffix, and/or // -Change integer to float - + LiteralInfo LitInfo; bool isIntZero = false; if (const IntegerLiteral *IntE = dyn_cast<IntegerLiteral>(literalE)) @@ -862,7 +862,7 @@ static bool rewriteToNumberLiteral(const ObjCMessageExpr *Msg, // Not easy to do int -> float with hex/octal and uncommon anyway. if (!LitIsFloat && CallIsFloating && (LitInfo.Hex || LitInfo.Octal)) return rewriteToNumericBoxedExpression(Msg, NS, commit); - + SourceLocation LitB = LitInfo.WithoutSuffRange.getBegin(); SourceLocation LitE = LitInfo.WithoutSuffRange.getEnd(); @@ -879,7 +879,7 @@ static bool rewriteToNumberLiteral(const ObjCMessageExpr *Msg, } else { if (CallIsUnsigned) commit.insert(LitE, LitInfo.U); - + if (CallIsLong) commit.insert(LitE, LitInfo.L); else if (CallIsLongLong) @@ -997,7 +997,7 @@ static bool rewriteToNumericBoxedExpression(const ObjCMessageExpr *Msg, uint64_t FinalTySize = Ctx.getTypeSize(FinalTy); uint64_t OrigTySize = Ctx.getTypeSize(OrigTy); - bool isTruncated = FinalTySize < OrigTySize; + bool isTruncated = FinalTySize < OrigTySize; bool needsCast = false; if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) { @@ -1090,7 +1090,7 @@ static bool rewriteToNumericBoxedExpression(const ObjCMessageExpr *Msg, } if (needsCast) { - DiagnosticsEngine &Diags = Ctx.getDiagnostics(); + DiagnosticsEngine &Diags = Ctx.getDiagnostics(); // FIXME: Use a custom category name to distinguish migration diagnostics. unsigned diagID = Diags.getCustomDiagID(DiagnosticsEngine::Warning, "converting to boxing syntax requires casting %0 to %1"); @@ -1145,7 +1145,7 @@ static bool doRewriteToUTF8StringBoxedExpressionHelper( commit.insertBefore(ArgRange.getBegin(), "@"); else commit.insertWrap("@(", ArgRange, ")"); - + return true; } } diff --git a/lib/Format/BreakableToken.cpp b/lib/Format/BreakableToken.cpp index cc68f70100e3..fc2f891e0857 100644 --- a/lib/Format/BreakableToken.cpp +++ b/lib/Format/BreakableToken.cpp @@ -235,6 +235,7 @@ BreakableToken::Split BreakableStringLiteral::getSplit( void BreakableStringLiteral::insertBreak(unsigned LineIndex, unsigned TailOffset, Split Split, + unsigned ContentIndent, WhitespaceManager &Whitespaces) const { Whitespaces.replaceWhitespaceInToken( Tok, Prefix.size() + TailOffset + Split.first, Split.second, Postfix, @@ -510,8 +511,33 @@ unsigned BreakableBlockComment::getContentStartColumn(unsigned LineIndex, return std::max(0, ContentColumn[LineIndex]); } +const llvm::StringSet<> + BreakableBlockComment::ContentIndentingJavadocAnnotations = { + "@param", "@return", "@returns", "@throws", "@type", "@template", + "@see", "@deprecated", "@define", "@exports", "@mods", "@private", +}; + +unsigned BreakableBlockComment::getContentIndent(unsigned LineIndex) const { + if (Style.Language != FormatStyle::LK_Java && + Style.Language != FormatStyle::LK_JavaScript) + return 0; + // The content at LineIndex 0 of a comment like: + // /** line 0 */ + // is "* line 0", so we need to skip over the decoration in that case. + StringRef ContentWithNoDecoration = Content[LineIndex]; + if (LineIndex == 0 && ContentWithNoDecoration.startswith("*")) { + ContentWithNoDecoration = ContentWithNoDecoration.substr(1).ltrim(Blanks); + } + StringRef FirstWord = ContentWithNoDecoration.substr( + 0, ContentWithNoDecoration.find_first_of(Blanks)); + if (ContentIndentingJavadocAnnotations.find(FirstWord) != + ContentIndentingJavadocAnnotations.end()) + return Style.ContinuationIndentWidth; + return 0; +} + void BreakableBlockComment::insertBreak(unsigned LineIndex, unsigned TailOffset, - Split Split, + Split Split, unsigned ContentIndent, WhitespaceManager &Whitespaces) const { StringRef Text = Content[LineIndex].substr(TailOffset); StringRef Prefix = Decoration; @@ -532,10 +558,14 @@ void BreakableBlockComment::insertBreak(unsigned LineIndex, unsigned TailOffset, Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first; unsigned CharsToRemove = Split.second; assert(LocalIndentAtLineBreak >= Prefix.size()); + std::string PrefixWithTrailingIndent = Prefix; + for (unsigned I = 0; I < ContentIndent; ++I) + PrefixWithTrailingIndent += " "; Whitespaces.replaceWhitespaceInToken( - tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "", Prefix, - InPPDirective, /*Newlines=*/1, - /*Spaces=*/LocalIndentAtLineBreak - Prefix.size()); + tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "", + PrefixWithTrailingIndent, InPPDirective, /*Newlines=*/1, + /*Spaces=*/LocalIndentAtLineBreak + ContentIndent - + PrefixWithTrailingIndent.size()); } BreakableToken::Split @@ -544,7 +574,16 @@ BreakableBlockComment::getReflowSplit(unsigned LineIndex, if (!mayReflow(LineIndex, CommentPragmasRegex)) return Split(StringRef::npos, 0); + // If we're reflowing into a line with content indent, only reflow the next + // line if its starting whitespace matches the content indent. size_t Trimmed = Content[LineIndex].find_first_not_of(Blanks); + if (LineIndex) { + unsigned PreviousContentIndent = getContentIndent(LineIndex - 1); + if (PreviousContentIndent && Trimmed != StringRef::npos && + Trimmed != PreviousContentIndent) + return Split(StringRef::npos, 0); + } + return Split(0, Trimmed != StringRef::npos ? Trimmed : 0); } @@ -583,7 +622,8 @@ void BreakableBlockComment::adaptStartOfLine( // break length are the same. size_t BreakLength = Lines[0].substr(1).find_first_not_of(Blanks); if (BreakLength != StringRef::npos) - insertBreak(LineIndex, 0, Split(1, BreakLength), Whitespaces); + insertBreak(LineIndex, 0, Split(1, BreakLength), /*ContentIndent=*/0, + Whitespaces); } return; } @@ -754,7 +794,7 @@ unsigned BreakableLineCommentSection::getContentStartColumn(unsigned LineIndex, void BreakableLineCommentSection::insertBreak( unsigned LineIndex, unsigned TailOffset, Split Split, - WhitespaceManager &Whitespaces) const { + unsigned ContentIndent, WhitespaceManager &Whitespaces) const { StringRef Text = Content[LineIndex].substr(TailOffset); // Compute the offset of the split relative to the beginning of the token // text. diff --git a/lib/Format/BreakableToken.h b/lib/Format/BreakableToken.h index 0fac8f08c026..10e180178021 100644 --- a/lib/Format/BreakableToken.h +++ b/lib/Format/BreakableToken.h @@ -21,6 +21,7 @@ #include "Encoding.h" #include "TokenAnnotator.h" #include "WhitespaceManager.h" +#include "llvm/ADT/StringSet.h" #include "llvm/Support/Regex.h" #include <utility> @@ -135,6 +136,21 @@ public: virtual unsigned getContentStartColumn(unsigned LineIndex, bool Break) const = 0; + /// Returns additional content indent required for the second line after the + /// content at line \p LineIndex is broken. + /// + // (Next lines do not start with `///` since otherwise -Wdocumentation picks + // up the example annotations and generates warnings for them) + // For example, Javadoc @param annotations require and indent of 4 spaces and + // in this example getContentIndex(1) returns 4. + // /** + // * @param loooooooooooooong line + // * continuation + // */ + virtual unsigned getContentIndent(unsigned LineIndex) const { + return 0; + } + /// Returns a range (offset, length) at which to break the line at /// \p LineIndex, if previously broken at \p TailOffset. If possible, do not /// violate \p ColumnLimit, assuming the text starting at \p TailOffset in @@ -146,6 +162,7 @@ public: /// Emits the previously retrieved \p Split via \p Whitespaces. virtual void insertBreak(unsigned LineIndex, unsigned TailOffset, Split Split, + unsigned ContentIndent, WhitespaceManager &Whitespaces) const = 0; /// Returns the number of columns needed to format @@ -210,7 +227,7 @@ public: Split SplitAfterLastLine, WhitespaceManager &Whitespaces) const { insertBreak(getLineCount() - 1, TailOffset, SplitAfterLastLine, - Whitespaces); + /*ContentIndent=*/0, Whitespaces); } /// Updates the next token of \p State to the next token after this @@ -245,6 +262,7 @@ public: unsigned ContentStartColumn, llvm::Regex &CommentPragmasRegex) const override; void insertBreak(unsigned LineIndex, unsigned TailOffset, Split Split, + unsigned ContentIndent, WhitespaceManager &Whitespaces) const override; void compressWhitespace(unsigned LineIndex, unsigned TailOffset, Split Split, WhitespaceManager &Whitespaces) const override {} @@ -354,7 +372,9 @@ public: unsigned getRemainingLength(unsigned LineIndex, unsigned Offset, unsigned StartColumn) const override; unsigned getContentStartColumn(unsigned LineIndex, bool Break) const override; + unsigned getContentIndent(unsigned LineIndex) const override; void insertBreak(unsigned LineIndex, unsigned TailOffset, Split Split, + unsigned ContentIndent, WhitespaceManager &Whitespaces) const override; Split getReflowSplit(unsigned LineIndex, llvm::Regex &CommentPragmasRegex) const override; @@ -368,6 +388,10 @@ public: bool mayReflow(unsigned LineIndex, llvm::Regex &CommentPragmasRegex) const override; + // Contains Javadoc annotations that require additional indent when continued + // on multiple lines. + static const llvm::StringSet<> ContentIndentingJavadocAnnotations; + private: // Rearranges the whitespace between Lines[LineIndex-1] and Lines[LineIndex]. // @@ -423,6 +447,7 @@ public: unsigned StartColumn) const override; unsigned getContentStartColumn(unsigned LineIndex, bool Break) const override; void insertBreak(unsigned LineIndex, unsigned TailOffset, Split Split, + unsigned ContentIndent, WhitespaceManager &Whitespaces) const override; Split getReflowSplit(unsigned LineIndex, llvm::Regex &CommentPragmasRegex) const override; diff --git a/lib/Format/ContinuationIndenter.cpp b/lib/Format/ContinuationIndenter.cpp index 90d2a9997111..7ca588a675b5 100644 --- a/lib/Format/ContinuationIndenter.cpp +++ b/lib/Format/ContinuationIndenter.cpp @@ -1809,6 +1809,7 @@ ContinuationIndenter::breakProtrudingToken(const FormatToken &Current, if (!DryRun) Token->adaptStartOfLine(0, Whitespaces); + unsigned ContentIndent = 0; unsigned Penalty = 0; LLVM_DEBUG(llvm::dbgs() << "Breaking protruding token at column " << StartColumn << ".\n"); @@ -1930,11 +1931,28 @@ ContinuationIndenter::breakProtrudingToken(const FormatToken &Current, } } LLVM_DEBUG(llvm::dbgs() << " Breaking...\n"); - ContentStartColumn = - Token->getContentStartColumn(LineIndex, /*Break=*/true); + // Update the ContentIndent only if the current line was not reflown with + // the previous line, since in that case the previous line should still + // determine the ContentIndent. Also never intent the last line. + if (!Reflow) + ContentIndent = Token->getContentIndent(LineIndex); + LLVM_DEBUG(llvm::dbgs() + << " ContentIndent: " << ContentIndent << "\n"); + ContentStartColumn = ContentIndent + Token->getContentStartColumn( + LineIndex, /*Break=*/true); + unsigned NewRemainingTokenColumns = Token->getRemainingLength( LineIndex, TailOffset + Split.first + Split.second, ContentStartColumn); + if (NewRemainingTokenColumns == 0) { + // No content to indent. + ContentIndent = 0; + ContentStartColumn = + Token->getContentStartColumn(LineIndex, /*Break=*/true); + NewRemainingTokenColumns = Token->getRemainingLength( + LineIndex, TailOffset + Split.first + Split.second, + ContentStartColumn); + } // When breaking before a tab character, it may be moved by a few columns, // but will still be expanded to the next tab stop, so we don't save any @@ -1948,7 +1966,8 @@ ContinuationIndenter::breakProtrudingToken(const FormatToken &Current, LLVM_DEBUG(llvm::dbgs() << " Breaking at: " << TailOffset + Split.first << ", " << Split.second << "\n"); if (!DryRun) - Token->insertBreak(LineIndex, TailOffset, Split, Whitespaces); + Token->insertBreak(LineIndex, TailOffset, Split, ContentIndent, + Whitespaces); Penalty += NewBreakPenalty; TailOffset += Split.first + Split.second; diff --git a/lib/Format/ContinuationIndenter.h b/lib/Format/ContinuationIndenter.h index 4ff05ba99f1a..fde89db864b1 100644 --- a/lib/Format/ContinuationIndenter.h +++ b/lib/Format/ContinuationIndenter.h @@ -107,7 +107,7 @@ private: void moveStateToNewBlock(LineState &State); /// Reformats a raw string literal. - /// + /// /// \returns An extra penalty induced by reformatting the token. unsigned reformatRawStringLiteral(const FormatToken &Current, LineState &State, diff --git a/lib/Format/Format.cpp b/lib/Format/Format.cpp index 59d34308c0a9..9a2da69e89b1 100644 --- a/lib/Format/Format.cpp +++ b/lib/Format/Format.cpp @@ -777,9 +777,11 @@ FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) { { "EqualsProto", "EquivToProto", + "PARSE_PARTIAL_TEXT_PROTO", "PARSE_TEST_PROTO", "PARSE_TEXT_PROTO", "ParseTextOrDie", + "ParseTextProtoOrDie", }, /*CanonicalDelimiter=*/"", /*BasedOnStyle=*/"google", @@ -808,10 +810,9 @@ FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) { GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; GoogleStyle.AlwaysBreakBeforeMultilineStrings = false; GoogleStyle.BreakBeforeTernaryOperators = false; - // taze:, triple slash directives (`/// <...`), @tag followed by { for a lot - // of JSDoc tags, and @see, which is commonly followed by overlong URLs. - GoogleStyle.CommentPragmas = - "(taze:|^/[ \t]*<|(@[A-Za-z_0-9-]+[ \\t]*{)|@see)"; + // taze:, triple slash directives (`/// <...`), @see, which is commonly + // followed by overlong URLs. + GoogleStyle.CommentPragmas = "(taze:|^/[ \t]*<|@see)"; GoogleStyle.MaxEmptyLinesToKeep = 3; GoogleStyle.NamespaceIndentation = FormatStyle::NI_All; GoogleStyle.SpacesInContainerLiterals = false; diff --git a/lib/Frontend/ASTConsumers.cpp b/lib/Frontend/ASTConsumers.cpp index b67c019baed8..2a8bfef68eb9 100644 --- a/lib/Frontend/ASTConsumers.cpp +++ b/lib/Frontend/ASTConsumers.cpp @@ -181,7 +181,7 @@ namespace { void ASTViewer::HandleTopLevelSingleDecl(Decl *D) { if (isa<FunctionDecl>(D) || isa<ObjCMethodDecl>(D)) { D->print(llvm::errs()); - + if (Stmt *Body = D->getBody()) { llvm::errs() << '\n'; Body->viewAST(); diff --git a/lib/Frontend/ASTMerge.cpp b/lib/Frontend/ASTMerge.cpp index 6ec0e2a98c1b..2434113ab0db 100644 --- a/lib/Frontend/ASTMerge.cpp +++ b/lib/Frontend/ASTMerge.cpp @@ -51,9 +51,9 @@ void ASTMergeAction::ExecuteAction() { if (!Unit) continue; - ASTImporter Importer(CI.getASTContext(), + ASTImporter Importer(CI.getASTContext(), CI.getFileManager(), - Unit->getASTContext(), + Unit->getASTContext(), Unit->getFileManager(), /*MinimalImport=*/false); @@ -64,9 +64,9 @@ void ASTMergeAction::ExecuteAction() { if (IdentifierInfo *II = ND->getIdentifier()) if (II->isStr("__va_list_tag") || II->isStr("__builtin_va_list")) continue; - + Decl *ToD = Importer.Import(D); - + if (ToD) { DeclGroupRef DGR(ToD); CI.getASTConsumer().HandleTopLevelDecl(DGR); @@ -88,7 +88,7 @@ ASTMergeAction::ASTMergeAction(std::unique_ptr<FrontendAction> adaptedAction, assert(AdaptedAction && "ASTMergeAction needs an action to adapt"); } -ASTMergeAction::~ASTMergeAction() { +ASTMergeAction::~ASTMergeAction() { } bool ASTMergeAction::usesPreprocessorOnly() const { diff --git a/lib/Frontend/ChainedIncludesSource.cpp b/lib/Frontend/ChainedIncludesSource.cpp index 534c7587f48d..4e8eb32121dc 100644 --- a/lib/Frontend/ChainedIncludesSource.cpp +++ b/lib/Frontend/ChainedIncludesSource.cpp @@ -126,7 +126,7 @@ IntrusiveRefCntPtr<ExternalSemaSource> clang::createChainedIncludesSource( bool firstInclude = (i == 0); std::unique_ptr<CompilerInvocation> CInvok; CInvok.reset(new CompilerInvocation(CI.getInvocation())); - + CInvok->getPreprocessorOpts().ChainedIncludes.clear(); CInvok->getPreprocessorOpts().ImplicitPCHInclude.clear(); CInvok->getPreprocessorOpts().ImplicitPTHInclude.clear(); @@ -134,7 +134,7 @@ IntrusiveRefCntPtr<ExternalSemaSource> clang::createChainedIncludesSource( CInvok->getPreprocessorOpts().Includes.clear(); CInvok->getPreprocessorOpts().MacroIncludes.clear(); CInvok->getPreprocessorOpts().Macros.clear(); - + CInvok->getFrontendOpts().Inputs.clear(); FrontendInputFile InputFile(includes[i], IK); CInvok->getFrontendOpts().Inputs.push_back(InputFile); @@ -193,7 +193,7 @@ IntrusiveRefCntPtr<ExternalSemaSource> clang::createChainedIncludesSource( Clang->setModuleManager(Reader); Clang->getASTContext().setExternalSource(Reader); } - + if (!Clang->InitializeSourceManager(InputFile)) return nullptr; diff --git a/lib/Frontend/CompilerInstance.cpp b/lib/Frontend/CompilerInstance.cpp index 155ead4ac8e8..ecb09da3c1ef 100644 --- a/lib/Frontend/CompilerInstance.cpp +++ b/lib/Frontend/CompilerInstance.cpp @@ -292,7 +292,7 @@ CompilerInstance::createDiagnostics(DiagnosticOptions *Opts, if (!Opts->DiagnosticSerializationFile.empty()) SetupSerializedDiagnostics(Opts, *Diags, Opts->DiagnosticSerializationFile); - + // Configure our handling of diagnostics. ProcessWarningOptions(*Diags, *Opts); @@ -935,7 +935,7 @@ bool CompilerInstance::ExecuteAction(FrontendAction &Act) { // Adjust target options based on codegen options. getTarget().adjustTargetOptions(getCodeGenOpts(), getTargetOpts()); - // rewriter project will change target built-in bool type from its default. + // rewriter project will change target built-in bool type from its default. if (getFrontendOpts().ProgramAction == frontend::RewriteObjC) getTarget().noSignedCharForObjCBool(); @@ -1026,7 +1026,7 @@ static InputKind::Language getLanguageFromOptions(const LangOptions &LangOpts) { return LangOpts.CPlusPlus ? InputKind::CXX : InputKind::C; } -/// Compile a module file for the given module, using the options +/// Compile a module file for the given module, using the options /// provided by the importing compiler instance. Returns true if the module /// was built without errors. static bool @@ -1042,7 +1042,7 @@ compileModuleImpl(CompilerInstance &ImportingInstance, SourceLocation ImportLoc, std::make_shared<CompilerInvocation>(ImportingInstance.getInvocation()); PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts(); - + // For any options that aren't intended to affect how a module is built, // reset them to their default values. Invocation->getLangOpts()->resetNonModularOptions(); @@ -1092,11 +1092,11 @@ compileModuleImpl(CompilerInstance &ImportingInstance, SourceLocation ImportLoc, // Don't free the remapped file buffers; they are owned by our caller. PPOpts.RetainRemappedFileBuffers = true; - + Invocation->getDiagnosticOpts().VerifyDiagnostics = 0; assert(ImportingInstance.getInvocation().getModuleHash() == Invocation->getModuleHash() && "Module hash mismatch!"); - + // Construct a compiler instance that will be used to actually create the // module. Since we're sharing a PCMCache, // CompilerInstance::CompilerInstance is responsible for finalizing the @@ -1172,7 +1172,7 @@ static const FileEntry *getPublicModuleMap(const FileEntry *File, return FileMgr.getFile(PublicFilename); } -/// Compile a module file for the given module, using the options +/// Compile a module file for the given module, using the options /// provided by the importing compiler instance. Returns true if the module /// was built without errors. static bool compileModuleImpl(CompilerInstance &ImportingInstance, @@ -1183,7 +1183,7 @@ static bool compileModuleImpl(CompilerInstance &ImportingInstance, InputKind::ModuleMap); // Get or create the module map that we'll use to build this module. - ModuleMap &ModMap + ModuleMap &ModMap = ImportingInstance.getPreprocessor().getHeaderSearchInfo().getModuleMap(); bool Result; if (const FileEntry *ModuleMapFile = @@ -1327,7 +1327,7 @@ static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro, Module *Mod, SourceLocation ImportLoc) { IdentifierInfo *Id = PP.getIdentifierInfo(ConfigMacro); SourceManager &SourceMgr = PP.getSourceManager(); - + // If this identifier has never had a macro definition, then it could // not have changed. if (!Id->hadMacroDefinition()) @@ -1651,7 +1651,7 @@ CompilerInstance::loadModule(SourceLocation ImportLoc, = KnownModules.find(Path[0].first); if (Known != KnownModules.end()) { // Retrieve the cached top-level module. - Module = Known->second; + Module = Known->second; } else if (ModuleName == getLangOpts().CurrentModule) { // This is the module we're building. Module = PP->getHeaderSearchInfo().lookupModule( @@ -1851,7 +1851,7 @@ CompilerInstance::loadModule(SourceLocation ImportLoc, // Cache the result of this top-level module lookup for later. Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first; } - + // If we never found the module, fail. if (!Module) return ModuleLoadResult(); @@ -1897,13 +1897,13 @@ CompilerInstance::loadModule(SourceLocation ImportLoc, } } } - + if (!Sub) { // Attempt to perform typo correction to find a module name that works. SmallVector<StringRef, 2> Best; unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)(); - - for (clang::Module::submodule_iterator J = Module->submodule_begin(), + + for (clang::Module::submodule_iterator J = Module->submodule_begin(), JEnd = Module->submodule_end(); J != JEnd; ++J) { unsigned ED = Name.edit_distance((*J)->Name, @@ -1914,20 +1914,20 @@ CompilerInstance::loadModule(SourceLocation ImportLoc, Best.clear(); BestEditDistance = ED; } - + Best.push_back((*J)->Name); } } - + // If there was a clear winner, user it. if (Best.size() == 1) { - getDiagnostics().Report(Path[I].second, + getDiagnostics().Report(Path[I].second, diag::err_no_submodule_suggest) << Path[I].first << Module->getFullModuleName() << Best[0] << SourceRange(Path[0].second, Path[I-1].second) << FixItHint::CreateReplacement(SourceRange(Path[I].second), Best[0]); - + Sub = Module->findSubmodule(Best[0]); } } @@ -1940,7 +1940,7 @@ CompilerInstance::loadModule(SourceLocation ImportLoc, << SourceRange(Path[0].second, Path[I-1].second); break; } - + Module = Sub; } } diff --git a/lib/Frontend/DependencyFile.cpp b/lib/Frontend/DependencyFile.cpp index f89722eeb9ed..e6e07190e1ff 100644 --- a/lib/Frontend/DependencyFile.cpp +++ b/lib/Frontend/DependencyFile.cpp @@ -318,7 +318,7 @@ void DFGImpl::InclusionDirective(SourceLocation HashLoc, const FileEntry *File, StringRef SearchPath, StringRef RelativePath, - const Module *Imported, + const Module *Imported, SrcMgr::CharacteristicKind FileType) { if (!File) { if (AddMissingHeaderDeps) diff --git a/lib/Frontend/DependencyGraph.cpp b/lib/Frontend/DependencyGraph.cpp index 660f664447ab..c6c9ac2ea2fa 100644 --- a/lib/Frontend/DependencyGraph.cpp +++ b/lib/Frontend/DependencyGraph.cpp @@ -33,9 +33,9 @@ class DependencyGraphCallback : public PPCallbacks { llvm::SetVector<const FileEntry *> AllFiles; typedef llvm::DenseMap<const FileEntry *, SmallVector<const FileEntry *, 2> > DependencyMap; - + DependencyMap Dependencies; - + private: raw_ostream &writeNodeReference(raw_ostream &OS, const FileEntry *Node); @@ -56,7 +56,7 @@ public: void EndOfMainFile() override { OutputGraphFile(); } - + }; } @@ -75,11 +75,11 @@ void DependencyGraphCallback::InclusionDirective( const FileEntry *File, StringRef SearchPath, StringRef RelativePath, - const Module *Imported, + const Module *Imported, SrcMgr::CharacteristicKind FileType) { if (!File) return; - + SourceManager &SM = PP->getSourceManager(); const FileEntry *FromFile = SM.getFileEntryForID(SM.getFileID(SM.getExpansionLoc(HashLoc))); @@ -87,7 +87,7 @@ void DependencyGraphCallback::InclusionDirective( return; Dependencies[FromFile].push_back(File); - + AllFiles.insert(File); AllFiles.insert(FromFile); } @@ -109,7 +109,7 @@ void DependencyGraphCallback::OutputGraphFile() { } OS << "digraph \"dependencies\" {\n"; - + // Write the nodes for (unsigned I = 0, N = AllFiles.size(); I != N; ++I) { // Write the node itself. @@ -119,15 +119,15 @@ void DependencyGraphCallback::OutputGraphFile() { StringRef FileName = AllFiles[I]->getName(); if (FileName.startswith(SysRoot)) FileName = FileName.substr(SysRoot.size()); - + OS << DOT::EscapeString(FileName) << "\"];\n"; } // Write the edges - for (DependencyMap::iterator F = Dependencies.begin(), + for (DependencyMap::iterator F = Dependencies.begin(), FEnd = Dependencies.end(); - F != FEnd; ++F) { + F != FEnd; ++F) { for (unsigned I = 0, N = F->second.size(); I != N; ++I) { OS.indent(2); writeNodeReference(OS, F->first); diff --git a/lib/Frontend/DiagnosticRenderer.cpp b/lib/Frontend/DiagnosticRenderer.cpp index fb0a92d1f8c6..757ceec7ec9d 100644 --- a/lib/Frontend/DiagnosticRenderer.cpp +++ b/lib/Frontend/DiagnosticRenderer.cpp @@ -172,9 +172,9 @@ void DiagnosticRenderer::emitIncludeStack(FullSourceLoc Loc, PresumedLoc PLoc, // Skip redundant include stacks altogether. if (LastIncludeLoc == IncludeLoc) return; - + LastIncludeLoc = IncludeLoc; - + if (!DiagOpts->ShowNoteIncludeStack && Level == DiagnosticsEngine::Note) return; @@ -199,7 +199,7 @@ void DiagnosticRenderer::emitIncludeStackRecursively(FullSourceLoc Loc) { return; // If this source location was imported from a module, print the module - // import stack rather than the + // import stack rather than the // FIXME: We want submodule granularity here. std::pair<FullSourceLoc, StringRef> Imported = Loc.getModuleImportLoc(); if (!Imported.second.empty()) { diff --git a/lib/Frontend/FrontendAction.cpp b/lib/Frontend/FrontendAction.cpp index a5929424e52a..74550c410396 100644 --- a/lib/Frontend/FrontendAction.cpp +++ b/lib/Frontend/FrontendAction.cpp @@ -288,7 +288,7 @@ static void addHeaderInclude(StringRef HeaderName, Includes += "}\n"; } -/// Collect the set of header includes needed to construct the given +/// Collect the set of header includes needed to construct the given /// module and update the TopHeaders file set of the module. /// /// \param Module The module we're collecting includes from. @@ -345,7 +345,7 @@ static std::error_code collectModuleHeaderIncludes( vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem(); for (vfs::recursive_directory_iterator Dir(FS, DirNative, EC), End; Dir != End && !EC; Dir.increment(EC)) { - // Check whether this entry has an extension typically associated with + // Check whether this entry has an extension typically associated with // headers. if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->getName())) .Cases(".h", ".H", ".hh", ".hpp", true) @@ -358,7 +358,7 @@ static std::error_code collectModuleHeaderIncludes( if (!Header) continue; - // If this header is marked 'unavailable' in this module, don't include + // If this header is marked 'unavailable' in this module, don't include // it. if (ModMap.isHeaderUnavailableInModule(Header, Module)) continue; @@ -431,7 +431,7 @@ static Module *prepareToBuildModule(CompilerInstance &CI, CI.getDiagnostics().Report(diag::err_missing_module_name); // FIXME: Eventually, we could consider asking whether there was just - // a single module described in the module map, and use that as a + // a single module described in the module map, and use that as a // default. Then it would be fairly trivial to just "compile" a module // map with a single module (the common case). return nullptr; diff --git a/lib/Frontend/FrontendActions.cpp b/lib/Frontend/FrontendActions.cpp index 9344e673c7ac..8a8354c7d4c9 100644 --- a/lib/Frontend/FrontendActions.cpp +++ b/lib/Frontend/FrontendActions.cpp @@ -377,7 +377,7 @@ private: if (auto *NamedTemplate = dyn_cast_or_null<NamedDecl>(Inst.Entity)) { llvm::raw_string_ostream OS(Entry.Name); NamedTemplate->getNameForDiagnostic(OS, TheSema.getLangOpts(), true); - const PresumedLoc DefLoc = + const PresumedLoc DefLoc = TheSema.getSourceManager().getPresumedLoc(Inst.Entity->getLocation()); if(!DefLoc.isInvalid()) Entry.DefinitionLocation = std::string(DefLoc.getFilename()) + ":" + @@ -709,13 +709,13 @@ void PrintPreprocessedAction::ExecuteAction() { // the input format has inconsistent line endings. // // This should be a relatively fast operation since most files won't have - // all of their source code on a single line. However, that is still a + // all of their source code on a single line. However, that is still a // concern, so if we scan for too long, we'll just assume the file should // be opened in binary mode. bool BinaryMode = true; bool InvalidFile = false; const SourceManager& SM = CI.getSourceManager(); - const llvm::MemoryBuffer *Buffer = SM.getBuffer(SM.getMainFileID(), + const llvm::MemoryBuffer *Buffer = SM.getBuffer(SM.getMainFileID(), &InvalidFile); if (!InvalidFile) { const char *cur = Buffer->getBufferStart(); @@ -723,7 +723,7 @@ void PrintPreprocessedAction::ExecuteAction() { const char *next = (cur != end) ? cur + 1 : end; // Limit ourselves to only scanning 256 characters into the source - // file. This is mostly a sanity check in case the file has no + // file. This is mostly a sanity check in case the file has no // newlines whatsoever. if (end - cur > 256) end = cur + 256; @@ -774,7 +774,7 @@ void PrintPreambleAction::ExecuteAction() { case InputKind::CUDA: case InputKind::HIP: break; - + case InputKind::Unknown: case InputKind::Asm: case InputKind::LLVM_IR: diff --git a/lib/Frontend/LayoutOverrideSource.cpp b/lib/Frontend/LayoutOverrideSource.cpp index 93e07eb81f72..b31fbd087ba7 100644 --- a/lib/Frontend/LayoutOverrideSource.cpp +++ b/lib/Frontend/LayoutOverrideSource.cpp @@ -23,7 +23,7 @@ static std::string parseName(StringRef S) { unsigned Offset = 1; while (Offset < S.size() && isIdentifierBody(S[Offset])) ++Offset; - + return S.substr(0, Offset).str(); } @@ -31,33 +31,33 @@ LayoutOverrideSource::LayoutOverrideSource(StringRef Filename) { std::ifstream Input(Filename.str().c_str()); if (!Input.is_open()) return; - + // Parse the output of -fdump-record-layouts. std::string CurrentType; Layout CurrentLayout; bool ExpectingType = false; - + while (Input.good()) { std::string Line; getline(Input, Line); - + StringRef LineStr(Line); - // Determine whether the following line will start a + // Determine whether the following line will start a if (LineStr.find("*** Dumping AST Record Layout") != StringRef::npos) { // Flush the last type/layout, if there is one. if (!CurrentType.empty()) Layouts[CurrentType] = CurrentLayout; CurrentLayout = Layout(); - + ExpectingType = true; continue; } - + // If we're expecting a type, grab it. if (ExpectingType) { ExpectingType = false; - + StringRef::size_type Pos; if ((Pos = LineStr.find("struct ")) != StringRef::npos) LineStr = LineStr.substr(Pos + strlen("struct ")); @@ -67,19 +67,19 @@ LayoutOverrideSource::LayoutOverrideSource(StringRef Filename) { LineStr = LineStr.substr(Pos + strlen("union ")); else continue; - + // Find the name of the type. CurrentType = parseName(LineStr); CurrentLayout = Layout(); continue; } - + // Check for the size of the type. StringRef::size_type Pos = LineStr.find(" Size:"); if (Pos != StringRef::npos) { // Skip past the " Size:" prefix. LineStr = LineStr.substr(Pos + strlen(" Size:")); - + unsigned long long Size = 0; (void)LineStr.getAsInteger(10, Size); CurrentLayout.Size = Size; @@ -91,13 +91,13 @@ LayoutOverrideSource::LayoutOverrideSource(StringRef Filename) { if (Pos != StringRef::npos) { // Skip past the "Alignment:" prefix. LineStr = LineStr.substr(Pos + strlen("Alignment:")); - + unsigned long long Alignment = 0; (void)LineStr.getAsInteger(10, Alignment); CurrentLayout.Align = Alignment; continue; } - + // Check for the size/alignment of the type. Pos = LineStr.find("sizeof="); if (Pos != StringRef::npos) { @@ -113,16 +113,16 @@ LayoutOverrideSource::LayoutOverrideSource(StringRef Filename) { if (Pos != StringRef::npos) { /* Skip past the align= prefix. */ LineStr = LineStr.substr(Pos + strlen("align=")); - + // Parse alignment. unsigned long long Alignment = 0; (void)LineStr.getAsInteger(10, Alignment); CurrentLayout.Align = Alignment; } - + continue; } - + // Check for the field offsets of the type. Pos = LineStr.find("FieldOffsets: ["); if (Pos == StringRef::npos) @@ -134,55 +134,55 @@ LayoutOverrideSource::LayoutOverrideSource(StringRef Filename) { unsigned Idx = 1; while (Idx < LineStr.size() && isDigit(LineStr[Idx])) ++Idx; - + unsigned long long Offset = 0; (void)LineStr.substr(0, Idx).getAsInteger(10, Offset); - + CurrentLayout.FieldOffsets.push_back(Offset); - + // Skip over this offset, the following comma, and any spaces. LineStr = LineStr.substr(Idx + 1); while (!LineStr.empty() && isWhitespace(LineStr[0])) LineStr = LineStr.substr(1); } } - + // Flush the last type/layout, if there is one. if (!CurrentType.empty()) Layouts[CurrentType] = CurrentLayout; } -bool +bool LayoutOverrideSource::layoutRecordType(const RecordDecl *Record, uint64_t &Size, uint64_t &Alignment, llvm::DenseMap<const FieldDecl *, uint64_t> &FieldOffsets, llvm::DenseMap<const CXXRecordDecl *, CharUnits> &BaseOffsets, - llvm::DenseMap<const CXXRecordDecl *, CharUnits> &VirtualBaseOffsets) + llvm::DenseMap<const CXXRecordDecl *, CharUnits> &VirtualBaseOffsets) { // We can't override unnamed declarations. if (!Record->getIdentifier()) return false; - + // Check whether we have a layout for this record. llvm::StringMap<Layout>::iterator Known = Layouts.find(Record->getName()); if (Known == Layouts.end()) return false; - + // Provide field layouts. unsigned NumFields = 0; - for (RecordDecl::field_iterator F = Record->field_begin(), + for (RecordDecl::field_iterator F = Record->field_begin(), FEnd = Record->field_end(); F != FEnd; ++F, ++NumFields) { if (NumFields >= Known->second.FieldOffsets.size()) continue; - + FieldOffsets[*F] = Known->second.FieldOffsets[NumFields]; } - + // Wrong number of fields. if (NumFields != Known->second.FieldOffsets.size()) return false; - + Size = Known->second.Size; Alignment = Known->second.Align; return true; @@ -190,7 +190,7 @@ LayoutOverrideSource::layoutRecordType(const RecordDecl *Record, LLVM_DUMP_METHOD void LayoutOverrideSource::dump() { raw_ostream &OS = llvm::errs(); - for (llvm::StringMap<Layout>::iterator L = Layouts.begin(), + for (llvm::StringMap<Layout>::iterator L = Layouts.begin(), LEnd = Layouts.end(); L != LEnd; ++L) { OS << "Type: blah " << L->first() << '\n'; diff --git a/lib/Frontend/MultiplexConsumer.cpp b/lib/Frontend/MultiplexConsumer.cpp index df36c88ec38e..c6e18d9cae21 100644 --- a/lib/Frontend/MultiplexConsumer.cpp +++ b/lib/Frontend/MultiplexConsumer.cpp @@ -107,7 +107,7 @@ public: void DeclarationMarkedOpenMPDeclareTarget(const Decl *D, const Attr *Attr) override; void RedefinedHiddenDefinition(const NamedDecl *D, Module *M) override; - void AddedAttributeToRecord(const Attr *Attr, + void AddedAttributeToRecord(const Attr *Attr, const RecordDecl *Record) override; private: @@ -219,9 +219,9 @@ void MultiplexASTMutationListener::RedefinedHiddenDefinition(const NamedDecl *D, for (auto *L : Listeners) L->RedefinedHiddenDefinition(D, M); } - + void MultiplexASTMutationListener::AddedAttributeToRecord( - const Attr *Attr, + const Attr *Attr, const RecordDecl *Record) { for (auto *L : Listeners) L->AddedAttributeToRecord(Attr, Record); diff --git a/lib/Frontend/PrintPreprocessedOutput.cpp b/lib/Frontend/PrintPreprocessedOutput.cpp index 1b35b32656e7..69cd072ea57f 100644 --- a/lib/Frontend/PrintPreprocessedOutput.cpp +++ b/lib/Frontend/PrintPreprocessedOutput.cpp @@ -160,7 +160,7 @@ public: } bool MoveToLine(unsigned LineNo); - bool AvoidConcat(const Token &PrevPrevTok, const Token &PrevTok, + bool AvoidConcat(const Token &PrevPrevTok, const Token &PrevTok, const Token &Tok) { return ConcatInfo.AvoidConcat(PrevPrevTok, PrevTok, Tok); } @@ -248,7 +248,7 @@ PrintPPOutputPPCallbacks::startNewLineIfNeeded(bool ShouldUpdateCurrentLine) { ++CurLine; return true; } - + return false; } @@ -262,11 +262,11 @@ void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc, // Unless we are exiting a #include, make sure to skip ahead to the line the // #include directive was at. SourceManager &SourceMgr = SM; - + PresumedLoc UserLoc = SourceMgr.getPresumedLoc(Loc); if (UserLoc.isInvalid()) return; - + unsigned NewLine = UserLoc.getLine(); if (Reason == PPCallbacks::EnterFile) { @@ -281,7 +281,7 @@ void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc, // off by one. We can do better by simply incrementing NewLine here. NewLine += 1; } - + CurLine = NewLine; CurFilename.clear(); @@ -292,7 +292,7 @@ void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc, startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false); return; } - + if (!Initialized) { WriteLineInfo(CurLine); Initialized = true; diff --git a/lib/Frontend/Rewrite/FixItRewriter.cpp b/lib/Frontend/Rewrite/FixItRewriter.cpp index 64785e301236..1c2efe63aa19 100644 --- a/lib/Frontend/Rewrite/FixItRewriter.cpp +++ b/lib/Frontend/Rewrite/FixItRewriter.cpp @@ -184,7 +184,7 @@ void FixItRewriter::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, } return; } - + if (!Editor.commit(commit)) { ++NumFailures; Diag(Info.getLocation(), diag::note_fixit_failed); diff --git a/lib/Frontend/Rewrite/FrontendActions.cpp b/lib/Frontend/Rewrite/FrontendActions.cpp index 4d587048f62d..fa17b3e7cb3f 100644 --- a/lib/Frontend/Rewrite/FrontendActions.cpp +++ b/lib/Frontend/Rewrite/FrontendActions.cpp @@ -131,9 +131,9 @@ bool FixItRecompile::BeginInvocation(CompilerInstance &CI) { FixItRewriter Rewriter(CI.getDiagnostics(), CI.getSourceManager(), CI.getLangOpts(), FixItOpts.get()); FixAction->Execute(); - + err = Rewriter.WriteFixedFiles(&RewrittenFiles); - + FixAction->EndSourceFile(); CI.setSourceManager(nullptr); CI.setFileManager(nullptr); diff --git a/lib/Frontend/Rewrite/RewriteModernObjC.cpp b/lib/Frontend/Rewrite/RewriteModernObjC.cpp index 52b979c85f15..36382e1438d5 100644 --- a/lib/Frontend/Rewrite/RewriteModernObjC.cpp +++ b/lib/Frontend/Rewrite/RewriteModernObjC.cpp @@ -39,12 +39,12 @@ using llvm::utostr; namespace { class RewriteModernObjC : public ASTConsumer { protected: - + enum { BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)), block, ... */ BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */ - BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the + BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the __block variable */ BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy helpers */ @@ -52,7 +52,7 @@ namespace { support routines */ BLOCK_BYREF_CURRENT_MAX = 256 }; - + enum { BLOCK_NEEDS_FREE = (1 << 24), BLOCK_HAS_COPY_DISPOSE = (1 << 25), @@ -61,7 +61,7 @@ namespace { BLOCK_IS_GLOBAL = (1 << 28), BLOCK_HAS_DESCRIPTOR = (1 << 29) }; - + Rewriter Rewrite; DiagnosticsEngine &Diags; const LangOptions &LangOpts; @@ -75,7 +75,7 @@ namespace { std::string InFileName; std::unique_ptr<raw_ostream> OutFile; std::string Preamble; - + TypeDecl *ProtocolTypeDecl; VarDecl *GlobalVarDecl; Expr *GlobalConstructionExp; @@ -88,13 +88,13 @@ namespace { // ObjC foreach break/continue generation support. int BcLabelCount; - + unsigned TryFinallyContainsReturnDiag; // Needed for super. ObjCMethodDecl *CurMethodDef; RecordDecl *SuperStructDecl; RecordDecl *ConstantStringDecl; - + FunctionDecl *MsgSendFunctionDecl; FunctionDecl *MsgSendSuperFunctionDecl; FunctionDecl *MsgSendStretFunctionDecl; @@ -118,22 +118,22 @@ namespace { SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen; /// DefinedNonLazyClasses - List of defined "non-lazy" classes. SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses; - + /// DefinedNonLazyCategories - List of defined "non-lazy" categories. SmallVector<ObjCCategoryDecl *, 8> DefinedNonLazyCategories; - + SmallVector<Stmt *, 32> Stmts; SmallVector<int, 8> ObjCBcLabelNo; // Remember all the @protocol(<expr>) expressions. llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls; - + llvm::DenseSet<uint64_t> CopyDestroyCache; // Block expressions. SmallVector<BlockExpr *, 32> Blocks; SmallVector<int, 32> InnerDeclRefsCount; SmallVector<DeclRefExpr *, 32> InnerDeclRefs; - + SmallVector<DeclRefExpr *, 32> BlockDeclRefs; // Block related declarations. @@ -144,11 +144,11 @@ namespace { llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo; llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls; llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls; - + llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs; - llvm::DenseMap<ObjCInterfaceDecl *, + llvm::DenseMap<ObjCInterfaceDecl *, llvm::SmallSetVector<ObjCIvarDecl *, 8> > ReferencedIvars; - + // ivar bitfield grouping containers llvm::DenseSet<const ObjCInterfaceDecl *> ObjCInterefaceHasBitfieldGroups; llvm::DenseMap<const ObjCIvarDecl* , unsigned> IvarGroupNumber; @@ -156,7 +156,7 @@ namespace { // of the struct where the bitfield belongs. llvm::DenseMap<std::pair<const ObjCInterfaceDecl*, unsigned>, QualType> GroupRecordType; SmallVector<FunctionDecl*, 32> FunctionDefinitionsSeen; - + // This maps an original source AST to it's rewritten form. This allows // us to avoid rewriting the same node twice (which is very uncommon). // This is needed to support some of the exotic property rewriting. @@ -167,12 +167,12 @@ namespace { bool SilenceRewriteMacroWarning; bool GenerateLineInfo; bool objc_impl_method; - + bool DisableReplaceStmt; class DisableReplaceStmtScope { RewriteModernObjC &R; bool SavedValue; - + public: DisableReplaceStmtScope(RewriteModernObjC &R) : R(R), SavedValue(R.DisableReplaceStmt) { @@ -237,7 +237,7 @@ namespace { } } } - + void HandleTopLevelSingleDecl(Decl *D); void HandleDeclInMainFile(Decl *D); RewriteModernObjC(std::string inFile, std::unique_ptr<raw_ostream> OS, @@ -314,7 +314,7 @@ namespace { std::string &LineString); void RewriteForwardClassDecl(DeclGroupRef D); void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG); - void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl, + void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl, const std::string &typedefString); void RewriteImplementations(); void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, @@ -341,9 +341,9 @@ namespace { void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl); void RewriteTypeOfDecl(VarDecl *VD); void RewriteObjCQualifiedInterfaceTypes(Expr *E); - + std::string getIvarAccessString(ObjCIvarDecl *D); - + // Expression Rewriting. Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S); Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp); @@ -367,7 +367,7 @@ namespace { Stmt *RewriteContinueStmt(ContinueStmt *S); void RewriteCastExpr(CStyleCastExpr *CE); void RewriteImplicitCastObjCExpr(CastExpr *IE); - + // Computes ivar bitfield group no. unsigned ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV); // Names field decl. for ivar bitfield group. @@ -381,28 +381,28 @@ namespace { QualType SynthesizeBitfieldGroupStructType( ObjCIvarDecl *IV, SmallVectorImpl<ObjCIvarDecl *> &IVars); - + // Block rewriting. void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D); - + // Block specific rewrite rules. void RewriteBlockPointerDecl(NamedDecl *VD); void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl); Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD); Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE); void RewriteBlockPointerFunctionArgs(FunctionDecl *FD); - + void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl, std::string &Result); - + void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result); bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag, bool &IsNamedDefinition); - void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl, + void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl, std::string &Result); - + bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result); - + void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl, std::string &Result); @@ -414,9 +414,9 @@ namespace { ArrayRef<Expr *> Args, SourceLocation StartLoc=SourceLocation(), SourceLocation EndLoc=SourceLocation()); - + Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor, - QualType returnType, + QualType returnType, SmallVectorImpl<QualType> &ArgTypes, SmallVectorImpl<Expr*> &MsgExprs, ObjCMethodDecl *Method); @@ -424,7 +424,7 @@ namespace { Stmt *SynthMessageExpr(ObjCMessageExpr *Exp, SourceLocation StartLoc=SourceLocation(), SourceLocation EndLoc=SourceLocation()); - + void SynthCountByEnumWithState(std::string &buf); void SynthMsgSendFunctionDecl(); void SynthMsgSendSuperFunctionDecl(); @@ -436,7 +436,7 @@ namespace { void SynthGetSuperClassFunctionDecl(); void SynthSelGetUidFunctionDecl(); void SynthSuperConstructorFunctionDecl(); - + // Rewriting metadata template<typename MethodIterator> void RewriteObjCMethodsMetaData(MethodIterator MethodBegin, @@ -450,27 +450,27 @@ namespace { void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl, std::string &Result); void RewriteClassSetupInitHook(std::string &Result); - + void RewriteMetaDataIntoBuffer(std::string &Result); void WriteImageInfo(std::string &Result); void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl, std::string &Result); void RewriteCategorySetupInitHook(std::string &Result); - + // Rewriting ivar void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar, std::string &Result); Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV); - + std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag); std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i, StringRef funcName, std::string Tag); std::string SynthesizeBlockFunc(BlockExpr *CE, int i, StringRef funcName, std::string Tag); - std::string SynthesizeBlockImpl(BlockExpr *CE, + std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag, std::string Desc); - std::string SynthesizeBlockDescriptor(std::string DescTag, + std::string SynthesizeBlockDescriptor(std::string DescTag, std::string ImplTag, int i, StringRef funcName, unsigned hasCopy); @@ -512,18 +512,18 @@ namespace { } return false; } - + bool convertObjCTypeToCStyleType(QualType &T); - + bool needToScanForQualifiers(QualType T); QualType getSuperStructType(); QualType getConstantStringStructType(); QualType convertFunctionTypeOfBlocks(const FunctionType *FT); - + void convertToUnqualifiedObjCType(QualType &T) { if (T->isObjCQualifiedIdType()) { bool isConst = T.isConstQualified(); - T = isConst ? Context->getObjCIdType().withConst() + T = isConst ? Context->getObjCIdType().withConst() : Context->getObjCIdType(); } else if (T->isObjCQualifiedClassType()) @@ -538,7 +538,7 @@ namespace { } } } - + // FIXME: This predicate seems like it would be useful to add to ASTContext. bool isObjCType(QualType T) { if (!LangOpts.ObjC1 && !LangOpts.ObjC2) @@ -562,7 +562,7 @@ namespace { bool PointerTypeTakesAnyObjCQualifiedType(QualType QT); void GetExtentOfArgList(const char *Name, const char *&LParen, const char *&RParen); - + void QuoteDoublequotes(std::string &From, std::string &To) { for (unsigned i = 0; i < From.length(); i++) { if (From[i] == '"') @@ -589,7 +589,7 @@ namespace { return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, nullptr, TInfo, SourceLocation(), SourceLocation()); } - + bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const { IdentifierInfo* II = &Context->Idents.get("load"); Selector LoadSel = Context->Selectors.getSelector(0, &II); @@ -653,7 +653,7 @@ RewriteModernObjC::RewriteModernObjC(std::string inFile, // may break including some headers. GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning, "rewriting block literal declared in global scope is not implemented"); - + TryFinallyContainsReturnDiag = Diags.getCustomDiagID( DiagnosticsEngine::Warning, "rewriter doesn't support user-specified control flow semantics " @@ -756,7 +756,7 @@ void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) { DG.push_back(*DI); else break; - + ++DI; } while (DI != DIEnd); RewriteForwardClassDecl(DG); @@ -781,14 +781,14 @@ void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) { DG.push_back(*DI); else break; - + ++DI; } while (DI != DIEnd); RewriteForwardProtocolDecl(DG); continue; } } - + HandleTopLevelSingleDecl(*DI); ++DI; } @@ -836,28 +836,28 @@ static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl, Result += IvarDecl->getName(); } -std::string +std::string RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) { const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface(); - + // Build name of symbol holding ivar offset. std::string IvarOffsetName; if (D->isBitField()) ObjCIvarBitfieldGroupOffset(D, IvarOffsetName); else WriteInternalIvarName(ClassDecl, D, IvarOffsetName); - + std::string S = "(*("; QualType IvarT = D->getType(); if (D->isBitField()) IvarT = GetGroupRecordTypeForObjCIvarBitfield(D); - + if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) { RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl(); RD = RD->getDefinition(); if (RD && !RD->getDeclName().getAsIdentifierInfo()) { // decltype(((Foo_IMPL*)0)->bar) * - ObjCContainerDecl *CDecl = + ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(D->getDeclContext()); // ivar in class extensions requires special treatment. if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl)) @@ -868,7 +868,7 @@ RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) { RecordDecl::Create(*Context, TTK_Struct, TUDecl, SourceLocation(), SourceLocation(), &Context->Idents.get(RecName)); QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD)); - unsigned UnsignedIntSize = + unsigned UnsignedIntSize = static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy)); Expr *Zero = IntegerLiteral::Create(*Context, llvm::APInt(UnsignedIntSize, 0), @@ -893,7 +893,7 @@ RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) { std::string TypeString(castT.getAsString(Context->getPrintingPolicy())); S += TypeString; S += ")"; - + // ((char *)self + IVAR_OFFSET_SYMBOL_NAME) S += "((char *)self + "; S += IvarOffsetName; @@ -913,7 +913,7 @@ static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP, bool getter) { return getter ? !IMP->getInstanceMethod(PD->getGetterName()) : !IMP->getInstanceMethod(PD->getSetterName()); - + } void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, @@ -922,7 +922,7 @@ void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, static bool objcGetPropertyDefined = false; static bool objcSetPropertyDefined = false; SourceLocation startGetterSetterLoc; - + if (PID->getLocStart().isValid()) { SourceLocation startLoc = PID->getLocStart(); InsertText(startLoc, "// "); @@ -946,7 +946,7 @@ void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, unsigned Attributes = PD->getPropertyAttributes(); if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) { bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) && - (Attributes & (ObjCPropertyDecl::OBJC_PR_retain | + (Attributes & (ObjCPropertyDecl::OBJC_PR_retain | ObjCPropertyDecl::OBJC_PR_copy)); std::string Getr; if (GenGetProperty && !objcGetPropertyDefined) { @@ -955,7 +955,7 @@ void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, Getr = "\nextern \"C\" __declspec(dllimport) " "id objc_getProperty(id, SEL, long, bool);\n"; } - RewriteObjCMethodDecl(OID->getContainingInterface(), + RewriteObjCMethodDecl(OID->getContainingInterface(), PD->getGetterMethodDecl(), Getr); Getr += "{ "; // Synthesize an explicit cast to gain access to the ivar. @@ -969,7 +969,7 @@ void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, Getr += " _TYPE"; if (FPRetType) { Getr += ")"; // close the precedence "scope" for "*". - + // Now, emit the argument types (if any). if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){ Getr += "("; @@ -999,14 +999,14 @@ void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, Getr += "; }"; InsertText(startGetterSetterLoc, Getr); } - - if (PD->isReadOnly() || + + if (PD->isReadOnly() || !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/)) return; // Generate the 'setter' function. std::string Setr; - bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain | + bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain | ObjCPropertyDecl::OBJC_PR_copy); if (GenSetProperty && !objcSetPropertyDefined) { objcSetPropertyDefined = true; @@ -1015,7 +1015,7 @@ void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, "void objc_setProperty (id, SEL, long, id, bool, bool);\n"; } - RewriteObjCMethodDecl(OID->getContainingInterface(), + RewriteObjCMethodDecl(OID->getContainingInterface(), PD->getSetterMethodDecl(), Setr); Setr += "{ "; // Synthesize an explicit cast to initialize the ivar. @@ -1063,9 +1063,9 @@ void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl const std::string &typedefString) { SourceLocation startLoc = ClassDecl->getLocStart(); const char *startBuf = SM->getCharacterData(startLoc); - const char *semiPtr = strchr(startBuf, ';'); + const char *semiPtr = strchr(startBuf, ';'); // Replace the @class with typedefs corresponding to the classes. - ReplaceText(startLoc, semiPtr-startBuf+1, typedefString); + ReplaceText(startLoc, semiPtr-startBuf+1, typedefString); } void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) { @@ -1139,24 +1139,24 @@ void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) { else { ReplaceText(LocStart, 0, "// "); } - + for (auto *I : CatDecl->instance_properties()) RewriteProperty(I); - + for (auto *I : CatDecl->instance_methods()) RewriteMethodDeclaration(I); for (auto *I : CatDecl->class_methods()) RewriteMethodDeclaration(I); // Lastly, comment out the @end. - ReplaceText(CatDecl->getAtEndRange().getBegin(), + ReplaceText(CatDecl->getAtEndRange().getBegin(), strlen("@end"), "/* @end */\n"); } void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) { SourceLocation LocStart = PDecl->getLocStart(); assert(PDecl->isThisDeclarationADefinition()); - + // FIXME: handle protocol headers that are declared across multiple lines. ReplaceText(LocStart, 0, "// "); @@ -1166,7 +1166,7 @@ void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) { RewriteMethodDeclaration(I); for (auto *I : PDecl->instance_properties()) RewriteProperty(I); - + // Lastly, comment out the @end. SourceLocation LocEnd = PDecl->getAtEndRange().getBegin(); ReplaceText(LocEnd, strlen("@end"), "/* @end */\n"); @@ -1196,7 +1196,7 @@ void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) { ReplaceText(LocStart, 0, "// "); } -void +void RewriteModernObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) { SourceLocation LocStart = DG[0]->getLocStart(); if (LocStart.isInvalid()) @@ -1390,11 +1390,11 @@ void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) { // we haven't seen a forward decl - generate a typedef. RewriteOneForwardClassDecl(ClassDecl, ResultStr); RewriteIvarOffsetSymbols(ClassDecl, ResultStr); - + RewriteObjCInternalStruct(ClassDecl, ResultStr); // Mark this typedef as having been written into its c++ equivalent. ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl()); - + for (auto *I : ClassDecl->instance_properties()) RewriteProperty(I); for (auto *I : ClassDecl->instance_methods()) @@ -1403,7 +1403,7 @@ void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) { RewriteMethodDeclaration(I); // Lastly, comment out the @end. - ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"), + ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"), "/* @end */\n"); } } @@ -1431,7 +1431,7 @@ Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseud Base = cast<OpaqueValueExpr>(Base)->getSourceExpr(); Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base)); } - + unsigned numArgs = OldMsg->getNumArgs(); for (unsigned i = 0; i < numArgs; i++) { Expr *Arg = OldMsg->getArg(i); @@ -1869,11 +1869,11 @@ Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) SourceLocation SynchLoc = S->getAtSynchronizedLoc(); ConvertSourceLocationToLineDirective(SynchLoc, buf); buf += "{ id _rethrow = 0; id _sync_obj = (id)"; - + const char *lparenBuf = startBuf; while (*lparenBuf != '(') lparenBuf++; ReplaceText(startLoc, lparenBuf-startBuf+1, buf); - + buf = "; objc_sync_enter(_sync_obj);\n"; buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}"; buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}"; @@ -1887,16 +1887,16 @@ Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc); while (*RParenExprLocBuf != ')') RParenExprLocBuf--; RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf); - + SourceLocation LBranceLoc = S->getSynchBody()->getLocStart(); const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc); assert (*LBraceLocBuf == '{'); ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf); - + SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd(); assert((*SM->getCharacterData(startRBraceLoc) == '}') && "bogus @synchronized block"); - + buf = "} catch (id e) {_rethrow = e;}\n"; Write_RethrowObject(buf); buf += "}\n"; @@ -1923,7 +1923,7 @@ void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S) Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) { SourceLocation startLoc = S->getAtLoc(); ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */"); - ReplaceText(S->getSubStmt()->getLocStart(), 1, + ReplaceText(S->getSubStmt()->getLocStart(), 1, "{ __AtAutoreleasePool __autoreleasepool; "); return nullptr; @@ -1935,7 +1935,7 @@ Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) { std::string buf; SourceLocation TryLocation = S->getAtTryLoc(); ConvertSourceLocationToLineDirective(TryLocation, buf); - + if (finalStmt) { if (noCatch) buf += "{ id volatile _rethrow = 0;\n"; @@ -1953,11 +1953,11 @@ Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) { else // @try -> try ReplaceText(startLoc, 1, ""); - + for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) { ObjCAtCatchStmt *Catch = S->getCatchStmt(I); VarDecl *catchDecl = Catch->getCatchParamDecl(); - + startLoc = Catch->getLocStart(); bool AtRemoved = false; if (catchDecl) { @@ -1968,12 +1968,12 @@ Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) { if (IDecl) { std::string Result; ConvertSourceLocationToLineDirective(Catch->getLocStart(), Result); - + startBuf = SM->getCharacterData(startLoc); assert((*startBuf == '@') && "bogus @catch location"); SourceLocation rParenLoc = Catch->getRParenLoc(); const char *rParenBuf = SM->getCharacterData(rParenLoc); - + // _objc_exc_Foo *_e as argument to catch. Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString(); Result += " *_"; Result += catchDecl->getNameAsString(); @@ -1986,7 +1986,7 @@ Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) { Result += " *"; Result += catchDecl->getNameAsString(); Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)"; Result += "_"; Result += catchDecl->getNameAsString(); - + Result += "; "; SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart(); ReplaceText(lBraceLoc, 1, Result); @@ -1997,12 +1997,12 @@ Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) { if (!AtRemoved) // @catch -> catch ReplaceText(startLoc, 1, ""); - + } if (finalStmt) { buf.clear(); SourceLocation FinallyLoc = finalStmt->getLocStart(); - + if (noCatch) { ConvertSourceLocationToLineDirective(FinallyLoc, buf); buf += "catch (id e) {_rethrow = e;}\n"; @@ -2012,7 +2012,7 @@ Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) { ConvertSourceLocationToLineDirective(FinallyLoc, buf); buf += "catch (id e) {_rethrow = e;}\n"; } - + SourceLocation startFinalLoc = finalStmt->getLocStart(); ReplaceText(startFinalLoc, 8, buf); Stmt *body = finalStmt->getFinallyBody(); @@ -2020,7 +2020,7 @@ Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) { buf.clear(); Write_RethrowObject(buf); ReplaceText(startFinalBodyLoc, 1, buf); - + SourceLocation endFinalBodyLoc = body->getLocEnd(); ReplaceText(endFinalBodyLoc, 1, "}\n}"); // Now check for any return/continue/go statements within the @try. @@ -2102,7 +2102,7 @@ RewriteModernObjC::SynthesizeCallToFunctionDecl(FunctionDecl *FD, // Now, we cast the reference to a pointer to the objc_msgSend type. QualType pToFunc = Context->getPointerType(msgSendType); - ImplicitCastExpr *ICE = + ImplicitCastExpr *ICE = ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay, DRE, nullptr, VK_RValue); @@ -2525,7 +2525,7 @@ void RewriteModernObjC::SynthGetClassFunctionDecl() { // SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls); void RewriteModernObjC::SynthGetSuperClassFunctionDecl() { - IdentifierInfo *getSuperClassIdent = + IdentifierInfo *getSuperClassIdent = &Context->Idents.get("class_getSuperclass"); SmallVector<QualType, 16> ArgTys; ArgTys.push_back(Context->getObjCClassType()); @@ -2602,13 +2602,13 @@ Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) { Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) { unsigned IntSize = static_cast<unsigned>(Context->getTypeSize(Context->IntTy)); - - Expr *FlagExp = IntegerLiteral::Create(*Context, - llvm::APInt(IntSize, Exp->getValue()), + + Expr *FlagExp = IntegerLiteral::Create(*Context, + llvm::APInt(IntSize, Exp->getValue()), Context->IntTy, Exp->getLocation()); CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy, CK_BitCast, FlagExp); - ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(), + ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(), cast); ReplaceStmt(Exp, PE); return PE; @@ -2623,25 +2623,25 @@ Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) { SynthMsgSendFunctionDecl(); if (!GetClassFunctionDecl) SynthGetClassFunctionDecl(); - + FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl; SourceLocation StartLoc = Exp->getLocStart(); SourceLocation EndLoc = Exp->getLocEnd(); - + // Synthesize a call to objc_msgSend(). SmallVector<Expr*, 4> MsgExprs; SmallVector<Expr*, 4> ClsExprs; - + // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument. ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod(); ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface(); - + IdentifierInfo *clsName = BoxingClass->getIdentifier(); ClsExprs.push_back(getStringLiteral(clsName->getName())); CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs, StartLoc, EndLoc); MsgExprs.push_back(Cls); - + // Create a call to sel_registerName("<BoxingMethod>:"), etc. // it will be the 2nd argument. SmallVector<Expr*, 4> SelExprs; @@ -2650,7 +2650,7 @@ Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) { CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl, SelExprs, StartLoc, EndLoc); MsgExprs.push_back(SelExp); - + // User provided sub-expression is the 3rd, and last, argument. Expr *subExpr = Exp->getSubExpr(); if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) { @@ -2662,35 +2662,35 @@ Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) { subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr); } MsgExprs.push_back(subExpr); - + SmallVector<QualType, 4> ArgTypes; ArgTypes.push_back(Context->getObjCClassType()); ArgTypes.push_back(Context->getObjCSelType()); for (const auto PI : BoxingMethod->parameters()) ArgTypes.push_back(PI->getType()); - + QualType returnType = Exp->getType(); // Get the type, we will need to reference it in a couple spots. QualType msgSendType = MsgSendFlavor->getType(); - + // Create a reference to the objc_msgSend() declaration. DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation()); - + CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE); - + // Now do the "normal" pointer to function cast. QualType castType = getSimpleFunctionType(returnType, ArgTypes, BoxingMethod->isVariadic()); castType = Context->getPointerType(castType); cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast, cast); - + // Don't forget the parens to enforce the proper binding. ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast); - + const FunctionType *FT = msgSendType->getAs<FunctionType>(); CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc); @@ -2707,24 +2707,24 @@ Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) { SynthMsgSendFunctionDecl(); if (!GetClassFunctionDecl) SynthGetClassFunctionDecl(); - + FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl; SourceLocation StartLoc = Exp->getLocStart(); SourceLocation EndLoc = Exp->getLocEnd(); - + // Build the expression: __NSContainer_literal(int, ...).arr QualType IntQT = Context->IntTy; QualType NSArrayFType = getSimpleFunctionType(Context->VoidTy, IntQT, true); std::string NSArrayFName("__NSContainer_literal"); FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName); - DeclRefExpr *NSArrayDRE = + DeclRefExpr *NSArrayDRE = new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue, SourceLocation()); SmallVector<Expr*, 16> InitExprs; unsigned NumElements = Exp->getNumElements(); - unsigned UnsignedIntSize = + unsigned UnsignedIntSize = static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy)); Expr *count = IntegerLiteral::Create(*Context, llvm::APInt(UnsignedIntSize, NumElements), @@ -2732,7 +2732,7 @@ Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) { InitExprs.push_back(count); for (unsigned i = 0; i < NumElements; i++) InitExprs.push_back(Exp->getElement(i)); - Expr *NSArrayCallExpr = + Expr *NSArrayCallExpr = new (Context) CallExpr(*Context, NSArrayDRE, InitExprs, NSArrayFType, VK_LValue, SourceLocation()); @@ -2746,27 +2746,27 @@ Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) { MemberExpr(NSArrayCallExpr, false, SourceLocation(), ARRFD, SourceLocation(), ARRFD->getType(), VK_LValue, OK_Ordinary); QualType ConstIdT = Context->getObjCIdType().withConst(); - CStyleCastExpr * ArrayLiteralObjects = - NoTypeInfoCStyleCastExpr(Context, + CStyleCastExpr * ArrayLiteralObjects = + NoTypeInfoCStyleCastExpr(Context, Context->getPointerType(ConstIdT), CK_BitCast, ArrayLiteralME); - + // Synthesize a call to objc_msgSend(). SmallVector<Expr*, 32> MsgExprs; SmallVector<Expr*, 4> ClsExprs; QualType expType = Exp->getType(); - + // Create a call to objc_getClass("NSArray"). It will be th 1st argument. - ObjCInterfaceDecl *Class = + ObjCInterfaceDecl *Class = expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface(); - + IdentifierInfo *clsName = Class->getIdentifier(); ClsExprs.push_back(getStringLiteral(clsName->getName())); CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs, StartLoc, EndLoc); MsgExprs.push_back(Cls); - + // Create a call to sel_registerName("arrayWithObjects:count:"). // it will be the 2nd argument. SmallVector<Expr*, 4> SelExprs; @@ -2776,44 +2776,44 @@ Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) { CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl, SelExprs, StartLoc, EndLoc); MsgExprs.push_back(SelExp); - + // (const id [])objects MsgExprs.push_back(ArrayLiteralObjects); - + // (NSUInteger)cnt Expr *cnt = IntegerLiteral::Create(*Context, llvm::APInt(UnsignedIntSize, NumElements), Context->UnsignedIntTy, SourceLocation()); MsgExprs.push_back(cnt); - + SmallVector<QualType, 4> ArgTypes; ArgTypes.push_back(Context->getObjCClassType()); ArgTypes.push_back(Context->getObjCSelType()); for (const auto *PI : ArrayMethod->parameters()) ArgTypes.push_back(PI->getType()); - + QualType returnType = Exp->getType(); // Get the type, we will need to reference it in a couple spots. QualType msgSendType = MsgSendFlavor->getType(); - + // Create a reference to the objc_msgSend() declaration. DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation()); - + CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE); - + // Now do the "normal" pointer to function cast. QualType castType = getSimpleFunctionType(returnType, ArgTypes, ArrayMethod->isVariadic()); castType = Context->getPointerType(castType); cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast, cast); - + // Don't forget the parens to enforce the proper binding. ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast); - + const FunctionType *FT = msgSendType->getAs<FunctionType>(); CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc); @@ -2830,26 +2830,26 @@ Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral SynthMsgSendFunctionDecl(); if (!GetClassFunctionDecl) SynthGetClassFunctionDecl(); - + FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl; SourceLocation StartLoc = Exp->getLocStart(); SourceLocation EndLoc = Exp->getLocEnd(); - + // Build the expression: __NSContainer_literal(int, ...).arr QualType IntQT = Context->IntTy; QualType NSDictFType = getSimpleFunctionType(Context->VoidTy, IntQT, true); std::string NSDictFName("__NSContainer_literal"); FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName); - DeclRefExpr *NSDictDRE = + DeclRefExpr *NSDictDRE = new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue, SourceLocation()); - + SmallVector<Expr*, 16> KeyExprs; SmallVector<Expr*, 16> ValueExprs; - + unsigned NumElements = Exp->getNumElements(); - unsigned UnsignedIntSize = + unsigned UnsignedIntSize = static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy)); Expr *count = IntegerLiteral::Create(*Context, llvm::APInt(UnsignedIntSize, NumElements), @@ -2861,9 +2861,9 @@ Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral KeyExprs.push_back(Element.Key); ValueExprs.push_back(Element.Value); } - + // (const id [])objects - Expr *NSValueCallExpr = + Expr *NSValueCallExpr = new (Context) CallExpr(*Context, NSDictDRE, ValueExprs, NSDictFType, VK_LValue, SourceLocation()); @@ -2877,13 +2877,13 @@ Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral MemberExpr(NSValueCallExpr, false, SourceLocation(), ARRFD, SourceLocation(), ARRFD->getType(), VK_LValue, OK_Ordinary); QualType ConstIdT = Context->getObjCIdType().withConst(); - CStyleCastExpr * DictValueObjects = - NoTypeInfoCStyleCastExpr(Context, + CStyleCastExpr * DictValueObjects = + NoTypeInfoCStyleCastExpr(Context, Context->getPointerType(ConstIdT), CK_BitCast, DictLiteralValueME); // (const id <NSCopying> [])keys - Expr *NSKeyCallExpr = + Expr *NSKeyCallExpr = new (Context) CallExpr(*Context, NSDictDRE, KeyExprs, NSDictFType, VK_LValue, SourceLocation()); @@ -2891,27 +2891,27 @@ Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral MemberExpr(NSKeyCallExpr, false, SourceLocation(), ARRFD, SourceLocation(), ARRFD->getType(), VK_LValue, OK_Ordinary); - CStyleCastExpr * DictKeyObjects = - NoTypeInfoCStyleCastExpr(Context, + CStyleCastExpr * DictKeyObjects = + NoTypeInfoCStyleCastExpr(Context, Context->getPointerType(ConstIdT), CK_BitCast, DictLiteralKeyME); - + // Synthesize a call to objc_msgSend(). SmallVector<Expr*, 32> MsgExprs; SmallVector<Expr*, 4> ClsExprs; QualType expType = Exp->getType(); - + // Create a call to objc_getClass("NSArray"). It will be th 1st argument. - ObjCInterfaceDecl *Class = + ObjCInterfaceDecl *Class = expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface(); - + IdentifierInfo *clsName = Class->getIdentifier(); ClsExprs.push_back(getStringLiteral(clsName->getName())); CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs, StartLoc, EndLoc); MsgExprs.push_back(Cls); - + // Create a call to sel_registerName("arrayWithObjects:count:"). // it will be the 2nd argument. SmallVector<Expr*, 4> SelExprs; @@ -2920,19 +2920,19 @@ Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl, SelExprs, StartLoc, EndLoc); MsgExprs.push_back(SelExp); - + // (const id [])objects MsgExprs.push_back(DictValueObjects); - + // (const id <NSCopying> [])keys MsgExprs.push_back(DictKeyObjects); - + // (NSUInteger)cnt Expr *cnt = IntegerLiteral::Create(*Context, llvm::APInt(UnsignedIntSize, NumElements), Context->UnsignedIntTy, SourceLocation()); MsgExprs.push_back(cnt); - + SmallVector<QualType, 8> ArgTypes; ArgTypes.push_back(Context->getObjCClassType()); ArgTypes.push_back(Context->getObjCSelType()); @@ -2945,29 +2945,29 @@ Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral } ArgTypes.push_back(T); } - + QualType returnType = Exp->getType(); // Get the type, we will need to reference it in a couple spots. QualType msgSendType = MsgSendFlavor->getType(); - + // Create a reference to the objc_msgSend() declaration. DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation()); - + CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE); - + // Now do the "normal" pointer to function cast. QualType castType = getSimpleFunctionType(returnType, ArgTypes, DictMethod->isVariadic()); castType = Context->getPointerType(castType); cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast, cast); - + // Don't forget the parens to enforce the proper binding. ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast); - + const FunctionType *FT = msgSendType->getAs<FunctionType>(); CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc); @@ -2975,8 +2975,8 @@ Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral return CE; } -// struct __rw_objc_super { -// struct objc_object *object; struct objc_object *superClass; +// struct __rw_objc_super { +// struct objc_object *object; struct objc_object *superClass; // }; QualType RewriteModernObjC::getSuperStructType() { if (!SuperStructDecl) { @@ -3057,9 +3057,9 @@ static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R, } void RewriteModernObjC::RewriteLineDirective(const Decl *D) { - + SourceLocation Location = D->getLocation(); - + if (Location.isFileID() && GenerateLineInfo) { std::string LineString("\n#line "); PresumedLoc PLoc = SM->getPresumedLoc(Location); @@ -3069,7 +3069,7 @@ void RewriteModernObjC::RewriteLineDirective(const Decl *D) { if (isa<ObjCMethodDecl>(D)) LineString += "\""; else LineString += "\"\n"; - + Location = D->getLocStart(); if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { if (FD->isExternC() && !FD->isMain()) { @@ -3091,11 +3091,11 @@ void RewriteModernObjC::RewriteLineDirective(const Decl *D) { /// msgSendType - function type of objc_msgSend_stret(...) /// returnType - Result type of the method being synthesized. /// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type. -/// MsgExprs - list of argument expressions being passed to objc_msgSend_stret, +/// MsgExprs - list of argument expressions being passed to objc_msgSend_stret, /// starting with receiver. /// Method - Method being rewritten. Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor, - QualType returnType, + QualType returnType, SmallVectorImpl<QualType> &ArgTypes, SmallVectorImpl<Expr*> &MsgExprs, ObjCMethodDecl *Method) { @@ -3104,11 +3104,11 @@ Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFla Method ? Method->isVariadic() : false); castType = Context->getPointerType(castType); - + // build type for containing the objc_msgSend_stret object. static unsigned stretCount=0; std::string name = "__Stret"; name += utostr(stretCount); - std::string str = + std::string str = "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n"; str += "namespace {\n"; str += "struct "; str += name; @@ -3127,13 +3127,13 @@ Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFla Context->getPrintingPolicy()); str += ", "; str += ArgName; } - + str += ") {\n"; str += "\t unsigned size = sizeof("; str += returnType.getAsString(Context->getPrintingPolicy()); str += ");\n"; - + str += "\t if (size == 1 || size == 2 || size == 4 || size == 8)\n"; - + str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy()); str += ")(void *)objc_msgSend)(receiver, sel"; for (unsigned i = 2; i < ArgTypes.size(); i++) { @@ -3144,11 +3144,11 @@ Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFla str += ", arg"; str += utostr(i); } str+= ");\n"; - + str += "\t else if (receiver == 0)\n"; str += "\t memset((void*)&s, 0, sizeof(s));\n"; str += "\t else\n"; - + str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy()); str += ")(void *)objc_msgSend_stret)(receiver, sel"; for (unsigned i = 2; i < ArgTypes.size(); i++) { @@ -3159,7 +3159,7 @@ Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFla str += ", arg"; str += utostr(i); } str += ");\n"; - + str += "\t}\n"; str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy()); str += " s;\n"; @@ -3174,7 +3174,7 @@ Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFla InsertText(FunLocStart, str); ++stretCount; - + // AST for __Stretn(receiver, args).s; IdentifierInfo *ID = &Context->Idents.get(name); FunctionDecl *FD = FunctionDecl::Create(*Context, TUDecl, SourceLocation(), @@ -3266,7 +3266,7 @@ Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp, ClsExprs.push_back(Cls); Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs, StartLoc, EndLoc); - + // (id)class_getSuperclass((Class)objc_getClass("CurrentClass")) // To turn off a warning, type-cast to 'id' InitExprs.push_back( // set 'super class', using class_getSuperclass(). @@ -3350,7 +3350,7 @@ Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp, Context->getObjCIdType(), VK_RValue, SourceLocation())) ); // set the 'receiver'. - + // (id)class_getSuperclass((Class)objc_getClass("CurrentClass")) SmallVector<Expr*, 8> ClsExprs; ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName())); @@ -3361,7 +3361,7 @@ Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp, ClsExprs.push_back(Cls); Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs, StartLoc, EndLoc); - + // (id)class_getSuperclass((Class)objc_getClass("CurrentClass")) // To turn off a warning, type-cast to 'id' InitExprs.push_back( @@ -3446,7 +3446,7 @@ Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp, (void)convertBlockPointerToFunctionPointer(type); const Expr *SubExpr = ICE->IgnoreParenImpCasts(); CastKind CK; - if (SubExpr->getType()->isIntegralType(*Context) && + if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType()) { CK = CK_IntegralToBoolean; } else if (type->isObjCObjectPointerType()) { @@ -3591,7 +3591,7 @@ QualType RewriteModernObjC::getProtocolType() { /// The forward references (and metadata) are generated in /// RewriteModernObjC::HandleTranslationUnit(). Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) { - std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" + + std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" + Exp->getProtocol()->getNameAsString(); IdentifierInfo *ID = &Context->Idents.get(Name); VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(), @@ -3608,9 +3608,9 @@ Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) { return castExpr; } -/// IsTagDefinedInsideClass - This routine checks that a named tagged type -/// is defined inside an objective-c class. If so, it returns true. -bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, +/// IsTagDefinedInsideClass - This routine checks that a named tagged type +/// is defined inside an objective-c class. If so, it returns true. +bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag, bool &IsNamedDefinition) { if (!IDecl) @@ -3638,13 +3638,13 @@ bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, /// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer. /// It handles elaborated types, as well as enum types in the process. -bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type, +bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type, std::string &Result) { if (isa<TypedefType>(Type)) { Result += "\t"; return false; } - + if (Type->isArrayType()) { QualType ElemTy = Context->getBaseElementType(Type); return RewriteObjCFieldDeclType(ElemTy, Result); @@ -3658,7 +3658,7 @@ bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type, Result += "\n\tunion "; else assert(false && "class not allowed as an ivar type"); - + Result += RD->getName(); if (GlobalDefinedTags.count(RD)) { // struct/union is defined globally, use it. @@ -3668,7 +3668,7 @@ bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type, Result += " {\n"; for (auto *FD : RD->fields()) RewriteObjCFieldDecl(FD, Result); - Result += "\t} "; + Result += "\t} "; return true; } } @@ -3682,7 +3682,7 @@ bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type, Result += " "; return true; } - + Result += " {\n"; for (const auto *EC : ED->enumerators()) { Result += "\t"; Result += EC->getName(); Result += " = "; @@ -3690,11 +3690,11 @@ bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type, Result += Val.toString(10); Result += ",\n"; } - Result += "\t} "; + Result += "\t} "; return true; } } - + Result += "\t"; convertObjCTypeToCStyleType(Type); return false; @@ -3703,12 +3703,12 @@ bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type, /// RewriteObjCFieldDecl - This routine rewrites a field into the buffer. /// It handles elaborated types, as well as enum types in the process. -void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl, +void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result) { QualType Type = fieldDecl->getType(); std::string Name = fieldDecl->getNameAsString(); - - bool EleboratedType = RewriteObjCFieldDeclType(Type, Result); + + bool EleboratedType = RewriteObjCFieldDeclType(Type, Result); if (!EleboratedType) Type.getAsStringInternal(Name, Context->getPrintingPolicy()); Result += Name; @@ -3727,20 +3727,20 @@ void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl, AT = Context->getAsArrayType(AT->getElementType()); } while (AT); } - + Result += ";\n"; } /// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined /// named aggregate types into the input buffer. -void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl, +void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl, std::string &Result) { QualType Type = fieldDecl->getType(); if (isa<TypedefType>(Type)) return; if (Type->isArrayType()) Type = Context->getBaseElementType(Type); - ObjCContainerDecl *IDecl = + ObjCContainerDecl *IDecl = dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext()); TagDecl *TD = nullptr; @@ -3750,11 +3750,11 @@ void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDec else if (Type->isEnumeralType()) { TD = Type->getAs<EnumType>()->getDecl(); } - + if (TD) { if (GlobalDefinedTags.count(TD)) return; - + bool IsNamedDefinition = false; if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) { RewriteObjCFieldDeclType(Type, Result); @@ -3775,7 +3775,7 @@ unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) { for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin(); IVD; IVD = IVD->getNextIvar()) IVars.push_back(IVD); - + for (unsigned i = 0, e = IVars.size(); i < e; i++) if (IVars[i]->isBitField()) { IvarGroupNumber[IVars[i++]] = ++GroupNo; @@ -3816,7 +3816,7 @@ QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl * std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo); if (GroupRecordType.count(tuple)) return GroupRecordType[tuple]; - + SmallVector<ObjCIvarDecl *, 8> IVars; for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin(); IVD; IVD = IVD->getNextIvar()) { @@ -3840,7 +3840,7 @@ QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl * } QualType RetQT = GroupRecordType[tuple]; assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL"); - + return RetQT; } @@ -3895,13 +3895,13 @@ void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl, for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin(); IVD; IVD = IVD->getNextIvar()) IVars.push_back(IVD); - + SourceLocation LocStart = CDecl->getLocStart(); SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc(); - + const char *startBuf = SM->getCharacterData(LocStart); const char *endBuf = SM->getCharacterData(LocEnd); - + // If no ivars and no root or if its root, directly or indirectly, // have no ivars (thus not synthesized) then no need to synthesize this class. if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) && @@ -3910,13 +3910,13 @@ void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl, ReplaceText(LocStart, endBuf-startBuf, Result); return; } - + // Insert named struct/union definitions inside class to // outer scope. This follows semantics of locally defined // struct/unions in objective-c classes. for (unsigned i = 0, e = IVars.size(); i < e; i++) RewriteLocallyDefinedNamedAggregates(IVars[i], Result); - + // Insert named structs which are syntheized to group ivar bitfields // to outer scope as well. for (unsigned i = 0, e = IVars.size(); i < e; i++) @@ -3928,17 +3928,17 @@ void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl, // skip over ivar bitfields in this group. SKIP_BITFIELDS(i , e, IVars); } - + Result += "\nstruct "; Result += CDecl->getNameAsString(); Result += "_IMPL {\n"; - + if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) { Result += "\tstruct "; Result += RCDecl->getNameAsString(); Result += "_IMPL "; Result += RCDecl->getNameAsString(); Result += "_IVARS;\n"; } - + for (unsigned i = 0, e = IVars.size(); i < e; i++) { if (IVars[i]->isBitField()) { ObjCIvarDecl *IV = IVars[i]; @@ -3984,7 +3984,7 @@ void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl, if (LangOpts.MicrosoftExt) Result += "__declspec(allocate(\".objc_ivar$B\")) "; Result += "extern \"C\" "; - if (LangOpts.MicrosoftExt && + if (LangOpts.MicrosoftExt && IvarDecl->getAccessControl() != ObjCIvarDecl::Private && IvarDecl->getAccessControl() != ObjCIvarDecl::Package) Result += "__declspec(dllimport) "; @@ -4031,14 +4031,14 @@ void RewriteModernObjC::RewriteImplementations() { } } -void RewriteModernObjC::RewriteByRefString(std::string &ResultStr, +void RewriteModernObjC::RewriteByRefString(std::string &ResultStr, const std::string &Name, ValueDecl *VD, bool def) { - assert(BlockByRefDeclNo.count(VD) && + assert(BlockByRefDeclNo.count(VD) && "RewriteByRefString: ByRef decl missing"); if (def) ResultStr += "struct "; - ResultStr += "__Block_byref_" + Name + + ResultStr += "__Block_byref_" + Name + "_" + utostr(BlockByRefDeclNo[VD]) ; } @@ -4057,7 +4057,7 @@ std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i, SourceLocation BlockLoc = CE->getExprLoc(); std::string S; ConvertSourceLocationToLineDirective(BlockLoc, S); - + S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" + funcName.str() + "_block_func_" + utostr(i); @@ -4132,7 +4132,7 @@ std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i, if (HasLocalVariableExternalStorage(*I)) QT = Context->getPointerType(QT); QT.getAsStringInternal(Name, Context->getPrintingPolicy()); - S += Name + " = __cself->" + + S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n"; } } @@ -4168,7 +4168,7 @@ std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i, S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);"; } S += "}\n"; - + S += "\nstatic void __"; S += funcName; S += "_block_dispose_" + utostr(i); @@ -4188,7 +4188,7 @@ std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i, return S; } -std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag, +std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag, std::string Desc) { std::string S = "\nstruct " + Tag; std::string Constructor = " " + Tag; @@ -4277,7 +4277,7 @@ std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Ta Constructor += ", "; Constructor += Name + "(_" + Name + "->__forwarding)"; } - + Constructor += " {\n"; if (GlobalVarDecl) Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n"; @@ -4303,19 +4303,19 @@ std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Ta return S; } -std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag, +std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag, std::string ImplTag, int i, StringRef FunName, unsigned hasCopy) { std::string S = "\nstatic struct " + DescTag; - + S += " {\n size_t reserved;\n"; S += " size_t Block_size;\n"; if (hasCopy) { S += " void (*copy)(struct "; S += ImplTag; S += "*, struct "; S += ImplTag; S += "*);\n"; - + S += " void (*dispose)(struct "; S += ImplTag; S += "*);\n"; } @@ -4343,7 +4343,7 @@ void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart, SC += "() {}"; InsertText(FunLocStart, SC); } - + // Insert closures that were part of the function. for (unsigned i = 0, count=0; i < Blocks.size(); i++) { CollectBlockDeclRefInfo(Blocks[i]); @@ -4368,7 +4368,7 @@ void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart, // imported objects in the inner blocks not used in the outer // blocks must be copied/disposed in the outer block as well. - if (VD->getType()->isObjCObjectPointerType() || + if (VD->getType()->isObjCObjectPointerType() || VD->getType()->isBlockPointerType()) ImportedBlockDecls.insert(VD); } @@ -4415,7 +4415,7 @@ void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart, } if (GlobalConstructionExp) { // extra fancy dance for global literal expression. - + // Always the latest block expression on the block stack. std::string Tag = "__"; Tag += FunName; @@ -4424,7 +4424,7 @@ void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart, std::string globalBuf = "static "; globalBuf += Tag; globalBuf += " "; std::string SStr; - + llvm::raw_string_ostream constructorExprBuf(SStr); GlobalConstructionExp->printPretty(constructorExprBuf, nullptr, PrintingPolicy(LangOpts)); @@ -4441,7 +4441,7 @@ void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart, } void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) { - SourceLocation FunLocStart = + SourceLocation FunLocStart = (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD) : FD->getTypeSpecStartLoc(); StringRef FuncName = FD->getName(); @@ -4528,7 +4528,7 @@ bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) { } } } - + convertToUnqualifiedObjCType(T); return T != oldT; } @@ -4544,7 +4544,7 @@ QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) SmallVector<QualType, 8> ArgTypes; QualType Res = FT->getReturnType(); bool modified = convertObjCTypeToCStyleType(Res); - + if (FTP) { for (auto &I : FTP->param_types()) { QualType t = I; @@ -4569,13 +4569,13 @@ Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp CPT = DRE->getType()->getAs<BlockPointerType>(); } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) { CPT = MExpr->getType()->getAs<BlockPointerType>(); - } + } else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) { return SynthesizeBlockCall(Exp, PRE->getSubExpr()); } - else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp)) + else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp)) CPT = IEXPR->getType()->getAs<BlockPointerType>(); - else if (const ConditionalOperator *CEXPR = + else if (const ConditionalOperator *CEXPR = dyn_cast<ConditionalOperator>(BlockExp)) { Expr *LHSExp = CEXPR->getLHS(); Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp); @@ -4676,7 +4676,7 @@ Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp // }; //} Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) { - // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR + // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR // for each DeclRefExp where BYREFVAR is name of the variable. ValueDecl *VD = DeclRefExp->getDecl(); bool isArrow = DeclRefExp->refersToEnclosingVariableOrCapture() || @@ -4684,7 +4684,7 @@ Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) { FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(), - &Context->Idents.get("__forwarding"), + &Context->Idents.get("__forwarding"), Context->VoidPtrTy, nullptr, /*BitWidth=*/nullptr, /*Mutable=*/true, ICIS_NoInit); @@ -4694,7 +4694,7 @@ Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) { StringRef Name = VD->getName(); FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(), - &Context->Idents.get(Name), + &Context->Idents.get(Name), Context->VoidPtrTy, nullptr, /*BitWidth=*/nullptr, /*Mutable=*/true, ICIS_NoInit); @@ -4703,14 +4703,14 @@ Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) { DeclRefExp->getType(), VK_LValue, OK_Ordinary); // Need parens to enforce precedence. - ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(), - DeclRefExp->getExprLoc(), + ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(), + DeclRefExp->getExprLoc(), ME); ReplaceStmt(DeclRefExp, PE); return PE; } -// Rewrites the imported local variable V with external storage +// Rewrites the imported local variable V with external storage // (static, extern, etc.) as *V // Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) { @@ -4722,7 +4722,7 @@ Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) { VK_LValue, OK_Ordinary, DRE->getLocation(), false); // Need parens to enforce precedence. - ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), + ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), Exp); ReplaceStmt(DRE, PE); return PE; @@ -4771,7 +4771,7 @@ void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) { if (CastKind != CK_BlockPointerToObjCPointerCast && CastKind != CK_AnyPointerToBlockPointerCast) return; - + QualType QT = IC->getType(); (void)convertBlockPointerToFunctionPointer(QT); std::string TypeString(QT.getAsString(Context->getPrintingPolicy())); @@ -4851,7 +4851,7 @@ bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) { I->getPointeeType()->isObjCQualifiedInterfaceType()) return true; } - + } return false; } @@ -4917,7 +4917,7 @@ void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) { } buf += ')'; OrigLength++; - + if (PointerTypeTakesAnyBlockArguments(DeclT) || PointerTypeTakesAnyObjCQualifiedType(DeclT)) { // Replace the '^' with '*' for arguments. @@ -4930,7 +4930,7 @@ void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) { if (*argListBegin == '^') buf += '*'; else if (*argListBegin == '<') { - buf += "/*"; + buf += "/*"; buf += *argListBegin++; OrigLength++; while (*argListBegin != '>') { @@ -4954,19 +4954,19 @@ void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) { /// SynthesizeByrefCopyDestroyHelper - This routine synthesizes: /// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst, /// struct Block_byref_id_object *src) { -/// _Block_object_assign (&_dest->object, _src->object, +/// _Block_object_assign (&_dest->object, _src->object, /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT /// [|BLOCK_FIELD_IS_WEAK]) // object -/// _Block_object_assign(&_dest->object, _src->object, +/// _Block_object_assign(&_dest->object, _src->object, /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK /// [|BLOCK_FIELD_IS_WEAK]) // block /// } /// And: /// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) { -/// _Block_object_dispose(_src->object, +/// _Block_object_dispose(_src->object, /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT /// [|BLOCK_FIELD_IS_WEAK]) // object -/// _Block_object_dispose(_src->object, +/// _Block_object_dispose(_src->object, /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK /// [|BLOCK_FIELD_IS_WEAK]) // block /// } @@ -4980,14 +4980,14 @@ std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD, S = "static void __Block_byref_id_object_copy_"; S += utostr(flag); S += "(void *dst, void *src) {\n"; - + // offset into the object pointer is computed as: // void * + void* + int + int + void* + void * - unsigned IntSize = + unsigned IntSize = static_cast<unsigned>(Context->getTypeSize(Context->IntTy)); - unsigned VoidPtrSize = + unsigned VoidPtrSize = static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy)); - + unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth(); S += " _Block_object_assign((char*)dst + "; S += utostr(offset); @@ -4996,7 +4996,7 @@ std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD, S += "), "; S += utostr(flag); S += ");\n}\n"; - + S += "static void __Block_byref_id_object_dispose_"; S += utostr(flag); S += "(void *src) {\n"; @@ -5021,8 +5021,8 @@ std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD, /// }; /// /// It then replaces declaration of ND variable with: -/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag, -/// __size=sizeof(struct __Block_byref_ND), +/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag, +/// __size=sizeof(struct __Block_byref_ND), /// ND=initializer-if-any}; /// /// @@ -5048,7 +5048,7 @@ void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl, ByrefType += " *__forwarding;\n"; ByrefType += " int __flags;\n"; ByrefType += " int __size;\n"; - // Add void *__Block_byref_id_object_copy; + // Add void *__Block_byref_id_object_copy; // void *__Block_byref_id_object_dispose; if needed. QualType Ty = ND->getType(); bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND); @@ -5060,7 +5060,7 @@ void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl, QualType T = Ty; (void)convertBlockPointerToFunctionPointer(T); T.getAsStringInternal(Name, Context->getPrintingPolicy()); - + ByrefType += " " + Name + ";\n"; ByrefType += "};\n"; // Insert this type in global scope. It is needed by helper function. @@ -5072,7 +5072,7 @@ void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl, FunLocStart = CurMethodDef->getLocStart(); } InsertText(FunLocStart, ByrefType); - + if (Ty.isObjCGCWeak()) { flag |= BLOCK_FIELD_IS_WEAK; isa = 1; @@ -5089,9 +5089,9 @@ void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl, if (!HF.empty()) Preamble += HF; } - - // struct __Block_byref_ND ND = - // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND), + + // struct __Block_byref_ND ND = + // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND), // initializer-if-any}; bool hasInit = (ND->getInit() != nullptr); // FIXME. rewriter does not support __block c++ objects which @@ -5102,7 +5102,7 @@ void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl, if (CXXDecl && CXXDecl->isDefaultConstructor()) hasInit = false; } - + unsigned flags = 0; if (HasCopyAndDispose) flags |= BLOCK_HAS_COPY_DISPOSE; @@ -5125,7 +5125,7 @@ void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl, ByrefType += ", __Block_byref_id_object_dispose_"; ByrefType += utostr(flag); } - + if (!firstDecl) { // In multiple __block declarations, and for all but 1st declaration, // find location of the separating comma. This would be start location @@ -5139,7 +5139,7 @@ void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl, DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf); startBuf = commaBuf; } - + if (!hasInit) { ByrefType += "};\n"; unsigned nameSize = Name.size(); @@ -5164,11 +5164,11 @@ void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl, const char separator = lastDecl ? ';' : ','; const char *startInitializerBuf = SM->getCharacterData(startLoc); const char *separatorBuf = strchr(startInitializerBuf, separator); - assert((*separatorBuf == separator) && + assert((*separatorBuf == separator) && "RewriteByRefVar: can't find ';' or ','"); SourceLocation separatorLoc = startLoc.getLocWithOffset(separatorBuf-startInitializerBuf); - + InsertText(separatorLoc, lastDecl ? "}" : "};\n"); } } @@ -5196,7 +5196,7 @@ void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) { // Find any imported blocks...they will need special attention. for (unsigned i = 0; i < BlockDeclRefs.size(); i++) if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() || - BlockDeclRefs[i]->getType()->isObjCObjectPointerType() || + BlockDeclRefs[i]->getType()->isObjCObjectPointerType() || BlockDeclRefs[i]->getType()->isBlockPointerType()) ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl()); } @@ -5213,11 +5213,11 @@ FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) { Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp, const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) { const BlockDecl *block = Exp->getBlockDecl(); - + Blocks.push_back(Exp); CollectBlockDeclRefInfo(Exp); - + // Add inner imported variables now used in current block. int countOfInnerDecls = 0; if (!InnerBlockDeclRefs.empty()) { @@ -5243,12 +5243,12 @@ Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp, // Find any imported blocks...they will need special attention. for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() || - InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() || + InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() || InnerBlockDeclRefs[i]->getType()->isBlockPointerType()) ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl()); } InnerDeclRefsCount.push_back(countOfInnerDecls); - + std::string FuncName; if (CurFunctionDef) @@ -5258,14 +5258,14 @@ Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp, else if (GlobalVarDecl) FuncName = std::string(GlobalVarDecl->getNameAsString()); - bool GlobalBlockExpr = + bool GlobalBlockExpr = block->getDeclContext()->getRedeclContext()->isFileContext(); - + if (GlobalBlockExpr && !GlobalVarDecl) { Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag); GlobalBlockExpr = false; } - + std::string BlockNumber = utostr(Blocks.size()-1); std::string Func = "__" + FuncName + "_block_func_" + BlockNumber; @@ -5279,13 +5279,13 @@ Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp, // Simulate a constructor call... std::string Tag; - + if (GlobalBlockExpr) Tag = "__global_"; else Tag = "__"; Tag += FuncName + "_block_impl_" + BlockNumber; - + FD = SynthBlockInitFunctionDecl(Tag); DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue, SourceLocation()); @@ -5310,13 +5310,13 @@ Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp, new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false, Context->VoidPtrTy, VK_LValue, - SourceLocation()), + SourceLocation()), UO_AddrOf, - Context->getPointerType(Context->VoidPtrTy), + Context->getPointerType(Context->VoidPtrTy), VK_RValue, OK_Ordinary, SourceLocation(), false); - InitExprs.push_back(DescRefExpr); - + InitExprs.push_back(DescRefExpr); + // Add initializers for any closure decl refs. if (BlockDeclRefs.size()) { Expr *Exp; @@ -5352,7 +5352,7 @@ Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp, OK_Ordinary, SourceLocation(), false); } - + } InitExprs.push_back(Exp); } @@ -5363,14 +5363,14 @@ Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp, std::string Name(ND->getNameAsString()); std::string RecName; RewriteByRefString(RecName, Name, ND, true); - IdentifierInfo *II = &Context->Idents.get(RecName.c_str() + IdentifierInfo *II = &Context->Idents.get(RecName.c_str() + sizeof("struct")); RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl, SourceLocation(), SourceLocation(), II); assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl"); QualType castT = Context->getPointerType(Context->getTagDeclType(RD)); - + FD = SynthBlockInitFunctionDecl((*I)->getName()); Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue, SourceLocation()); @@ -5379,7 +5379,7 @@ Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp, for (const auto &CI : block->captures()) { const VarDecl *variable = CI.getVariable(); if (variable == ND && CI.isNested()) { - assert (CI.isByRef() && + assert (CI.isByRef() && "SynthBlockInitExpr - captured block variable is not byref"); isNestedCapturedVar = true; break; @@ -5399,22 +5399,22 @@ Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp, if (ImportedBlockDecls.size()) { // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR); - unsigned IntSize = + unsigned IntSize = static_cast<unsigned>(Context->getTypeSize(Context->IntTy)); - Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag), + Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag), Context->IntTy, SourceLocation()); InitExprs.push_back(FlagExp); } NewRep = new (Context) CallExpr(*Context, DRE, InitExprs, FType, VK_LValue, SourceLocation()); - + if (GlobalBlockExpr) { assert (!GlobalConstructionExp && "SynthBlockInitExpr - GlobalConstructionExp must be null"); GlobalConstructionExp = NewRep; NewRep = DRE; } - + NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf, Context->getPointerType(NewRep->getType()), VK_RValue, OK_Ordinary, SourceLocation(), false); @@ -5423,7 +5423,7 @@ Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp, // Put Paren around the call. NewRep = new (Context) ParenExpr(SourceLocation(), SourceLocation(), NewRep); - + BlockDeclRefs.clear(); BlockByRefDecls.clear(); BlockByRefDeclsPtrSet.clear(); @@ -5434,7 +5434,7 @@ Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp, } bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) { - if (const ObjCForCollectionStmt * CS = + if (const ObjCForCollectionStmt * CS = dyn_cast<ObjCForCollectionStmt>(Stmts.back())) return CS->getElement() == DS; return false; @@ -5506,7 +5506,7 @@ Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) { RewrittenBlockExprs[BE] = Str; Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs); - + //blockTranscribed->dump(); ReplaceStmt(S, blockTranscribed); return blockTranscribed; @@ -5520,17 +5520,17 @@ Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) { if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S)) return RewriteObjCStringLiteral(AtString); - + if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S)) return RewriteObjCBoolLiteralExpr(BoolLitExpr); - + if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S)) return RewriteObjCBoxedExpr(BoxedExpr); - + if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S)) return RewriteObjCArrayLiteralExpr(ArrayLitExpr); - - if (ObjCDictionaryLiteral *DictionaryLitExpr = + + if (ObjCDictionaryLiteral *DictionaryLitExpr = dyn_cast<ObjCDictionaryLiteral>(S)) return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr); @@ -5557,11 +5557,11 @@ Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) { return RewriteMessageExpr(MessExpr); } - if (ObjCAutoreleasePoolStmt *StmtAutoRelease = + if (ObjCAutoreleasePoolStmt *StmtAutoRelease = dyn_cast<ObjCAutoreleasePoolStmt>(S)) { return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease); } - + if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S)) return RewriteObjCTryStmt(StmtTry); @@ -5595,7 +5595,7 @@ Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) { // the context of an ObjCForCollectionStmt. For example: // NSArray *someArray; // for (id <FooProtocol> index in someArray) ; - // This is because RewriteObjCForCollectionStmt() does textual rewriting + // This is because RewriteObjCForCollectionStmt() does textual rewriting // and it depends on the original text locations/positions. if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS)) RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin()); @@ -5617,7 +5617,7 @@ Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) { BlockByRefDeclNo[ND] = uniqueByrefDeclCount++; RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE)); } - else + else RewriteTypeOfDecl(VD); } } @@ -5643,13 +5643,13 @@ Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) { } // Handle blocks rewriting. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) { - ValueDecl *VD = DRE->getDecl(); + ValueDecl *VD = DRE->getDecl(); if (VD->hasAttr<BlocksAttr>()) return RewriteBlockDeclRefExpr(DRE); if (HasLocalVariableExternalStorage(VD)) return RewriteLocalVariableExternalStorage(DRE); } - + if (CallExpr *CE = dyn_cast<CallExpr>(S)) { if (CE->getCallee()->getType()->isBlockPointerType()) { Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee()); @@ -5812,7 +5812,7 @@ void RewriteModernObjC::HandleDeclInMainFile(Decl *D) { case Decl::CXXRecord: case Decl::Record: { RecordDecl *RD = cast<RecordDecl>(D); - if (RD->isCompleteDefinition()) + if (RD->isCompleteDefinition()) RewriteRecordBody(RD); break; } @@ -5825,7 +5825,7 @@ void RewriteModernObjC::HandleDeclInMainFile(Decl *D) { /// Write_ProtocolExprReferencedMetadata - This routine writer out the /// protocol reference symbols in the for of: /// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA. -static void Write_ProtocolExprReferencedMetadata(ASTContext *Context, +static void Write_ProtocolExprReferencedMetadata(ASTContext *Context, ObjCProtocolDecl *PDecl, std::string &Result) { // Also output .objc_protorefs$B section and its meta-data. @@ -5861,10 +5861,10 @@ void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) { } InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false); - + if (ClassImplementation.size() || CategoryImplementation.size()) RewriteImplementations(); - + for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) { ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i]; // Write struct declaration for the class matching its ivar declarations. @@ -5873,7 +5873,7 @@ void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) { // private ivars. RewriteInterfaceDecl(CDecl); } - + // Get the buffer corresponding to MainFileID. If we haven't changed it, then // we are done. if (const RewriteBuffer *RewriteBuf = @@ -5903,7 +5903,7 @@ void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) { void RewriteModernObjC::Initialize(ASTContext &context) { InitializeCommon(context); - + Preamble += "#ifndef __OBJC2__\n"; Preamble += "#define __OBJC2__\n"; Preamble += "#endif\n"; @@ -5919,7 +5919,7 @@ void RewriteModernObjC::Initialize(ASTContext &context) { Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) "; Preamble += ": object(o), superClass(s) {} "; Preamble += "\n};\n"; - + if (LangOpts.MicrosoftExt) { // Define all sections using syntax that makes sense. // These are currently generated. @@ -5933,13 +5933,13 @@ void RewriteModernObjC::Initialize(ASTContext &context) { Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n"; Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n"; Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n"; - + // These need be generated for performance. Currently they are not, // using API calls instead. Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n"; Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n"; Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n"; - + } Preamble += "#ifndef _REWRITER_typedef_Protocol\n"; Preamble += "typedef struct objc_object Protocol;\n"; @@ -5948,10 +5948,10 @@ void RewriteModernObjC::Initialize(ASTContext &context) { if (LangOpts.MicrosoftExt) { Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n"; Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n"; - } + } else Preamble += "#define __OBJC_RW_DLLIMPORT extern\n"; - + Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n"; Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n"; Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n"; @@ -6041,7 +6041,7 @@ void RewriteModernObjC::Initialize(ASTContext &context) { Preamble += "#define __block\n"; Preamble += "#define __weak\n"; } - + // Declarations required for modern objective-c array and dictionary literals. Preamble += "\n#include <stdarg.h>\n"; Preamble += "struct __NSContainer_literal {\n"; @@ -6058,7 +6058,7 @@ void RewriteModernObjC::Initialize(ASTContext &context) { Preamble += "\tdelete[] arr;\n"; Preamble += " }\n"; Preamble += "};\n"; - + // Declaration required for implementation of @autoreleasepool statement. Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n"; Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n"; @@ -6067,7 +6067,7 @@ void RewriteModernObjC::Initialize(ASTContext &context) { Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n"; Preamble += " void * atautoreleasepoolobj;\n"; Preamble += "};\n"; - + // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long // as this avoids warning in any 64bit/32bit compilation model. Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n"; @@ -6195,20 +6195,20 @@ static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Re static bool meta_data_declared = false; if (meta_data_declared) return; - + Result += "\nstruct _prop_t {\n"; Result += "\tconst char *name;\n"; Result += "\tconst char *attributes;\n"; Result += "};\n"; - + Result += "\nstruct _protocol_t;\n"; - + Result += "\nstruct _objc_method {\n"; Result += "\tstruct objc_selector * _cmd;\n"; Result += "\tconst char *method_type;\n"; Result += "\tvoid *_imp;\n"; Result += "};\n"; - + Result += "\nstruct _protocol_t {\n"; Result += "\tvoid * isa; // NULL\n"; Result += "\tconst char *protocol_name;\n"; @@ -6222,7 +6222,7 @@ static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Re Result += "\tconst unsigned int flags; // = 0\n"; Result += "\tconst char ** extendedMethodTypes;\n"; Result += "};\n"; - + Result += "\nstruct _ivar_t {\n"; Result += "\tunsigned long int *offset; // pointer to ivar offset location\n"; Result += "\tconst char *name;\n"; @@ -6230,7 +6230,7 @@ static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Re Result += "\tunsigned int alignment;\n"; Result += "\tunsigned int size;\n"; Result += "};\n"; - + Result += "\nstruct _class_ro_t {\n"; Result += "\tunsigned int flags;\n"; Result += "\tunsigned int instanceStart;\n"; @@ -6246,7 +6246,7 @@ static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Re Result += "\tconst unsigned char *weakIvarLayout;\n"; Result += "\tconst struct _prop_list_t *properties;\n"; Result += "};\n"; - + Result += "\nstruct _class_t {\n"; Result += "\tstruct _class_t *isa;\n"; Result += "\tstruct _class_t *superclass;\n"; @@ -6254,7 +6254,7 @@ static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Re Result += "\tvoid *vtable;\n"; Result += "\tstruct _class_ro_t *ro;\n"; Result += "};\n"; - + Result += "\nstruct _category_t {\n"; Result += "\tconst char *name;\n"; Result += "\tstruct _class_t *cls;\n"; @@ -6263,7 +6263,7 @@ static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Re Result += "\tconst struct _protocol_list_t *protocols;\n"; Result += "\tconst struct _prop_list_t *properties;\n"; Result += "};\n"; - + Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n"; Result += "#pragma warning(disable:4273)\n"; meta_data_declared = true; @@ -6316,12 +6316,12 @@ static void Write_protocol_list_initializer(ASTContext *Context, std::string &Re Result += "\nstatic "; Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size()); Result += " "; Result += VarName; - Result += ProtocolName; + Result += ProtocolName; Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n"; Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n"; for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) { ObjCProtocolDecl *SuperPD = SuperProtocols[i]; - Result += "\t&"; Result += "_OBJC_PROTOCOL_"; + Result += "\t&"; Result += "_OBJC_PROTOCOL_"; Result += SuperPD->getNameAsString(); if (i == e-1) Result += "\n};\n"; @@ -6341,7 +6341,7 @@ static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj, Result += "\nstatic "; Write_method_list_t_TypeDecl(Result, Methods.size()); Result += " "; Result += VarName; - Result += TopLevelDeclName; + Result += TopLevelDeclName; Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n"; Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n"; Result += "\t"; Result += utostr(Methods.size()); Result += ",\n"; @@ -6381,7 +6381,7 @@ static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj, Result += "\nstatic "; Write__prop_list_t_TypeDecl(Result, Properties.size()); Result += " "; Result += VarName; - Result += ProtocolName; + Result += ProtocolName; Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n"; Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n"; Result += "\t"; Result += utostr(Properties.size()); Result += ",\n"; @@ -6413,16 +6413,16 @@ enum MetaDataDlags { CLS_ROOT = 0x2, OBJC2_CLS_HIDDEN = 0x10, CLS_EXCEPTION = 0x20, - + /// (Obsolete) ARC-specific: this class has a .release_ivars method CLS_HAS_IVAR_RELEASER = 0x40, /// class was compiled with -fobjc-arr CLS_COMPILED_BY_ARC = 0x80 // (1<<7) }; -static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result, - unsigned int flags, - const std::string &InstanceStart, +static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result, + unsigned int flags, + const std::string &InstanceStart, const std::string &InstanceSize, ArrayRef<ObjCMethodDecl *>baseMethods, ArrayRef<ObjCProtocolDecl *>baseProtocols, @@ -6433,8 +6433,8 @@ static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Resu Result += "\nstatic struct _class_ro_t "; Result += VarName; Result += ClassName; Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n"; - Result += "\t"; - Result += llvm::utostr(flags); Result += ", "; + Result += "\t"; + Result += llvm::utostr(flags); Result += ", "; Result += InstanceStart; Result += ", "; Result += InstanceSize; Result += ", \n"; Result += "\t"; @@ -6492,7 +6492,7 @@ static void Write_class_t(ASTContext *Context, std::string &Result, const ObjCInterfaceDecl *CDecl, bool metaclass) { bool rootClass = (!CDecl->getSuperClass()); const ObjCInterfaceDecl *RootClass = CDecl; - + if (!rootClass) { // Find the Root class RootClass = CDecl->getSuperClass(); @@ -6509,7 +6509,7 @@ static void Write_class_t(ASTContext *Context, std::string &Result, Result += "__declspec(dllexport) "; else Result += "__declspec(dllimport) "; - + Result += "struct _class_t OBJC_CLASS_$_"; Result += CDecl->getNameAsString(); Result += ";\n"; @@ -6524,11 +6524,11 @@ static void Write_class_t(ASTContext *Context, std::string &Result, else Result += "__declspec(dllimport) "; - Result += "struct _class_t "; + Result += "struct _class_t "; Result += VarName; Result += SuperClass->getNameAsString(); Result += ";\n"; - + if (metaclass && RootClass != SuperClass) { Result += "extern \"C\" "; if (RootClass->getImplementation()) @@ -6536,14 +6536,14 @@ static void Write_class_t(ASTContext *Context, std::string &Result, else Result += "__declspec(dllimport) "; - Result += "struct _class_t "; + Result += "struct _class_t "; Result += VarName; Result += RootClass->getNameAsString(); Result += ";\n"; } } - - Result += "\nextern \"C\" __declspec(dllexport) struct _class_t "; + + Result += "\nextern \"C\" __declspec(dllexport) struct _class_t "; Result += VarName; Result += CDecl->getNameAsString(); Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n"; Result += "\t"; @@ -6557,7 +6557,7 @@ static void Write_class_t(ASTContext *Context, std::string &Result, Result += ",\n\t"; } else { - Result += "0, // &"; Result += VarName; + Result += "0, // &"; Result += VarName; Result += CDecl->getNameAsString(); Result += ",\n\t"; Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString(); @@ -6565,7 +6565,7 @@ static void Write_class_t(ASTContext *Context, std::string &Result, } } else { - Result += "0, // &OBJC_METACLASS_$_"; + Result += "0, // &OBJC_METACLASS_$_"; Result += CDecl->getNameAsString(); Result += ",\n\t"; if (!rootClass) { @@ -6573,7 +6573,7 @@ static void Write_class_t(ASTContext *Context, std::string &Result, Result += CDecl->getSuperClass()->getNameAsString(); Result += ",\n\t"; } - else + else Result += "0,\n\t"; } Result += "0, // (void *)&_objc_empty_cache,\n\t"; @@ -6584,22 +6584,22 @@ static void Write_class_t(ASTContext *Context, std::string &Result, Result += "&_OBJC_CLASS_RO_$_"; Result += CDecl->getNameAsString(); Result += ",\n};\n"; - + // Add static function to initialize some of the meta-data fields. // avoid doing it twice. if (metaclass) return; - - const ObjCInterfaceDecl *SuperClass = + + const ObjCInterfaceDecl *SuperClass = rootClass ? CDecl : CDecl->getSuperClass(); - + Result += "static void OBJC_CLASS_SETUP_$_"; Result += CDecl->getNameAsString(); Result += "(void ) {\n"; Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString(); Result += ".isa = "; Result += "&OBJC_METACLASS_$_"; Result += RootClass->getNameAsString(); Result += ";\n"; - + Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString(); Result += ".superclass = "; if (rootClass) @@ -6608,26 +6608,26 @@ static void Write_class_t(ASTContext *Context, std::string &Result, Result += "&OBJC_METACLASS_$_"; Result += SuperClass->getNameAsString(); Result += ";\n"; - + Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString(); Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n"; - + Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString(); Result += ".isa = "; Result += "&OBJC_METACLASS_$_"; Result += CDecl->getNameAsString(); Result += ";\n"; - + if (!rootClass) { Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString(); Result += ".superclass = "; Result += "&OBJC_CLASS_$_"; Result += SuperClass->getNameAsString(); Result += ";\n"; } - + Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString(); Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n"; Result += "}\n"; } -static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context, +static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context, std::string &Result, ObjCCategoryDecl *CatDecl, ObjCInterfaceDecl *ClassDecl, @@ -6637,7 +6637,7 @@ static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context, ArrayRef<ObjCPropertyDecl *> ClassProperties) { StringRef CatName = CatDecl->getName(); StringRef ClassName = ClassDecl->getName(); - // must declare an extern class object in case this class is not implemented + // must declare an extern class object in case this class is not implemented // in this TU. Result += "\n"; Result += "extern \"C\" "; @@ -6645,11 +6645,11 @@ static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context, Result += "__declspec(dllexport) "; else Result += "__declspec(dllimport) "; - + Result += "struct _class_t "; Result += "OBJC_CLASS_$_"; Result += ClassName; Result += ";\n"; - + Result += "\nstatic struct _category_t "; Result += "_OBJC_$_CATEGORY_"; Result += ClassName; Result += "_$_"; Result += CatName; @@ -6659,32 +6659,32 @@ static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context, Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName; Result += ",\n"; if (InstanceMethods.size() > 0) { - Result += "\t(const struct _method_list_t *)&"; + Result += "\t(const struct _method_list_t *)&"; Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_"; Result += ClassName; Result += "_$_"; Result += CatName; Result += ",\n"; } else Result += "\t0,\n"; - + if (ClassMethods.size() > 0) { - Result += "\t(const struct _method_list_t *)&"; + Result += "\t(const struct _method_list_t *)&"; Result += "_OBJC_$_CATEGORY_CLASS_METHODS_"; Result += ClassName; Result += "_$_"; Result += CatName; Result += ",\n"; } else Result += "\t0,\n"; - + if (RefedProtocols.size() > 0) { - Result += "\t(const struct _protocol_list_t *)&"; + Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_CATEGORY_PROTOCOLS_$_"; Result += ClassName; Result += "_$_"; Result += CatName; Result += ",\n"; } else Result += "\t0,\n"; - + if (ClassProperties.size() > 0) { Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_"; Result += ClassName; Result += "_$_"; Result += CatName; @@ -6692,16 +6692,16 @@ static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context, } else Result += "\t0,\n"; - + Result += "};\n"; - + // Add static function to initialize the class pointer in the category structure. Result += "static void OBJC_CATEGORY_SETUP_$_"; Result += ClassDecl->getNameAsString(); Result += "_$_"; Result += CatName; Result += "(void ) {\n"; - Result += "\t_OBJC_$_CATEGORY_"; + Result += "\t_OBJC_$_CATEGORY_"; Result += ClassDecl->getNameAsString(); Result += "_$_"; Result += CatName; @@ -6716,7 +6716,7 @@ static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj StringRef ProtocolName) { if (Methods.size() == 0) return; - + Result += "\nstatic const char *"; Result += VarName; Result += ProtocolName; Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n"; @@ -6738,8 +6738,8 @@ static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj, ASTContext *Context, - std::string &Result, - ArrayRef<ObjCIvarDecl *> Ivars, + std::string &Result, + ArrayRef<ObjCIvarDecl *> Ivars, ObjCInterfaceDecl *CDecl) { // FIXME. visibilty of offset symbols may have to be set; for Darwin // this is what happens: @@ -6751,17 +6751,17 @@ static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj, else Visibility should be: DefaultVisibility; */ - + Result += "\n"; for (unsigned i =0, e = Ivars.size(); i < e; i++) { ObjCIvarDecl *IvarDecl = Ivars[i]; if (Context->getLangOpts().MicrosoftExt) Result += "__declspec(allocate(\".objc_ivar$B\")) "; - + if (!Context->getLangOpts().MicrosoftExt || IvarDecl->getAccessControl() == ObjCIvarDecl::Private || IvarDecl->getAccessControl() == ObjCIvarDecl::Package) - Result += "extern \"C\" unsigned long int "; + Result += "extern \"C\" unsigned long int "; else Result += "extern \"C\" __declspec(dllexport) unsigned long int "; if (Ivars[i]->isBitField()) @@ -6799,7 +6799,7 @@ static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj, else Ivars.push_back(OriginalIvars[i]); } - + Result += "\nstatic "; Write__ivar_list_t_TypeDecl(Result, Ivars.size()); Result += " "; Result += VarName; @@ -6819,24 +6819,24 @@ static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj, else WriteInternalIvarName(CDecl, IvarDecl, Result); Result += ", "; - + Result += "\""; if (Ivars[i]->isBitField()) RewriteObj.ObjCIvarBitfieldGroupDecl(Ivars[i], Result); else Result += IvarDecl->getName(); Result += "\", "; - + QualType IVQT = IvarDecl->getType(); if (IvarDecl->isBitField()) IVQT = RewriteObj.GetGroupRecordTypeForObjCIvarBitfield(IvarDecl); - + std::string IvarTypeString, QuoteIvarTypeString; Context->getObjCEncodingForType(IVQT, IvarTypeString, IvarDecl); RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString); Result += "\""; Result += QuoteIvarTypeString; Result += "\", "; - + // FIXME. this alignment represents the host alignment and need be changed to // represent the target alignment. unsigned Align = Context->getTypeAlign(IVQT)/8; @@ -6854,21 +6854,21 @@ static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj, } /// RewriteObjCProtocolMetaData - Rewrite protocols meta-data. -void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, +void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, std::string &Result) { - + // Do not synthesize the protocol more than once. if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl())) return; WriteModernMetadataDeclarations(Context, Result); - + if (ObjCProtocolDecl *Def = PDecl->getDefinition()) PDecl = Def; // Must write out all protocol definitions in current qualifier list, // and in their nested qualifiers before writing out current definition. for (auto *I : PDecl->protocols()) RewriteObjCProtocolMetaData(I, Result); - + // Construct method lists. std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods; std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods; @@ -6879,7 +6879,7 @@ void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, InstanceMethods.push_back(MD); } } - + for (auto *MD : PDecl->class_methods()) { if (MD->getImplementationControl() == ObjCMethodDecl::Optional) { OptClassMethods.push_back(MD); @@ -6902,27 +6902,27 @@ void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, "_OBJC_PROTOCOL_METHOD_TYPES_", PDecl->getNameAsString()); // Protocol's super protocol list - SmallVector<ObjCProtocolDecl *, 8> SuperProtocols(PDecl->protocols()); + SmallVector<ObjCProtocolDecl *, 8> SuperProtocols(PDecl->protocols()); Write_protocol_list_initializer(Context, Result, SuperProtocols, "_OBJC_PROTOCOL_REFS_", PDecl->getNameAsString()); - - Write_method_list_t_initializer(*this, Context, Result, InstanceMethods, + + Write_method_list_t_initializer(*this, Context, Result, InstanceMethods, "_OBJC_PROTOCOL_INSTANCE_METHODS_", PDecl->getNameAsString(), false); - - Write_method_list_t_initializer(*this, Context, Result, ClassMethods, + + Write_method_list_t_initializer(*this, Context, Result, ClassMethods, "_OBJC_PROTOCOL_CLASS_METHODS_", PDecl->getNameAsString(), false); - Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods, + Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods, "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_", PDecl->getNameAsString(), false); - - Write_method_list_t_initializer(*this, Context, Result, OptClassMethods, + + Write_method_list_t_initializer(*this, Context, Result, OptClassMethods, "_OBJC_PROTOCOL_OPT_CLASS_METHODS_", PDecl->getNameAsString(), false); - + // Protocol's property metadata. SmallVector<ObjCPropertyDecl *, 8> ProtocolProperties( PDecl->instance_properties()); @@ -6947,43 +6947,43 @@ void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, else Result += "\t0,\n"; if (InstanceMethods.size() > 0) { - Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_"; + Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_"; Result += PDecl->getNameAsString(); Result += ",\n"; } else Result += "\t0,\n"; if (ClassMethods.size() > 0) { - Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_"; + Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_"; Result += PDecl->getNameAsString(); Result += ",\n"; } else Result += "\t0,\n"; - + if (OptInstanceMethods.size() > 0) { - Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_"; + Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_"; Result += PDecl->getNameAsString(); Result += ",\n"; } else Result += "\t0,\n"; - + if (OptClassMethods.size() > 0) { - Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_"; + Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_"; Result += PDecl->getNameAsString(); Result += ",\n"; } else Result += "\t0,\n"; - + if (ProtocolProperties.size() > 0) { - Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_"; + Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_"; Result += PDecl->getNameAsString(); Result += ",\n"; } else Result += "\t0,\n"; - + Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n"; Result += "\t0,\n"; - + if (AllMethods.size() > 0) { Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_"; Result += PDecl->getNameAsString(); @@ -6991,14 +6991,14 @@ void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, } else Result += "\t0\n};\n"; - + if (LangOpts.MicrosoftExt) Result += "static "; Result += "struct _protocol_t *"; Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString(); Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString(); Result += ";\n"; - + // Mark this protocol as having been generated. if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()).second) llvm_unreachable("protocol already synthesized"); @@ -7019,15 +7019,15 @@ static bool hasObjCExceptionAttribute(ASTContext &Context, void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl, std::string &Result) { ObjCInterfaceDecl *CDecl = IDecl->getClassInterface(); - + // Explicitly declared @interface's are already synthesized. if (CDecl->isImplicitInterfaceDecl()) - assert(false && + assert(false && "Legacy implicit interface rewriting not supported in moder abi"); - + WriteModernMetadataDeclarations(Context, Result); SmallVector<ObjCIvarDecl *, 8> IVars; - + for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin(); IVD; IVD = IVD->getNextIvar()) { // Ignore unnamed bit-fields. @@ -7035,14 +7035,14 @@ void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl, continue; IVars.push_back(IVD); } - - Write__ivar_list_t_initializer(*this, Context, Result, IVars, + + Write__ivar_list_t_initializer(*this, Context, Result, IVars, "_OBJC_$_INSTANCE_VARIABLES_", CDecl); - + // Build _objc_method_list for class's instance methods if needed SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods()); - + // If any of our property implementations have associated getters or // setters, produce metadata for them as well. for (const auto *Prop : IDecl->property_impls()) { @@ -7062,17 +7062,17 @@ void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl, if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/)) InstanceMethods.push_back(Setter); } - + Write_method_list_t_initializer(*this, Context, Result, InstanceMethods, "_OBJC_$_INSTANCE_METHODS_", IDecl->getNameAsString(), true); - + SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods()); - + Write_method_list_t_initializer(*this, Context, Result, ClassMethods, "_OBJC_$_CLASS_METHODS_", IDecl->getNameAsString(), true); - + // Protocols referenced in class declaration? // Protocol's super protocol list std::vector<ObjCProtocolDecl *> RefedProtocols; @@ -7085,12 +7085,12 @@ void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl, // and in their nested qualifiers before writing out current definition. RewriteObjCProtocolMetaData(*I, Result); } - - Write_protocol_list_initializer(Context, Result, + + Write_protocol_list_initializer(Context, Result, RefedProtocols, "_OBJC_CLASS_PROTOCOLS_$_", IDecl->getNameAsString()); - + // Protocol's property metadata. SmallVector<ObjCPropertyDecl *, 8> ClassProperties( CDecl->instance_properties()); @@ -7098,22 +7098,22 @@ void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl, /* Container */IDecl, "_OBJC_$_PROP_LIST_", CDecl->getNameAsString()); - + // Data for initializing _class_ro_t metaclass meta-data uint32_t flags = CLS_META; std::string InstanceSize; std::string InstanceStart; - + bool classIsHidden = CDecl->getVisibility() == HiddenVisibility; if (classIsHidden) flags |= OBJC2_CLS_HIDDEN; - + if (!CDecl->getSuperClass()) // class is root flags |= CLS_ROOT; InstanceSize = "sizeof(struct _class_t)"; InstanceStart = InstanceSize; - Write__class_ro_t_initializer(Context, Result, flags, + Write__class_ro_t_initializer(Context, Result, flags, InstanceStart, InstanceSize, ClassMethods, nullptr, @@ -7126,14 +7126,14 @@ void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl, flags = CLS; if (classIsHidden) flags |= OBJC2_CLS_HIDDEN; - + if (hasObjCExceptionAttribute(*Context, CDecl)) flags |= CLS_EXCEPTION; if (!CDecl->getSuperClass()) // class is root flags |= CLS_ROOT; - + InstanceSize.clear(); InstanceStart.clear(); if (!ObjCSynthesizedStructs.count(CDecl)) { @@ -7144,15 +7144,15 @@ void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl, InstanceSize = "sizeof(struct "; InstanceSize += CDecl->getNameAsString(); InstanceSize += "_IMPL)"; - + ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin(); if (IVD) { RewriteIvarOffsetComputation(IVD, InstanceStart); } - else + else InstanceStart = InstanceSize; } - Write__class_ro_t_initializer(Context, Result, flags, + Write__class_ro_t_initializer(Context, Result, flags, InstanceStart, InstanceSize, InstanceMethods, RefedProtocols, @@ -7160,15 +7160,15 @@ void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl, ClassProperties, "_OBJC_CLASS_RO_$_", CDecl->getNameAsString()); - + Write_class_t(Context, Result, "OBJC_METACLASS_$_", CDecl, /*metaclass*/true); - + Write_class_t(Context, Result, "OBJC_CLASS_$_", CDecl, /*metaclass*/false); - + if (ImplementationIsNonLazy(IDecl)) DefinedNonLazyClasses.push_back(CDecl); } @@ -7192,25 +7192,25 @@ void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) { void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) { int ClsDefCount = ClassImplementation.size(); int CatDefCount = CategoryImplementation.size(); - + // For each implemented class, write out all its meta data. for (int i = 0; i < ClsDefCount; i++) RewriteObjCClassMetaData(ClassImplementation[i], Result); - + RewriteClassSetupInitHook(Result); - + // For each implemented category, write out all its meta data. for (int i = 0; i < CatDefCount; i++) RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result); - + RewriteCategorySetupInitHook(Result); - + if (ClsDefCount > 0) { if (LangOpts.MicrosoftExt) Result += "__declspec(allocate(\".objc_classlist$B\")) "; Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ ["; Result += llvm::utostr(ClsDefCount); Result += "]"; - Result += + Result += " __attribute__((used, section (\"__DATA, __objc_classlist," "regular,no_dead_strip\")))= {\n"; for (int i = 0; i < ClsDefCount; i++) { @@ -7219,7 +7219,7 @@ void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) { Result += ",\n"; } Result += "};\n"; - + if (!DefinedNonLazyClasses.empty()) { if (LangOpts.MicrosoftExt) Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n"; @@ -7231,34 +7231,34 @@ void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) { Result += "};\n"; } } - + if (CatDefCount > 0) { if (LangOpts.MicrosoftExt) Result += "__declspec(allocate(\".objc_catlist$B\")) "; Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ ["; Result += llvm::utostr(CatDefCount); Result += "]"; - Result += + Result += " __attribute__((used, section (\"__DATA, __objc_catlist," "regular,no_dead_strip\")))= {\n"; for (int i = 0; i < CatDefCount; i++) { Result += "\t&_OBJC_$_CATEGORY_"; - Result += - CategoryImplementation[i]->getClassInterface()->getNameAsString(); + Result += + CategoryImplementation[i]->getClassInterface()->getNameAsString(); Result += "_$_"; Result += CategoryImplementation[i]->getNameAsString(); Result += ",\n"; } Result += "};\n"; } - + if (!DefinedNonLazyCategories.empty()) { if (LangOpts.MicrosoftExt) Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n"; Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t"; for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) { Result += "\t&_OBJC_$_CATEGORY_"; - Result += - DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString(); + Result += + DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString(); Result += "_$_"; Result += DefinedNonLazyCategories[i]->getNameAsString(); Result += ",\n"; @@ -7270,7 +7270,7 @@ void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) { void RewriteModernObjC::WriteImageInfo(std::string &Result) { if (LangOpts.MicrosoftExt) Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n"; - + Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } "; // version 0, ObjCABI is 2 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n"; @@ -7285,14 +7285,14 @@ void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl, // Find category declaration for this implementation. ObjCCategoryDecl *CDecl = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier()); - + std::string FullCategoryName = ClassDecl->getNameAsString(); FullCategoryName += "_$_"; FullCategoryName += CDecl->getNameAsString(); - + // Build _objc_method_list for class's instance methods if needed SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods()); - + // If any of our property implementations have associated getters or // setters, produce metadata for them as well. for (const auto *Prop : IDecl->property_impls()) { @@ -7310,17 +7310,17 @@ void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl, if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl()) InstanceMethods.push_back(Setter); } - + Write_method_list_t_initializer(*this, Context, Result, InstanceMethods, "_OBJC_$_CATEGORY_INSTANCE_METHODS_", FullCategoryName, true); - + SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods()); - + Write_method_list_t_initializer(*this, Context, Result, ClassMethods, "_OBJC_$_CATEGORY_CLASS_METHODS_", FullCategoryName, true); - + // Protocols referenced in class declaration? // Protocol's super protocol list SmallVector<ObjCProtocolDecl *, 8> RefedProtocols(CDecl->protocols()); @@ -7328,12 +7328,12 @@ void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl, // Must write out all protocol definitions in current qualifier list, // and in their nested qualifiers before writing out current definition. RewriteObjCProtocolMetaData(I, Result); - - Write_protocol_list_initializer(Context, Result, + + Write_protocol_list_initializer(Context, Result, RefedProtocols, "_OBJC_CATEGORY_PROTOCOLS_$_", FullCategoryName); - + // Protocol's property metadata. SmallVector<ObjCPropertyDecl *, 8> ClassProperties( CDecl->instance_properties()); @@ -7341,7 +7341,7 @@ void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl, /* Container */IDecl, "_OBJC_$_PROP_LIST_", FullCategoryName); - + Write_category_t(*this, Context, Result, CDecl, ClassDecl, @@ -7349,7 +7349,7 @@ void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl, ClassMethods, RefedProtocols, ClassProperties); - + // Determine if this category is also "non-lazy". if (ImplementationIsNonLazy(IDecl)) DefinedNonLazyCategories.push_back(CDecl); @@ -7385,7 +7385,7 @@ void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin, StringRef ClassName, std::string &Result) { if (MethodBegin == MethodEnd) return; - + if (!objc_impl_method) { /* struct _objc_method { SEL _cmd; @@ -7398,12 +7398,12 @@ void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin, Result += "\tchar *method_types;\n"; Result += "\tvoid *_imp;\n"; Result += "};\n"; - + objc_impl_method = true; } - + // Build _objc_method_list for class's methods if needed - + /* struct { struct _objc_method_list *next_method; int method_count; @@ -7432,7 +7432,7 @@ void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin, Result += IsInstanceMethod ? "inst" : "cls"; Result += "_meth\")))= "; Result += "{\n\t0, " + utostr(NumMethods) + "\n"; - + Result += "\t,{{(SEL)\""; Result += (*MethodBegin)->getSelector().getAsString().c_str(); std::string MethodTypeString; @@ -7459,18 +7459,18 @@ void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin, Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) { SourceRange OldRange = IV->getSourceRange(); Expr *BaseExpr = IV->getBase(); - + // Rewrite the base, but without actually doing replaces. { DisableReplaceStmtScope S(*this); BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr)); IV->setBase(BaseExpr); } - + ObjCIvarDecl *D = IV->getDecl(); - + Expr *Replacement = IV; - + if (BaseExpr->getType()->isObjCObjectPointerType()) { const ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType()); @@ -7480,18 +7480,18 @@ Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) { iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared); assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class"); - + // Build name of symbol holding ivar offset. std::string IvarOffsetName; if (D->isBitField()) ObjCIvarBitfieldGroupOffset(D, IvarOffsetName); else WriteInternalIvarName(clsDeclared, D, IvarOffsetName); - + ReferencedIvars[clsDeclared].insert(D); - + // cast offset to "char *". - CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, + CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->getPointerType(Context->CharTy), CK_BitCast, BaseExpr); @@ -7502,8 +7502,8 @@ Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) { DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, Context->UnsignedLongTy, VK_LValue, SourceLocation()); - BinaryOperator *addExpr = - new (Context) BinaryOperator(castExpr, DRE, BO_Add, + BinaryOperator *addExpr = + new (Context) BinaryOperator(castExpr, DRE, BO_Add, Context->getPointerType(Context->CharTy), VK_RValue, OK_Ordinary, SourceLocation(), FPOptions()); // Don't forget the parens to enforce the proper binding. @@ -7519,7 +7519,7 @@ Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) { RD = RD->getDefinition(); if (RD && !RD->getDeclName().getAsIdentifierInfo()) { // decltype(((Foo_IMPL*)0)->bar) * - ObjCContainerDecl *CDecl = + ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(D->getDeclContext()); // ivar in class extensions requires special treatment. if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl)) @@ -7530,7 +7530,7 @@ Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) { *Context, TTK_Struct, TUDecl, SourceLocation(), SourceLocation(), &Context->Idents.get(RecName)); QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD)); - unsigned UnsignedIntSize = + unsigned UnsignedIntSize = static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy)); Expr *Zero = IntegerLiteral::Create(*Context, llvm::APInt(UnsignedIntSize, 0), @@ -7552,20 +7552,20 @@ Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) { } convertObjCTypeToCStyleType(IvarT); QualType castT = Context->getPointerType(IvarT); - - castExpr = NoTypeInfoCStyleCastExpr(Context, + + castExpr = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, PE); - - + + Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT, VK_LValue, OK_Ordinary, SourceLocation(), false); PE = new (Context) ParenExpr(OldRange.getBegin(), OldRange.getEnd(), Exp); - + if (D->isBitField()) { FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(), @@ -7582,9 +7582,9 @@ Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) { else Replacement = PE; } - + ReplaceStmtWithRange(IV, Replacement, OldRange); - return Replacement; + return Replacement; } #endif // CLANG_ENABLE_OBJC_REWRITER diff --git a/lib/Frontend/Rewrite/RewriteObjC.cpp b/lib/Frontend/Rewrite/RewriteObjC.cpp index 9938f89eb869..6229351e8f54 100644 --- a/lib/Frontend/Rewrite/RewriteObjC.cpp +++ b/lib/Frontend/Rewrite/RewriteObjC.cpp @@ -42,7 +42,7 @@ namespace { BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)), block, ... */ BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */ - BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the + BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the __block variable */ BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy helpers */ @@ -50,7 +50,7 @@ namespace { support routines */ BLOCK_BYREF_CURRENT_MAX = 256 }; - + enum { BLOCK_NEEDS_FREE = (1 << 24), BLOCK_HAS_COPY_DISPOSE = (1 << 25), @@ -60,7 +60,7 @@ namespace { BLOCK_HAS_DESCRIPTOR = (1 << 29) }; static const int OBJC_ABI_VERSION = 7; - + Rewriter Rewrite; DiagnosticsEngine &Diags; const LangOptions &LangOpts; @@ -74,7 +74,7 @@ namespace { std::string InFileName; std::unique_ptr<raw_ostream> OutFile; std::string Preamble; - + TypeDecl *ProtocolTypeDecl; VarDecl *GlobalVarDecl; unsigned RewriteFailedDiag; @@ -85,13 +85,13 @@ namespace { // ObjC foreach break/continue generation support. int BcLabelCount; - + unsigned TryFinallyContainsReturnDiag; // Needed for super. ObjCMethodDecl *CurMethodDef; RecordDecl *SuperStructDecl; RecordDecl *ConstantStringDecl; - + FunctionDecl *MsgSendFunctionDecl; FunctionDecl *MsgSendSuperFunctionDecl; FunctionDecl *MsgSendStretFunctionDecl; @@ -117,14 +117,14 @@ namespace { SmallVector<int, 8> ObjCBcLabelNo; // Remember all the @protocol(<expr>) expressions. llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls; - + llvm::DenseSet<uint64_t> CopyDestroyCache; // Block expressions. SmallVector<BlockExpr *, 32> Blocks; SmallVector<int, 32> InnerDeclRefsCount; SmallVector<DeclRefExpr *, 32> InnerDeclRefs; - + SmallVector<DeclRefExpr *, 32> BlockDeclRefs; // Block related declarations. @@ -135,7 +135,7 @@ namespace { llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo; llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls; llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls; - + llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs; // This maps an original source AST to it's rewritten form. This allows @@ -147,12 +147,12 @@ namespace { bool IsHeader; bool SilenceRewriteMacroWarning; bool objc_impl_method; - + bool DisableReplaceStmt; class DisableReplaceStmtScope { RewriteObjC &R; bool SavedValue; - + public: DisableReplaceStmtScope(RewriteObjC &R) : R(R), SavedValue(R.DisableReplaceStmt) { @@ -262,7 +262,7 @@ namespace { void RewriteInclude(); void RewriteForwardClassDecl(DeclGroupRef D); void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG); - void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl, + void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl, const std::string &typedefString); void RewriteImplementations(); void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, @@ -289,7 +289,7 @@ namespace { void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl); void RewriteTypeOfDecl(VarDecl *VD); void RewriteObjCQualifiedInterfaceTypes(Expr *E); - + // Expression Rewriting. Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S); Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp); @@ -309,17 +309,17 @@ namespace { Stmt *RewriteBreakStmt(BreakStmt *S); Stmt *RewriteContinueStmt(ContinueStmt *S); void RewriteCastExpr(CStyleCastExpr *CE); - + // Block rewriting. void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D); - + // Block specific rewrite rules. void RewriteBlockPointerDecl(NamedDecl *VD); void RewriteByRefVar(VarDecl *VD); Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD); Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE); void RewriteBlockPointerFunctionArgs(FunctionDecl *FD); - + void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl, std::string &Result); @@ -339,12 +339,12 @@ namespace { std::string &Result) = 0; virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl, std::string &Result) = 0; - + // Rewriting ivar access virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) = 0; virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar, std::string &Result) = 0; - + // Misc. AST transformation routines. Sometimes they end up calling // rewriting routines on the new ASTs. CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD, @@ -352,15 +352,15 @@ namespace { SourceLocation StartLoc=SourceLocation(), SourceLocation EndLoc=SourceLocation()); CallExpr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor, - QualType msgSendType, - QualType returnType, + QualType msgSendType, + QualType returnType, SmallVectorImpl<QualType> &ArgTypes, SmallVectorImpl<Expr*> &MsgExprs, ObjCMethodDecl *Method); Stmt *SynthMessageExpr(ObjCMessageExpr *Exp, SourceLocation StartLoc=SourceLocation(), SourceLocation EndLoc=SourceLocation()); - + void SynthCountByEnumWithState(std::string &buf); void SynthMsgSendFunctionDecl(); void SynthMsgSendSuperFunctionDecl(); @@ -372,15 +372,15 @@ namespace { void SynthGetSuperClassFunctionDecl(); void SynthSelGetUidFunctionDecl(); void SynthSuperConstructorFunctionDecl(); - + std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag); std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i, StringRef funcName, std::string Tag); std::string SynthesizeBlockFunc(BlockExpr *CE, int i, StringRef funcName, std::string Tag); - std::string SynthesizeBlockImpl(BlockExpr *CE, + std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag, std::string Desc); - std::string SynthesizeBlockDescriptor(std::string DescTag, + std::string SynthesizeBlockDescriptor(std::string DescTag, std::string ImplTag, int i, StringRef funcName, unsigned hasCopy); @@ -423,13 +423,13 @@ namespace { } return false; } - + bool needToScanForQualifiers(QualType T); QualType getSuperStructType(); QualType getConstantStringStructType(); QualType convertFunctionTypeOfBlocks(const FunctionType *FT); bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf); - + void convertToUnqualifiedObjCType(QualType &T) { if (T->isObjCQualifiedIdType()) T = Context->getObjCIdType(); @@ -445,7 +445,7 @@ namespace { } } } - + // FIXME: This predicate seems like it would be useful to add to ASTContext. bool isObjCType(QualType T) { if (!LangOpts.ObjC1 && !LangOpts.ObjC2) @@ -468,7 +468,7 @@ namespace { bool PointerTypeTakesAnyObjCQualifiedType(QualType QT); void GetExtentOfArgList(const char *Name, const char *&LParen, const char *&RParen); - + void QuoteDoublequotes(std::string &From, std::string &To) { for (unsigned i = 0; i < From.length(); i++) { if (From[i] == '"') @@ -504,7 +504,7 @@ namespace { /*Pascal=*/false, StrType, SourceLocation()); } }; - + class RewriteObjCFragileABI : public RewriteObjC { public: RewriteObjCFragileABI(std::string inFile, std::unique_ptr<raw_ostream> OS, @@ -688,7 +688,7 @@ void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) { DG.push_back(*DI); else break; - + ++DI; } while (DI != DIEnd); RewriteForwardClassDecl(DG); @@ -707,14 +707,14 @@ void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) { DG.push_back(*DI); else break; - + ++DI; } while (DI != DIEnd); RewriteForwardProtocolDecl(DG); continue; } } - + HandleTopLevelSingleDecl(*DI); ++DI; } @@ -790,7 +790,7 @@ void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, unsigned Attributes = PD->getPropertyAttributes(); if (!PD->getGetterMethodDecl()->isDefined()) { bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) && - (Attributes & (ObjCPropertyDecl::OBJC_PR_retain | + (Attributes & (ObjCPropertyDecl::OBJC_PR_retain | ObjCPropertyDecl::OBJC_PR_copy)); std::string Getr; if (GenGetProperty && !objcGetPropertyDefined) { @@ -799,7 +799,7 @@ void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, Getr = "\nextern \"C\" __declspec(dllimport) " "id objc_getProperty(id, SEL, long, bool);\n"; } - RewriteObjCMethodDecl(OID->getContainingInterface(), + RewriteObjCMethodDecl(OID->getContainingInterface(), PD->getGetterMethodDecl(), Getr); Getr += "{ "; // Synthesize an explicit cast to gain access to the ivar. @@ -813,7 +813,7 @@ void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, Getr += " _TYPE"; if (FPRetType) { Getr += ")"; // close the precedence "scope" for "*". - + // Now, emit the argument types (if any). if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){ Getr += "("; @@ -843,13 +843,13 @@ void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, Getr += "; }"; InsertText(onePastSemiLoc, Getr); } - + if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined()) return; // Generate the 'setter' function. std::string Setr; - bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain | + bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain | ObjCPropertyDecl::OBJC_PR_copy); if (GenSetProperty && !objcSetPropertyDefined) { objcSetPropertyDefined = true; @@ -857,8 +857,8 @@ void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, Setr = "\nextern \"C\" __declspec(dllimport) " "void objc_setProperty (id, SEL, long, id, bool, bool);\n"; } - - RewriteObjCMethodDecl(OID->getContainingInterface(), + + RewriteObjCMethodDecl(OID->getContainingInterface(), PD->getSetterMethodDecl(), Setr); Setr += "{ "; // Synthesize an explicit cast to initialize the ivar. @@ -903,9 +903,9 @@ void RewriteObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl, const std::string &typedefString) { SourceLocation startLoc = ClassDecl->getLocStart(); const char *startBuf = SM->getCharacterData(startLoc); - const char *semiPtr = strchr(startBuf, ';'); + const char *semiPtr = strchr(startBuf, ';'); // Replace the @class with typedefs corresponding to the classes. - ReplaceText(startLoc, semiPtr-startBuf+1, typedefString); + ReplaceText(startLoc, semiPtr-startBuf+1, typedefString); } void RewriteObjC::RewriteForwardClassDecl(DeclGroupRef D) { @@ -971,21 +971,21 @@ void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) { ReplaceText(LocStart, 0, "// "); for (auto *I : CatDecl->instance_properties()) - RewriteProperty(I); + RewriteProperty(I); for (auto *I : CatDecl->instance_methods()) RewriteMethodDeclaration(I); for (auto *I : CatDecl->class_methods()) RewriteMethodDeclaration(I); // Lastly, comment out the @end. - ReplaceText(CatDecl->getAtEndRange().getBegin(), + ReplaceText(CatDecl->getAtEndRange().getBegin(), strlen("@end"), "/* @end */"); } void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) { SourceLocation LocStart = PDecl->getLocStart(); assert(PDecl->isThisDeclarationADefinition()); - + // FIXME: handle protocol headers that are declared across multiple lines. ReplaceText(LocStart, 0, "// "); @@ -995,7 +995,7 @@ void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) { RewriteMethodDeclaration(I); for (auto *I : PDecl->instance_properties()) RewriteProperty(I); - + // Lastly, comment out the @end. SourceLocation LocEnd = PDecl->getAtEndRange().getBegin(); ReplaceText(LocEnd, strlen("@end"), "/* @end */"); @@ -1025,7 +1025,7 @@ void RewriteObjC::RewriteForwardProtocolDecl(DeclGroupRef D) { ReplaceText(LocStart, 0, "// "); } -void +void RewriteObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) { SourceLocation LocStart = DG[0]->getLocStart(); if (LocStart.isInvalid()) @@ -1220,7 +1220,7 @@ void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) { RewriteMethodDeclaration(I); // Lastly, comment out the @end. - ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"), + ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"), "/* @end */"); } @@ -1677,7 +1677,7 @@ Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) { buf += "}\n"; buf += "{ /* implicit finally clause */\n"; buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n"; - + std::string syncBuf; syncBuf += " objc_sync_exit("; @@ -1695,7 +1695,7 @@ Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) { syncExpr->printPretty(syncExprBuf, nullptr, PrintingPolicy(LangOpts)); syncBuf += syncExprBuf.str(); syncBuf += ");"; - + buf += syncBuf; buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n"; buf += "}\n"; @@ -1724,8 +1724,8 @@ void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S) } } -void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns) -{ +void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns) +{ // Perform a bottom up traversal of all children. for (Stmt *SubStmt : S->children()) if (SubStmt) @@ -1750,7 +1750,7 @@ void RewriteObjC::RewriteTryReturnStmts(Stmt *S) { std::string buf; buf = "{ objc_exception_try_exit(&_stack); return"; - + ReplaceText(startLoc, 6, buf); InsertText(onePastSemiLoc, "}"); } @@ -1774,7 +1774,7 @@ void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) { buf = "{ objc_exception_try_exit(&_stack);"; buf += syncExitBuf; buf += " return"; - + ReplaceText(startLoc, 6, buf); InsertText(onePastSemiLoc, "}"); } @@ -1930,7 +1930,7 @@ Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) { buf += " if (_rethrow) objc_exception_throw(_rethrow);\n"; buf += "}"; ReplaceText(lastCurlyLoc, 1, buf); - + // Now check for any return/continue/go statements within the @try. // The implicit finally clause won't called if the @try contains any // jump statements. @@ -2446,7 +2446,7 @@ void RewriteObjC::SynthGetClassFunctionDecl() { // SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls); void RewriteObjC::SynthGetSuperClassFunctionDecl() { - IdentifierInfo *getSuperClassIdent = + IdentifierInfo *getSuperClassIdent = &Context->Idents.get("class_getSuperclass"); SmallVector<QualType, 16> ArgTys; ArgTys.push_back(Context->getObjCClassType()); @@ -2583,8 +2583,8 @@ QualType RewriteObjC::getConstantStringStructType() { } CallExpr *RewriteObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor, - QualType msgSendType, - QualType returnType, + QualType msgSendType, + QualType returnType, SmallVectorImpl<QualType> &ArgTypes, SmallVectorImpl<Expr*> &MsgExprs, ObjCMethodDecl *Method) { @@ -2603,10 +2603,10 @@ CallExpr *RewriteObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavo castType = Context->getPointerType(castType); cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast, cast); - + // Don't forget the parens to enforce the proper binding. ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast); - + const FunctionType *FT = msgSendType->getAs<FunctionType>(); CallExpr *STCE = new (Context) CallExpr( *Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, SourceLocation()); @@ -2764,7 +2764,7 @@ Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp, Context->getObjCIdType(), VK_RValue, SourceLocation())) ); // set the 'receiver'. - + // (id)class_getSuperclass((Class)objc_getClass("CurrentClass")) SmallVector<Expr*, 8> ClsExprs; ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName())); @@ -2778,7 +2778,7 @@ Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp, ClsExprs.push_back(ArgExpr); Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs, StartLoc, EndLoc); - + // (id)class_getSuperclass((Class)objc_getClass("CurrentClass")) // To turn off a warning, type-cast to 'id' InitExprs.push_back( @@ -2863,7 +2863,7 @@ Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp, (void)convertBlockPointerToFunctionPointer(type); const Expr *SubExpr = ICE->IgnoreParenImpCasts(); CastKind CK; - if (SubExpr->getType()->isIntegralType(*Context) && + if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType()) { CK = CK_IntegralToBoolean; } else if (type->isObjCObjectPointerType()) { @@ -2968,9 +2968,9 @@ Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp, // call to objc_msgSend_stret and hang both varieties on a conditional // expression which dictate which one to envoke depending on size of // method's return type. - - CallExpr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor, - msgSendType, returnType, + + CallExpr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor, + msgSendType, returnType, ArgTypes, MsgExprs, Exp->getMethodDecl()); @@ -2990,7 +2990,7 @@ Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp, llvm::APInt(IntSize, 8), Context->IntTy, SourceLocation()); - BinaryOperator *lessThanExpr = + BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy, VK_RValue, OK_Ordinary, SourceLocation(), FPOptions()); @@ -3000,7 +3000,7 @@ Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp, SourceLocation(), CE, SourceLocation(), STCE, returnType, VK_RValue, OK_Ordinary); - ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), + ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr); } // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info. @@ -3232,14 +3232,14 @@ void RewriteObjC::RewriteImplementations() { RewriteImplementationDecl(CategoryImplementation[i]); } -void RewriteObjC::RewriteByRefString(std::string &ResultStr, +void RewriteObjC::RewriteByRefString(std::string &ResultStr, const std::string &Name, ValueDecl *VD, bool def) { - assert(BlockByRefDeclNo.count(VD) && + assert(BlockByRefDeclNo.count(VD) && "RewriteByRefString: ByRef decl missing"); if (def) ResultStr += "struct "; - ResultStr += "__Block_byref_" + Name + + ResultStr += "__Block_byref_" + Name + "_" + utostr(BlockByRefDeclNo[VD]) ; } @@ -3329,7 +3329,7 @@ std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i, if (HasLocalVariableExternalStorage(*I)) QT = Context->getPointerType(QT); QT.getAsStringInternal(Name, Context->getPrintingPolicy()); - S += Name + " = __cself->" + + S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n"; } } @@ -3365,7 +3365,7 @@ std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i, S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);"; } S += "}\n"; - + S += "\nstatic void __"; S += funcName; S += "_block_dispose_" + utostr(i); @@ -3385,7 +3385,7 @@ std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i, return S; } -std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag, +std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag, std::string Desc) { std::string S = "\nstruct " + Tag; std::string Constructor = " " + Tag; @@ -3474,7 +3474,7 @@ std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag, Constructor += ", "; Constructor += Name + "(_" + Name + "->__forwarding)"; } - + Constructor += " {\n"; if (GlobalVarDecl) Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n"; @@ -3500,19 +3500,19 @@ std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag, return S; } -std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag, +std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag, std::string ImplTag, int i, StringRef FunName, unsigned hasCopy) { std::string S = "\nstatic struct " + DescTag; - + S += " {\n unsigned long reserved;\n"; S += " unsigned long Block_size;\n"; if (hasCopy) { S += " void (*copy)(struct "; S += ImplTag; S += "*, struct "; S += ImplTag; S += "*);\n"; - + S += " void (*dispose)(struct "; S += ImplTag; S += "*);\n"; } @@ -3543,7 +3543,7 @@ void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart, SC += "() {}"; InsertText(FunLocStart, SC); } - + // Insert closures that were part of the function. for (unsigned i = 0, count=0; i < Blocks.size(); i++) { CollectBlockDeclRefInfo(Blocks[i]); @@ -3564,7 +3564,7 @@ void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart, // imported objects in the inner blocks not used in the outer // blocks must be copied/disposed in the outer block as well. if (VD->hasAttr<BlocksAttr>() || - VD->getType()->isObjCObjectPointerType() || + VD->getType()->isObjCObjectPointerType() || VD->getType()->isBlockPointerType()) ImportedBlockDecls.insert(VD); } @@ -3609,7 +3609,7 @@ void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart, SC += "restrict "; InsertText(FunLocStart, SC); } - + Blocks.clear(); InnerDeclRefsCount.clear(); InnerDeclRefs.clear(); @@ -3697,7 +3697,7 @@ QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) { SmallVector<QualType, 8> ArgTypes; QualType Res = FT->getReturnType(); bool HasBlockType = convertBlockPointerToFunctionPointer(Res); - + if (FTP) { for (auto &I : FTP->param_types()) { QualType t = I; @@ -3724,13 +3724,13 @@ Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) { CPT = DRE->getType()->getAs<BlockPointerType>(); } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) { CPT = MExpr->getType()->getAs<BlockPointerType>(); - } + } else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) { return SynthesizeBlockCall(Exp, PRE->getSubExpr()); } - else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp)) + else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp)) CPT = IEXPR->getType()->getAs<BlockPointerType>(); - else if (const ConditionalOperator *CEXPR = + else if (const ConditionalOperator *CEXPR = dyn_cast<ConditionalOperator>(BlockExp)) { Expr *LHSExp = CEXPR->getLHS(); Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp); @@ -3831,7 +3831,7 @@ Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) { // }; //} Stmt *RewriteObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) { - // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR + // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR // for each DeclRefExp where BYREFVAR is name of the variable. ValueDecl *VD = DeclRefExp->getDecl(); bool isArrow = DeclRefExp->refersToEnclosingVariableOrCapture() || @@ -3839,7 +3839,7 @@ Stmt *RewriteObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) { FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(), - &Context->Idents.get("__forwarding"), + &Context->Idents.get("__forwarding"), Context->VoidPtrTy, nullptr, /*BitWidth=*/nullptr, /*Mutable=*/true, ICIS_NoInit); @@ -3849,7 +3849,7 @@ Stmt *RewriteObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) { StringRef Name = VD->getName(); FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(), - &Context->Idents.get(Name), + &Context->Idents.get(Name), Context->VoidPtrTy, nullptr, /*BitWidth=*/nullptr, /*Mutable=*/true, ICIS_NoInit); @@ -3858,14 +3858,14 @@ Stmt *RewriteObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) { DeclRefExp->getType(), VK_LValue, OK_Ordinary); // Need parens to enforce precedence. - ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(), - DeclRefExp->getExprLoc(), + ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(), + DeclRefExp->getExprLoc(), ME); ReplaceStmt(DeclRefExp, PE); return PE; } -// Rewrites the imported local variable V with external storage +// Rewrites the imported local variable V with external storage // (static, extern, etc.) as *V // Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) { @@ -3877,7 +3877,7 @@ Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) { VK_LValue, OK_Ordinary, DRE->getLocation(), false); // Need parens to enforce precedence. - ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), + ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), Exp); ReplaceStmt(DRE, PE); return PE; @@ -3991,7 +3991,7 @@ bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) { I->getPointeeType()->isObjCQualifiedInterfaceType()) return true; } - + } return false; } @@ -4057,7 +4057,7 @@ void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) { } buf += ')'; OrigLength++; - + if (PointerTypeTakesAnyBlockArguments(DeclT) || PointerTypeTakesAnyObjCQualifiedType(DeclT)) { // Replace the '^' with '*' for arguments. @@ -4070,7 +4070,7 @@ void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) { if (*argListBegin == '^') buf += '*'; else if (*argListBegin == '<') { - buf += "/*"; + buf += "/*"; buf += *argListBegin++; OrigLength++; while (*argListBegin != '>') { @@ -4094,19 +4094,19 @@ void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) { /// SynthesizeByrefCopyDestroyHelper - This routine synthesizes: /// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst, /// struct Block_byref_id_object *src) { -/// _Block_object_assign (&_dest->object, _src->object, +/// _Block_object_assign (&_dest->object, _src->object, /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT /// [|BLOCK_FIELD_IS_WEAK]) // object -/// _Block_object_assign(&_dest->object, _src->object, +/// _Block_object_assign(&_dest->object, _src->object, /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK /// [|BLOCK_FIELD_IS_WEAK]) // block /// } /// And: /// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) { -/// _Block_object_dispose(_src->object, +/// _Block_object_dispose(_src->object, /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT /// [|BLOCK_FIELD_IS_WEAK]) // object -/// _Block_object_dispose(_src->object, +/// _Block_object_dispose(_src->object, /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK /// [|BLOCK_FIELD_IS_WEAK]) // block /// } @@ -4120,14 +4120,14 @@ std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD, S = "static void __Block_byref_id_object_copy_"; S += utostr(flag); S += "(void *dst, void *src) {\n"; - + // offset into the object pointer is computed as: // void * + void* + int + int + void* + void * - unsigned IntSize = + unsigned IntSize = static_cast<unsigned>(Context->getTypeSize(Context->IntTy)); - unsigned VoidPtrSize = + unsigned VoidPtrSize = static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy)); - + unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth(); S += " _Block_object_assign((char*)dst + "; S += utostr(offset); @@ -4136,7 +4136,7 @@ std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD, S += "), "; S += utostr(flag); S += ");\n}\n"; - + S += "static void __Block_byref_id_object_dispose_"; S += utostr(flag); S += "(void *src) {\n"; @@ -4161,8 +4161,8 @@ std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD, /// }; /// /// It then replaces declaration of ND variable with: -/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag, -/// __size=sizeof(struct __Block_byref_ND), +/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag, +/// __size=sizeof(struct __Block_byref_ND), /// ND=initializer-if-any}; /// /// @@ -4191,7 +4191,7 @@ void RewriteObjC::RewriteByRefVar(VarDecl *ND) { ByrefType += " *__forwarding;\n"; ByrefType += " int __flags;\n"; ByrefType += " int __size;\n"; - // Add void *__Block_byref_id_object_copy; + // Add void *__Block_byref_id_object_copy; // void *__Block_byref_id_object_dispose; if needed. QualType Ty = ND->getType(); bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND); @@ -4203,7 +4203,7 @@ void RewriteObjC::RewriteByRefVar(VarDecl *ND) { QualType T = Ty; (void)convertBlockPointerToFunctionPointer(T); T.getAsStringInternal(Name, Context->getPrintingPolicy()); - + ByrefType += " " + Name + ";\n"; ByrefType += "};\n"; // Insert this type in global scope. It is needed by helper function. @@ -4219,7 +4219,7 @@ void RewriteObjC::RewriteByRefVar(VarDecl *ND) { flag |= BLOCK_FIELD_IS_WEAK; isa = 1; } - + if (HasCopyAndDispose) { flag = BLOCK_BYREF_CALLER; QualType Ty = ND->getType(); @@ -4232,9 +4232,9 @@ void RewriteObjC::RewriteByRefVar(VarDecl *ND) { if (!HF.empty()) InsertText(FunLocStart, HF); } - - // struct __Block_byref_ND ND = - // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND), + + // struct __Block_byref_ND ND = + // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND), // initializer-if-any}; bool hasInit = (ND->getInit() != nullptr); unsigned flags = 0; @@ -4294,13 +4294,13 @@ void RewriteObjC::RewriteByRefVar(VarDecl *ND) { ByrefType += ", "; } ReplaceText(DeclLoc, endBuf-startBuf, ByrefType); - + // Complete the newly synthesized compound expression by inserting a right // curly brace before the end of the declaration. // FIXME: This approach avoids rewriting the initializer expression. It // also assumes there is only one declarator. For example, the following // isn't currently supported by this routine (in general): - // + // // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37; // const char *startInitializerBuf = SM->getCharacterData(startLoc); @@ -4336,7 +4336,7 @@ void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) { // Find any imported blocks...they will need special attention. for (unsigned i = 0; i < BlockDeclRefs.size(); i++) if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() || - BlockDeclRefs[i]->getType()->isObjCObjectPointerType() || + BlockDeclRefs[i]->getType()->isObjCObjectPointerType() || BlockDeclRefs[i]->getType()->isBlockPointerType()) ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl()); } @@ -4356,7 +4356,7 @@ Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp, Blocks.push_back(Exp); CollectBlockDeclRefInfo(Exp); - + // Add inner imported variables now used in current block. int countOfInnerDecls = 0; if (!InnerBlockDeclRefs.empty()) { @@ -4382,12 +4382,12 @@ Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp, // Find any imported blocks...they will need special attention. for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() || - InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() || + InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() || InnerBlockDeclRefs[i]->getType()->isBlockPointerType()) ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl()); } InnerDeclRefsCount.push_back(countOfInnerDecls); - + std::string FuncName; if (CurFunctionDef) @@ -4434,13 +4434,13 @@ Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp, new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false, Context->VoidPtrTy, VK_LValue, - SourceLocation()), + SourceLocation()), UO_AddrOf, - Context->getPointerType(Context->VoidPtrTy), + Context->getPointerType(Context->VoidPtrTy), VK_RValue, OK_Ordinary, SourceLocation(), false); - InitExprs.push_back(DescRefExpr); - + InitExprs.push_back(DescRefExpr); + // Add initializers for any closure decl refs. if (BlockDeclRefs.size()) { Expr *Exp; @@ -4486,14 +4486,14 @@ Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp, std::string Name(ND->getNameAsString()); std::string RecName; RewriteByRefString(RecName, Name, ND, true); - IdentifierInfo *II = &Context->Idents.get(RecName.c_str() + IdentifierInfo *II = &Context->Idents.get(RecName.c_str() + sizeof("struct")); RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl, SourceLocation(), SourceLocation(), II); assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl"); QualType castT = Context->getPointerType(Context->getTagDeclType(RD)); - + FD = SynthBlockInitFunctionDecl((*I)->getName()); Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue, SourceLocation()); @@ -4502,7 +4502,7 @@ Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp, for (const auto &CI : block->captures()) { const VarDecl *variable = CI.getVariable(); if (variable == ND && CI.isNested()) { - assert (CI.isByRef() && + assert (CI.isByRef() && "SynthBlockInitExpr - captured block variable is not byref"); isNestedCapturedVar = true; break; @@ -4521,9 +4521,9 @@ Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp, if (ImportedBlockDecls.size()) { // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR); - unsigned IntSize = + unsigned IntSize = static_cast<unsigned>(Context->getTypeSize(Context->IntTy)); - Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag), + Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag), Context->IntTy, SourceLocation()); InitExprs.push_back(FlagExp); } @@ -4544,7 +4544,7 @@ Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp, } bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) { - if (const ObjCForCollectionStmt * CS = + if (const ObjCForCollectionStmt * CS = dyn_cast<ObjCForCollectionStmt>(Stmts.back())) return CS->getElement() == DS; return false; @@ -4614,7 +4614,7 @@ Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) { RewrittenBlockExprs[BE] = Str; Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs); - + //blockTranscribed->dump(); ReplaceStmt(S, blockTranscribed); return blockTranscribed; @@ -4685,7 +4685,7 @@ Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) { // the context of an ObjCForCollectionStmt. For example: // NSArray *someArray; // for (id <FooProtocol> index in someArray) ; - // This is because RewriteObjCForCollectionStmt() does textual rewriting + // This is because RewriteObjCForCollectionStmt() does textual rewriting // and it depends on the original text locations/positions. if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS)) RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin()); @@ -4705,7 +4705,7 @@ Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) { BlockByRefDeclNo[ND] = uniqueByrefDeclCount++; RewriteByRefVar(VD); } - else + else RewriteTypeOfDecl(VD); } } @@ -4731,13 +4731,13 @@ Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) { } // Handle blocks rewriting. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) { - ValueDecl *VD = DRE->getDecl(); + ValueDecl *VD = DRE->getDecl(); if (VD->hasAttr<BlocksAttr>()) return RewriteBlockDeclRefExpr(DRE); if (HasLocalVariableExternalStorage(VD)) return RewriteLocalVariableExternalStorage(DRE); } - + if (CallExpr *CE = dyn_cast<CallExpr>(S)) { if (CE->getCallee()->getType()->isBlockPointerType()) { Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee()); @@ -4894,7 +4894,7 @@ void RewriteObjC::HandleDeclInMainFile(Decl *D) { case Decl::CXXRecord: case Decl::Record: { RecordDecl *RD = cast<RecordDecl>(D); - if (RD->isCompleteDefinition()) + if (RD->isCompleteDefinition()) RewriteRecordBody(RD); break; } @@ -4942,7 +4942,7 @@ void RewriteObjC::HandleTranslationUnit(ASTContext &C) { void RewriteObjCFragileABI::Initialize(ASTContext &context) { InitializeCommon(context); - + // declaring objc_selector outside the parameter list removes a silly // scope related warning... if (IsHeader) @@ -5079,7 +5079,7 @@ void RewriteObjCFragileABI::RewriteObjCProtocolMetaData( ObjCProtocolDecl *PDecl, StringRef prefix, StringRef ClassName, std::string &Result) { static bool objc_protocol_methods = false; - + // Output struct protocol_methods holder of method selector and type. if (!objc_protocol_methods && PDecl->hasDefinition()) { /* struct protocol_methods { @@ -5091,16 +5091,16 @@ void RewriteObjCFragileABI::RewriteObjCProtocolMetaData( Result += "\tstruct objc_selector *_cmd;\n"; Result += "\tchar *method_types;\n"; Result += "};\n"; - + objc_protocol_methods = true; } // Do not synthesize the protocol more than once. if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl())) return; - + if (ObjCProtocolDecl *Def = PDecl->getDefinition()) PDecl = Def; - + if (PDecl->instmeth_begin() != PDecl->instmeth_end()) { unsigned NumMethods = std::distance(PDecl->instmeth_begin(), PDecl->instmeth_end()); @@ -5117,7 +5117,7 @@ void RewriteObjCFragileABI::RewriteObjCProtocolMetaData( Result += PDecl->getNameAsString(); Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= " "{\n\t" + utostr(NumMethods) + "\n"; - + // Output instance methods declared in this protocol. for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(), E = PDecl->instmeth_end(); @@ -5134,7 +5134,7 @@ void RewriteObjCFragileABI::RewriteObjCProtocolMetaData( } Result += "\t }\n};\n"; } - + // Output class methods declared in this protocol. unsigned NumMethods = std::distance(PDecl->classmeth_begin(), PDecl->classmeth_end()); @@ -5154,7 +5154,7 @@ void RewriteObjCFragileABI::RewriteObjCProtocolMetaData( "{\n\t"; Result += utostr(NumMethods); Result += "\n"; - + // Output instance methods declared in this protocol. for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(), E = PDecl->classmeth_end(); @@ -5171,7 +5171,7 @@ void RewriteObjCFragileABI::RewriteObjCProtocolMetaData( } Result += "\t }\n};\n"; } - + // Output: /* struct _objc_protocol { // Objective-C 1.0 extensions @@ -5191,10 +5191,10 @@ void RewriteObjCFragileABI::RewriteObjCProtocolMetaData( Result += "\tstruct _objc_protocol_method_list *instance_methods;\n"; Result += "\tstruct _objc_protocol_method_list *class_methods;\n"; Result += "};\n"; - + objc_protocol = true; } - + Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_"; Result += PDecl->getNameAsString(); Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= " @@ -5216,7 +5216,7 @@ void RewriteObjCFragileABI::RewriteObjCProtocolMetaData( else Result += "0\n"; Result += "};\n"; - + // Mark this protocol as having been generated. if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()).second) llvm_unreachable("protocol already synthesized"); @@ -5227,10 +5227,10 @@ void RewriteObjCFragileABI::RewriteObjCProtocolListMetaData( StringRef prefix, StringRef ClassName, std::string &Result) { if (Protocols.empty()) return; - + for (unsigned i = 0; i != Protocols.size(); i++) RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result); - + // Output the top lovel protocol meta-data for the class. /* struct _objc_protocol_list { struct _objc_protocol_list *next; @@ -5251,11 +5251,11 @@ void RewriteObjCFragileABI::RewriteObjCProtocolListMetaData( "{\n\t0, "; Result += utostr(Protocols.size()); Result += "\n"; - + Result += "\t,{&_OBJC_PROTOCOL_"; Result += Protocols[0]->getNameAsString(); Result += " \n"; - + for (unsigned i = 1; i != Protocols.size(); i++) { Result += "\t ,&_OBJC_PROTOCOL_"; Result += Protocols[i]->getNameAsString(); @@ -5267,14 +5267,14 @@ void RewriteObjCFragileABI::RewriteObjCProtocolListMetaData( void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl, std::string &Result) { ObjCInterfaceDecl *CDecl = IDecl->getClassInterface(); - + // Explicitly declared @interface's are already synthesized. if (CDecl->isImplicitInterfaceDecl()) { // FIXME: Implementation of a class with no @interface (legacy) does not // produce correct synthesis as yet. RewriteObjCInternalStruct(CDecl, Result); } - + // Build _objc_ivar_list metadata for classes ivars if needed unsigned NumIvars = !IDecl->ivar_empty() ? IDecl->ivar_size() @@ -5293,10 +5293,10 @@ void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDe Result += "\tchar *ivar_type;\n"; Result += "\tint ivar_offset;\n"; Result += "};\n"; - + objc_ivar = true; } - + /* struct { int ivar_count; struct _objc_ivar ivar_list[nIvars]; @@ -5312,7 +5312,7 @@ void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDe "{\n\t"; Result += utostr(NumIvars); Result += "\n"; - + ObjCInterfaceDecl::ivar_iterator IVI, IVE; SmallVector<ObjCIvarDecl *, 8> IVars; if (!IDecl->ivar_empty()) { @@ -5346,13 +5346,13 @@ void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDe RewriteIvarOffsetComputation(*IVI, Result); Result += "}\n"; } - + Result += "\t }\n};\n"; } - + // Build _objc_method_list for class's instance methods if needed SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods()); - + // If any of our property implementations have associated getters or // setters, produce metadata for them as well. for (const auto *Prop : IDecl->property_impls()) { @@ -5374,15 +5374,15 @@ void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDe } RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(), true, "", IDecl->getName(), Result); - + // Build _objc_method_list for class's class methods if needed RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(), false, "", IDecl->getName(), Result); - + // Protocols referenced in class declaration? RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CLASS", CDecl->getName(), Result); - + // Declaration of class/meta-class metadata /* struct _objc_class { struct _objc_class *isa; // or const char *root_class_name when metadata @@ -5417,7 +5417,7 @@ void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDe Result += "};\n"; objc_class = true; } - + // Meta-class metadata generation. ObjCInterfaceDecl *RootClass = nullptr; ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass(); @@ -5426,14 +5426,14 @@ void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDe SuperClass = SuperClass->getSuperClass(); } SuperClass = CDecl->getSuperClass(); - + Result += "\nstatic struct _objc_class _OBJC_METACLASS_"; Result += CDecl->getNameAsString(); Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= " "{\n\t(struct _objc_class *)\""; Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString()); Result += "\""; - + if (SuperClass) { Result += ", \""; Result += SuperClass->getNameAsString(); @@ -5464,7 +5464,7 @@ void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDe else Result += "\t,0,0,0,0\n"; Result += "};\n"; - + // class metadata generation. Result += "\nstatic struct _objc_class _OBJC_CLASS_"; Result += CDecl->getNameAsString(); @@ -5522,15 +5522,15 @@ void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDe void RewriteObjCFragileABI::RewriteMetaDataIntoBuffer(std::string &Result) { int ClsDefCount = ClassImplementation.size(); int CatDefCount = CategoryImplementation.size(); - + // For each implemented class, write out all its meta data. for (int i = 0; i < ClsDefCount; i++) RewriteObjCClassMetaData(ClassImplementation[i], Result); - + // For each implemented category, write out all its meta data. for (int i = 0; i < CatDefCount; i++) RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result); - + // Write objc_symtab metadata /* struct _objc_symtab @@ -5542,7 +5542,7 @@ void RewriteObjCFragileABI::RewriteMetaDataIntoBuffer(std::string &Result) { void *defs[cls_def_cnt + cat_def_cnt]; }; */ - + Result += "\nstruct _objc_symtab {\n"; Result += "\tlong sel_ref_cnt;\n"; Result += "\tSEL *refs;\n"; @@ -5550,7 +5550,7 @@ void RewriteObjCFragileABI::RewriteMetaDataIntoBuffer(std::string &Result) { Result += "\tshort cat_def_cnt;\n"; Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n"; Result += "};\n\n"; - + Result += "static struct _objc_symtab " "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n"; Result += "\t0, 0, " + utostr(ClsDefCount) @@ -5560,7 +5560,7 @@ void RewriteObjCFragileABI::RewriteMetaDataIntoBuffer(std::string &Result) { Result += ClassImplementation[i]->getNameAsString(); Result += "\n"; } - + for (int i = 0; i < CatDefCount; i++) { Result += "\t,&_OBJC_CATEGORY_"; Result += CategoryImplementation[i]->getClassInterface()->getNameAsString(); @@ -5568,11 +5568,11 @@ void RewriteObjCFragileABI::RewriteMetaDataIntoBuffer(std::string &Result) { Result += CategoryImplementation[i]->getNameAsString(); Result += "\n"; } - + Result += "};\n\n"; - + // Write objc_module metadata - + /* struct _objc_module { long version; @@ -5581,7 +5581,7 @@ void RewriteObjCFragileABI::RewriteMetaDataIntoBuffer(std::string &Result) { struct _objc_symtab *symtab; } */ - + Result += "\nstruct _objc_module {\n"; Result += "\tlong version;\n"; Result += "\tlong size;\n"; @@ -5593,7 +5593,7 @@ void RewriteObjCFragileABI::RewriteMetaDataIntoBuffer(std::string &Result) { Result += "\t" + utostr(OBJC_ABI_VERSION) + ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n"; Result += "};\n\n"; - + if (LangOpts.MicrosoftExt) { if (ProtocolExprDecls.size()) { Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n"; @@ -5623,14 +5623,14 @@ void RewriteObjCFragileABI::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *ID // Find category declaration for this implementation. ObjCCategoryDecl *CDecl = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier()); - + std::string FullCategoryName = ClassDecl->getNameAsString(); FullCategoryName += '_'; FullCategoryName += IDecl->getNameAsString(); - + // Build _objc_method_list for class's instance methods if needed SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods()); - + // If any of our property implementations have associated getters or // setters, produce metadata for them as well. for (const auto *Prop : IDecl->property_impls()) { @@ -5672,7 +5672,7 @@ void RewriteObjCFragileABI::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *ID // @property decl. }; */ - + static bool objc_category = false; if (!objc_category) { Result += "\nstruct _objc_category {\n"; @@ -5693,7 +5693,7 @@ void RewriteObjCFragileABI::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *ID Result += "\"\n\t, \""; Result += ClassDecl->getNameAsString(); Result += "\"\n"; - + if (IDecl->instmeth_begin() != IDecl->instmeth_end()) { Result += "\t, (struct _objc_method_list *)" "&_OBJC_CATEGORY_INSTANCE_METHODS_"; @@ -5710,7 +5710,7 @@ void RewriteObjCFragileABI::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *ID } else Result += "\t, 0\n"; - + if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) { Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_"; Result += FullCategoryName; @@ -5731,7 +5731,7 @@ void RewriteObjCFragileABI::RewriteObjCMethodsMetaData(MethodIterator MethodBegi StringRef ClassName, std::string &Result) { if (MethodBegin == MethodEnd) return; - + if (!objc_impl_method) { /* struct _objc_method { SEL _cmd; @@ -5744,12 +5744,12 @@ void RewriteObjCFragileABI::RewriteObjCMethodsMetaData(MethodIterator MethodBegi Result += "\tchar *method_types;\n"; Result += "\tvoid *_imp;\n"; Result += "};\n"; - + objc_impl_method = true; } - + // Build _objc_method_list for class's methods if needed - + /* struct { struct _objc_method_list *next_method; int method_count; @@ -5771,7 +5771,7 @@ void RewriteObjCFragileABI::RewriteObjCMethodsMetaData(MethodIterator MethodBegi Result += IsInstanceMethod ? "inst" : "cls"; Result += "_meth\")))= "; Result += "{\n\t0, " + utostr(NumMethods) + "\n"; - + Result += "\t,{{(SEL)\""; Result += (*MethodBegin)->getSelector().getAsString(); std::string MethodTypeString = @@ -5798,16 +5798,16 @@ void RewriteObjCFragileABI::RewriteObjCMethodsMetaData(MethodIterator MethodBegi Stmt *RewriteObjCFragileABI::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) { SourceRange OldRange = IV->getSourceRange(); Expr *BaseExpr = IV->getBase(); - + // Rewrite the base, but without actually doing replaces. { DisableReplaceStmtScope S(*this); BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr)); IV->setBase(BaseExpr); } - + ObjCIvarDecl *D = IV->getDecl(); - + Expr *Replacement = IV; if (CurMethodDef) { if (BaseExpr->getType()->isObjCObjectPointerType()) { @@ -5819,7 +5819,7 @@ Stmt *RewriteObjCFragileABI::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) { iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared); assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class"); - + // Synthesize an explicit cast to gain access to the ivar. std::string RecName = clsDeclared->getIdentifier()->getName(); RecName += "_IMPL"; @@ -5848,7 +5848,7 @@ Stmt *RewriteObjCFragileABI::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) { } } else { // we are outside a method. assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method"); - + // Explicit ivar refs need to have a cast inserted. // FIXME: consider sharing some of this code with the code above. if (BaseExpr->getType()->isObjCObjectPointerType()) { @@ -5859,7 +5859,7 @@ Stmt *RewriteObjCFragileABI::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) { iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared); assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class"); - + // Synthesize an explicit cast to gain access to the ivar. std::string RecName = clsDeclared->getIdentifier()->getName(); RecName += "_IMPL"; @@ -5881,9 +5881,9 @@ Stmt *RewriteObjCFragileABI::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) { IV->setBase(PE); } } - + ReplaceStmtWithRange(IV, Replacement, OldRange); - return Replacement; + return Replacement; } #endif // CLANG_ENABLE_OBJC_REWRITER diff --git a/lib/Frontend/SerializedDiagnosticPrinter.cpp b/lib/Frontend/SerializedDiagnosticPrinter.cpp index ca60c4812f72..22546ce4c097 100644 --- a/lib/Frontend/SerializedDiagnosticPrinter.cpp +++ b/lib/Frontend/SerializedDiagnosticPrinter.cpp @@ -28,31 +28,31 @@ using namespace clang; using namespace clang::serialized_diags; namespace { - + class AbbreviationMap { llvm::DenseMap<unsigned, unsigned> Abbrevs; public: AbbreviationMap() {} - + void set(unsigned recordID, unsigned abbrevID) { - assert(Abbrevs.find(recordID) == Abbrevs.end() + assert(Abbrevs.find(recordID) == Abbrevs.end() && "Abbreviation already set."); Abbrevs[recordID] = abbrevID; } - + unsigned get(unsigned recordID) { assert(Abbrevs.find(recordID) != Abbrevs.end() && "Abbreviation not set."); return Abbrevs[recordID]; } }; - + typedef SmallVector<uint64_t, 64> RecordData; typedef SmallVectorImpl<uint64_t> RecordDataImpl; typedef ArrayRef<uint64_t> RecordDataRef; class SDiagsWriter; - + class SDiagsRenderer : public DiagnosticNoteRenderer { SDiagsWriter &Writer; public: @@ -172,7 +172,7 @@ private: /// Emit the preamble for the serialized diagnostics. void EmitPreamble(); - + /// Emit the BLOCKINFO block. void EmitBlockInfoBlock(); @@ -197,10 +197,10 @@ private: /// Emit a record for a CharSourceRange. void EmitCharSourceRange(CharSourceRange R, const SourceManager &SM); - + /// Emit the string information for the category. unsigned getEmitCategory(unsigned category = 0); - + /// Emit the string information for diagnostic flags. unsigned getEmitDiagnosticFlag(DiagnosticsEngine::Level DiagLevel, unsigned DiagID = 0); @@ -312,7 +312,7 @@ static void EmitBlockID(unsigned ID, const char *Name, Record.clear(); Record.push_back(ID); Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record); - + // Emit the block name if present. if (!Name || Name[0] == 0) return; @@ -370,11 +370,11 @@ void SDiagsWriter::AddCharSourceRangeToRecord(CharSourceRange Range, unsigned SDiagsWriter::getEmitFile(const char *FileName){ if (!FileName) return 0; - + unsigned &entry = State->Files[FileName]; if (entry) return entry; - + // Lazily generate the record for the file. entry = State->Files.size(); StringRef Name(FileName); @@ -417,7 +417,7 @@ static void AddSourceLocationAbbrev(llvm::BitCodeAbbrev &Abbrev) { static void AddRangeLocationAbbrev(llvm::BitCodeAbbrev &Abbrev) { AddSourceLocationAbbrev(Abbrev); - AddSourceLocationAbbrev(Abbrev); + AddSourceLocationAbbrev(Abbrev); } void SDiagsWriter::EmitBlockInfoBlock() { @@ -456,12 +456,12 @@ void SDiagsWriter::EmitBlockInfoBlock() { Abbrev->Add(BitCodeAbbrevOp(RECORD_DIAG)); Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Diag level. AddSourceLocationAbbrev(*Abbrev); - Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 10)); // Category. + Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 10)); // Category. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 10)); // Mapped Diag ID. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // Text size. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Diagnostc text. Abbrevs.set(RECORD_DIAG, Stream.EmitBlockInfoAbbrev(BLOCK_DIAG, Abbrev)); - + // Emit abbreviation for RECORD_CATEGORY. Abbrev = std::make_shared<BitCodeAbbrev>(); Abbrev->Add(BitCodeAbbrevOp(RECORD_CATEGORY)); @@ -476,7 +476,7 @@ void SDiagsWriter::EmitBlockInfoBlock() { AddRangeLocationAbbrev(*Abbrev); Abbrevs.set(RECORD_SOURCE_RANGE, Stream.EmitBlockInfoAbbrev(BLOCK_DIAG, Abbrev)); - + // Emit the abbreviation for RECORD_DIAG_FLAG. Abbrev = std::make_shared<BitCodeAbbrev>(); Abbrev->Add(BitCodeAbbrevOp(RECORD_DIAG_FLAG)); @@ -485,18 +485,18 @@ void SDiagsWriter::EmitBlockInfoBlock() { Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Flag name text. Abbrevs.set(RECORD_DIAG_FLAG, Stream.EmitBlockInfoAbbrev(BLOCK_DIAG, Abbrev)); - + // Emit the abbreviation for RECORD_FILENAME. Abbrev = std::make_shared<BitCodeAbbrev>(); Abbrev->Add(BitCodeAbbrevOp(RECORD_FILENAME)); Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 10)); // Mapped file ID. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // Size. - Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // Modification time. + Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // Modification time. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Text size. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name text. Abbrevs.set(RECORD_FILENAME, Stream.EmitBlockInfoAbbrev(BLOCK_DIAG, Abbrev)); - + // Emit the abbreviation for RECORD_FIXIT. Abbrev = std::make_shared<BitCodeAbbrev>(); Abbrev->Add(BitCodeAbbrevOp(RECORD_FIXIT)); @@ -529,7 +529,7 @@ unsigned SDiagsWriter::getEmitCategory(unsigned int category) { RecordData::value_type Record[] = {RECORD_CATEGORY, category, catName.size()}; State->Stream.EmitRecordWithBlob(State->Abbrevs.get(RECORD_CATEGORY), Record, catName); - + return category; } @@ -537,7 +537,7 @@ unsigned SDiagsWriter::getEmitDiagnosticFlag(DiagnosticsEngine::Level DiagLevel, unsigned DiagID) { if (DiagLevel == DiagnosticsEngine::Note) return 0; // No flag for notes. - + StringRef FlagName = DiagnosticIDs::getWarningOptionForDiag(DiagID); return getEmitDiagnosticFlag(FlagName); } @@ -553,7 +553,7 @@ unsigned SDiagsWriter::getEmitDiagnosticFlag(StringRef FlagName) { if (entry.first == 0) { entry.first = State->DiagFlags.size(); entry.second = FlagName; - + // Lazily emit the string in a separate record. RecordData::value_type Record[] = {RECORD_DIAG_FLAG, entry.first, FlagName.size()}; @@ -630,7 +630,7 @@ void SDiagsWriter::EmitDiagnosticMessage(FullSourceLoc Loc, PresumedLoc PLoc, llvm::BitstreamWriter &Stream = State->Stream; RecordData &Record = State->Record; AbbreviationMap &Abbrevs = State->Abbrevs; - + // Emit the RECORD_DIAG record. Record.clear(); Record.push_back(RECORD_DIAG); diff --git a/lib/Frontend/TestModuleFileExtension.cpp b/lib/Frontend/TestModuleFileExtension.cpp index 294f7e44cee5..087bdc543548 100644 --- a/lib/Frontend/TestModuleFileExtension.cpp +++ b/lib/Frontend/TestModuleFileExtension.cpp @@ -91,7 +91,7 @@ llvm::hash_code TestModuleFileExtension::hashExtension( Code = llvm::hash_combine(Code, MinorVersion); Code = llvm::hash_combine(Code, UserInfo); } - + return Code; } diff --git a/lib/Frontend/TextDiagnostic.cpp b/lib/Frontend/TextDiagnostic.cpp index 85cd019005da..35b99b10f94a 100644 --- a/lib/Frontend/TextDiagnostic.cpp +++ b/lib/Frontend/TextDiagnostic.cpp @@ -100,7 +100,7 @@ printableTextForNextCharacter(StringRef SourceLine, size_t *i, unsigned TabStop) { assert(i && "i must not be null"); assert(*i<SourceLine.size() && "must point to a valid index"); - + if (SourceLine[*i]=='\t') { assert(0 < TabStop && TabStop <= DiagnosticOptions::MaxTabStop && "Invalid -ftabstop value"); @@ -118,7 +118,7 @@ printableTextForNextCharacter(StringRef SourceLine, size_t *i, unsigned char const *begin, *end; begin = reinterpret_cast<unsigned char const *>(&*(SourceLine.begin() + *i)); end = begin + (SourceLine.size() - *i); - + if (llvm::isLegalUTF8Sequence(begin, end)) { llvm::UTF32 c; llvm::UTF32 *cptr = &c; @@ -203,7 +203,7 @@ static void byteToColumn(StringRef SourceLine, unsigned TabStop, out.resize(1u,0); return; } - + out.resize(SourceLine.size()+1, -1); int columns = 0; @@ -255,10 +255,10 @@ namespace { struct SourceColumnMap { SourceColumnMap(StringRef SourceLine, unsigned TabStop) : m_SourceLine(SourceLine) { - + ::byteToColumn(SourceLine, TabStop, m_byteToColumn); ::columnToByte(SourceLine, TabStop, m_columnToByte); - + assert(m_byteToColumn.size()==SourceLine.size()+1); assert(0 < m_byteToColumn.size() && 0 < m_columnToByte.size()); assert(m_byteToColumn.size() @@ -309,7 +309,7 @@ struct SourceColumnMap { StringRef getSourceLine() const { return m_SourceLine; } - + private: const std::string m_SourceLine; SmallVector<int,200> m_byteToColumn; @@ -684,7 +684,7 @@ void TextDiagnostic::emitDiagnosticMessage( if (DiagOpts->ShowColors) OS.resetColor(); - + printDiagnosticLevel(OS, Level, DiagOpts->ShowColors, DiagOpts->CLFallbackMode); printDiagnosticMessage(OS, @@ -891,7 +891,7 @@ void TextDiagnostic::emitIncludeLocation(FullSourceLoc Loc, PresumedLoc PLoc) { OS << "In file included from " << PLoc.getFilename() << ':' << PLoc.getLine() << ":\n"; else - OS << "In included file:\n"; + OS << "In included file:\n"; } void TextDiagnostic::emitImportLocation(FullSourceLoc Loc, PresumedLoc PLoc, @@ -1269,15 +1269,15 @@ void TextDiagnostic::emitSnippet(StringRef line) { return; size_t i = 0; - + std::string to_print; bool print_reversed = false; - + while (i<line.size()) { std::pair<SmallString<16>,bool> res = printableTextForNextCharacter(line, &i, DiagOpts->TabStop); bool was_printable = res.second; - + if (DiagOpts->ShowColors && was_printable == print_reversed) { if (print_reversed) OS.reverseColor(); @@ -1286,17 +1286,17 @@ void TextDiagnostic::emitSnippet(StringRef line) { if (DiagOpts->ShowColors) OS.resetColor(); } - + print_reversed = !was_printable; to_print += res.first.str(); } - + if (print_reversed && DiagOpts->ShowColors) OS.reverseColor(); OS << to_print; if (print_reversed && DiagOpts->ShowColors) OS.resetColor(); - + OS << '\n'; } diff --git a/lib/FrontendTool/ExecuteCompilerInvocation.cpp b/lib/FrontendTool/ExecuteCompilerInvocation.cpp index ac2ee50a1e4b..747fdd241640 100644 --- a/lib/FrontendTool/ExecuteCompilerInvocation.cpp +++ b/lib/FrontendTool/ExecuteCompilerInvocation.cpp @@ -139,7 +139,7 @@ CreateFrontendAction(CompilerInstance &CI) { if (FEOpts.FixAndRecompile) { Act = llvm::make_unique<FixItRecompile>(std::move(Act)); } - + #if CLANG_ENABLE_ARCMT if (CI.getFrontendOpts().ProgramAction != frontend::MigrateSource && CI.getFrontendOpts().ProgramAction != frontend::GeneratePCH) { @@ -260,4 +260,4 @@ bool ExecuteCompilerInvocation(CompilerInstance *Clang) { return Success; } -} // namespace clang +} // namespace clang diff --git a/lib/Headers/avx512fintrin.h b/lib/Headers/avx512fintrin.h index 81696953b76e..8dd4a0a40eea 100644 --- a/lib/Headers/avx512fintrin.h +++ b/lib/Headers/avx512fintrin.h @@ -319,9 +319,9 @@ _mm512_set1_epi32(int __s) } static __inline __m512i __DEFAULT_FN_ATTRS512 -_mm512_maskz_set1_epi32(__mmask16 __M, int __A) +_mm512_maskz_set1_epi32(__mmask16 __M, int __A) { - return (__m512i)__builtin_ia32_selectd_512(__M, + return (__m512i)__builtin_ia32_selectd_512(__M, (__v16si)_mm512_set1_epi32(__A), (__v16si)_mm512_setzero_si512()); } diff --git a/lib/Headers/avx512vlcdintrin.h b/lib/Headers/avx512vlcdintrin.h index 127c5b132ac7..903a7c25493f 100644 --- a/lib/Headers/avx512vlcdintrin.h +++ b/lib/Headers/avx512vlcdintrin.h @@ -34,7 +34,7 @@ static __inline__ __m128i __DEFAULT_FN_ATTRS128 _mm_broadcastmb_epi64 (__mmask8 __A) -{ +{ return (__m128i) _mm_set1_epi64x((long long) __A); } diff --git a/lib/Headers/clzerointrin.h b/lib/Headers/clzerointrin.h index 07628acd8005..f4e920839bee 100644 --- a/lib/Headers/clzerointrin.h +++ b/lib/Headers/clzerointrin.h @@ -45,6 +45,6 @@ _mm_clzero (void * __line) __builtin_ia32_clzero ((void *)__line); } -#undef __DEFAULT_FN_ATTRS +#undef __DEFAULT_FN_ATTRS #endif /* __CLZEROINTRIN_H */ diff --git a/lib/Headers/lwpintrin.h b/lib/Headers/lwpintrin.h index 3455575cced6..0b28d7358295 100644 --- a/lib/Headers/lwpintrin.h +++ b/lib/Headers/lwpintrin.h @@ -84,7 +84,7 @@ __slwpcb (void) (__builtin_ia32_lwpins32((unsigned int) (DATA2), (unsigned int) (DATA1), \ (unsigned int) (FLAGS))) -/// Decrements the LWP programmed value sample event counter. If the result is +/// Decrements the LWP programmed value sample event counter. If the result is /// negative, inserts an event record into the LWP event ring buffer in memory /// and advances the ring buffer pointer. /// @@ -125,7 +125,7 @@ __slwpcb (void) (__builtin_ia32_lwpins64((unsigned long long) (DATA2), (unsigned int) (DATA1), \ (unsigned int) (FLAGS))) -/// Decrements the LWP programmed value sample event counter. If the result is +/// Decrements the LWP programmed value sample event counter. If the result is /// negative, inserts an event record into the LWP event ring buffer in memory /// and advances the ring buffer pointer. /// diff --git a/lib/Headers/opencl-c.h b/lib/Headers/opencl-c.h index e648b0f2f370..e481c792df71 100644 --- a/lib/Headers/opencl-c.h +++ b/lib/Headers/opencl-c.h @@ -11540,7 +11540,7 @@ half16 __ovld __cnfn select(half16 a, half16 b, ushort16 c); * * vstoren write sizeof (gentypen) bytes given by data to address (p + (offset * n)). * - * The address computed as (p + (offset * n)) must be + * The address computed as (p + (offset * n)) must be * 8-bit aligned if gentype is char, uchar; * 16-bit aligned if gentype is short, ushort, half; * 32-bit aligned if gentype is int, uint, float; @@ -12888,7 +12888,7 @@ void __ovld write_mem_fence(cl_mem_fence_flags flags); cl_mem_fence_flags __ovld get_fence(const void *ptr); cl_mem_fence_flags __ovld get_fence(void *ptr); -/** +/** * Builtin functions to_global, to_local, and to_private need to be declared as Clang builtin functions * and checked in Sema since they should be declared as * addr gentype* to_addr (gentype*); @@ -13773,7 +13773,7 @@ ulong __ovld atomic_fetch_max_explicit(volatile atomic_ulong *object, long opera // add/sub: atomic type argument can be uintptr_t/intptr_t, value type argument can be ptrdiff_t. // or/xor/and/min/max: atomic type argument can be intptr_t/uintptr_t, value type argument can be intptr_t/uintptr_t. -#if defined(cl_khr_int64_base_atomics) && defined(cl_khr_int64_extended_atomics) +#if defined(cl_khr_int64_base_atomics) && defined(cl_khr_int64_extended_atomics) uintptr_t __ovld atomic_fetch_add(volatile atomic_uintptr_t *object, ptrdiff_t operand); uintptr_t __ovld atomic_fetch_add_explicit(volatile atomic_uintptr_t *object, ptrdiff_t operand, memory_order order); uintptr_t __ovld atomic_fetch_add_explicit(volatile atomic_uintptr_t *object, ptrdiff_t operand, memory_order order, memory_scope scope); @@ -14571,7 +14571,7 @@ int printf(__constant const char* st, ...); * only. The filter_mode specified in sampler * must be set to CLK_FILTER_NEAREST; otherwise * the values returned are undefined. - + * The read_image{f|i|ui} calls that take * integer coordinates must use a sampler with * normalized coordinates set to diff --git a/lib/Index/IndexBody.cpp b/lib/Index/IndexBody.cpp index ac34956b2484..786563a44a4d 100644 --- a/lib/Index/IndexBody.cpp +++ b/lib/Index/IndexBody.cpp @@ -30,7 +30,7 @@ public: BodyIndexer(IndexingContext &indexCtx, const NamedDecl *Parent, const DeclContext *DC) : IndexCtx(indexCtx), Parent(Parent), ParentDC(DC) { } - + bool shouldWalkTypesOfTypeLocs() const { return false; } bool dataTraverseStmtPre(Stmt *S) { @@ -322,7 +322,7 @@ public: } return true; } - + bool VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) { if (ObjCMethodDecl *MD = E->getDictWithObjectsMethod()) { return passObjCLiteralMethodCall(MD, E); diff --git a/lib/Index/IndexTypeSourceInfo.cpp b/lib/Index/IndexTypeSourceInfo.cpp index 7a7a156478f8..4b6bfbc67eff 100644 --- a/lib/Index/IndexTypeSourceInfo.cpp +++ b/lib/Index/IndexTypeSourceInfo.cpp @@ -37,7 +37,7 @@ public: Relations.emplace_back((unsigned)SymbolRole::RelationIBTypeOf, Parent); } } - + bool shouldWalkTypesOfTypeLocs() const { return false; } #define TRY_TO(CALL_EXPR) \ @@ -193,7 +193,7 @@ void IndexingContext::indexTypeSourceInfo(TypeSourceInfo *TInfo, bool isIBType) { if (!TInfo || TInfo->getTypeLoc().isNull()) return; - + indexTypeLoc(TInfo->getTypeLoc(), Parent, DC, isBase, isIBType); } diff --git a/lib/Index/IndexingContext.cpp b/lib/Index/IndexingContext.cpp index 80d851b43d73..333f9dc3091b 100644 --- a/lib/Index/IndexingContext.cpp +++ b/lib/Index/IndexingContext.cpp @@ -75,7 +75,7 @@ bool IndexingContext::handleReference(const NamedDecl *D, SourceLocation Loc, if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D)) return true; - + return handleDeclOccurrence(D, Loc, /*IsRef=*/true, Parent, Roles, Relations, RefE, RefD, DC); } diff --git a/lib/Index/USRGeneration.cpp b/lib/Index/USRGeneration.cpp index e69fa749b45f..b128b69931a3 100644 --- a/lib/Index/USRGeneration.cpp +++ b/lib/Index/USRGeneration.cpp @@ -62,9 +62,9 @@ class USRGenerator : public ConstDeclVisitor<USRGenerator> { bool IgnoreResults; ASTContext *Context; bool generatedLoc; - + llvm::DenseMap<const Type *, unsigned> TypeSubstitutions; - + public: explicit USRGenerator(ASTContext *Ctx, SmallVectorImpl<char> &Buf) : Buf(Buf), @@ -159,7 +159,7 @@ public: void VisitTemplateParameterList(const TemplateParameterList *Params); void VisitTemplateName(TemplateName Name); void VisitTemplateArgument(const TemplateArgument &Arg); - + /// Emit a Decl's name using NamedDecl::printName() and return true if /// the decl had no name. bool EmitDeclName(const NamedDecl *D); @@ -366,7 +366,7 @@ void USRGenerator::VisitClassTemplateDecl(const ClassTemplateDecl *D) { void USRGenerator::VisitNamespaceAliasDecl(const NamespaceAliasDecl *D) { VisitDeclContext(D->getDeclContext()); if (!IgnoreResults) - Out << "@NA@" << D->getName(); + Out << "@NA@" << D->getName(); } void USRGenerator::VisitObjCMethodDecl(const ObjCMethodDecl *D) { @@ -493,7 +493,7 @@ void USRGenerator::VisitTagDecl(const TagDecl *D) { if (const CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(D)) { if (ClassTemplateDecl *ClassTmpl = CXXRecord->getDescribedClassTemplate()) { AlreadyStarted = true; - + switch (D->getTagKind()) { case TTK_Interface: case TTK_Class: @@ -505,18 +505,18 @@ void USRGenerator::VisitTagDecl(const TagDecl *D) { } else if (const ClassTemplatePartialSpecializationDecl *PartialSpec = dyn_cast<ClassTemplatePartialSpecializationDecl>(CXXRecord)) { AlreadyStarted = true; - + switch (D->getTagKind()) { case TTK_Interface: case TTK_Class: case TTK_Struct: Out << "@SP"; break; case TTK_Union: Out << "@UP"; break; case TTK_Enum: llvm_unreachable("enum partial specialization"); - } + } VisitTemplateParameterList(PartialSpec->getTemplateParameters()); } } - + if (!AlreadyStarted) { switch (D->getTagKind()) { case TTK_Interface: @@ -526,7 +526,7 @@ void USRGenerator::VisitTagDecl(const TagDecl *D) { case TTK_Enum: Out << "@E"; break; } } - + Out << '@'; assert(Buf.size() > 0); const unsigned off = Buf.size() - 1; @@ -551,7 +551,7 @@ void USRGenerator::VisitTagDecl(const TagDecl *D) { } } } - + // For a class template specialization, mangle the template arguments. if (const ClassTemplateSpecializationDecl *Spec = dyn_cast<ClassTemplateSpecializationDecl>(D)) { @@ -640,7 +640,7 @@ void USRGenerator::VisitType(QualType T) { Out << 'P'; T = Expansion->getPattern(); } - + if (const BuiltinType *BT = T->getAs<BuiltinType>()) { unsigned char c = '\0'; switch (BT->getKind()) { @@ -758,7 +758,7 @@ void USRGenerator::VisitType(QualType T) { unsigned Number = TypeSubstitutions.size(); TypeSubstitutions[T.getTypePtr()] = Number; } - + if (const PointerType *PT = T->getAs<PointerType>()) { Out << '*'; T = PT->getPointeeType(); @@ -889,7 +889,7 @@ void USRGenerator::VisitTemplateParameterList( Out << 'T'; continue; } - + if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) { if (NTTP->isParameterPack()) Out << 'p'; @@ -897,7 +897,7 @@ void USRGenerator::VisitTemplateParameterList( VisitType(NTTP->getType()); continue; } - + TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P); if (TTP->isParameterPack()) Out << 'p'; @@ -913,11 +913,11 @@ void USRGenerator::VisitTemplateName(TemplateName Name) { Out << 't' << TTP->getDepth() << '.' << TTP->getIndex(); return; } - + Visit(Template); return; } - + // FIXME: Visit dependent template names. } @@ -939,21 +939,21 @@ void USRGenerator::VisitTemplateArgument(const TemplateArgument &Arg) { case TemplateArgument::Template: VisitTemplateName(Arg.getAsTemplateOrTemplatePattern()); break; - + case TemplateArgument::Expression: // FIXME: Visit expressions. break; - + case TemplateArgument::Pack: Out << 'p' << Arg.pack_size(); for (const auto &P : Arg.pack_elements()) VisitTemplateArgument(P); break; - + case TemplateArgument::Type: VisitType(Arg.getAsType()); break; - + case TemplateArgument::Integral: Out << 'V'; VisitType(Arg.getIntegralType()); diff --git a/lib/Lex/HeaderSearch.cpp b/lib/Lex/HeaderSearch.cpp index b1a2ef121288..fbfa54b2fffd 100644 --- a/lib/Lex/HeaderSearch.cpp +++ b/lib/Lex/HeaderSearch.cpp @@ -246,9 +246,9 @@ Module *HeaderSearch::lookupModule(StringRef ModuleName, StringRef SearchName, break; } } - + // FIXME: Figure out how header maps and module maps will work together. - + // Only deal with normal search directories. if (!SearchDirs[Idx].isNormalDir()) continue; @@ -263,7 +263,7 @@ Module *HeaderSearch::lookupModule(StringRef ModuleName, StringRef SearchName, if (Module) break; } - + // Search for a module map in a subdirectory with the same name as the // module. SmallString<128> NestedModuleMapDirName; @@ -530,7 +530,7 @@ const FileEntry *DirectoryLookup::DoFrameworkLookup( RelativePath->clear(); RelativePath->append(Filename.begin()+SlashPos+1, Filename.end()); } - + // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h" unsigned OrigSize = FrameworkName.size(); @@ -709,7 +709,7 @@ const FileEntry *HeaderSearch::LookupFile( if (SuggestedModule) *SuggestedModule = ModuleMap::KnownHeader(); - + // If 'Filename' is absolute, check to see if it exists and no searching. if (llvm::sys::path::is_absolute(Filename)) { CurDir = nullptr; @@ -898,7 +898,7 @@ const FileEntry *HeaderSearch::LookupFile( size_t SlashPos = Filename.find('/'); if (SlashPos != StringRef::npos) { HFI.IndexHeaderMapHeader = 1; - HFI.Framework = getUniqueFrameworkName(StringRef(Filename.begin(), + HFI.Framework = getUniqueFrameworkName(StringRef(Filename.begin(), SlashPos)); } } @@ -1079,7 +1079,7 @@ LookupSubframeworkHeader(StringRef Filename, /// Merge the header file info provided by \p OtherHFI into the current /// header file info (\p HFI) -static void mergeHeaderFileInfo(HeaderFileInfo &HFI, +static void mergeHeaderFileInfo(HeaderFileInfo &HFI, const HeaderFileInfo &OtherHFI) { assert(OtherHFI.External && "expected to merge external HFI"); @@ -1101,7 +1101,7 @@ static void mergeHeaderFileInfo(HeaderFileInfo &HFI, if (HFI.Framework.empty()) HFI.Framework = OtherHFI.Framework; } - + /// getFileInfo - Return the HeaderFileInfo structure for the specified /// FileEntry. HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) { @@ -1285,14 +1285,14 @@ StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) { return FrameworkNames.insert(Framework).first->first(); } -bool HeaderSearch::hasModuleMap(StringRef FileName, +bool HeaderSearch::hasModuleMap(StringRef FileName, const DirectoryEntry *Root, bool IsSystem) { if (!HSOpts->ImplicitModuleMaps) return false; SmallVector<const DirectoryEntry *, 2> FixUpDirectories; - + StringRef DirName = FileName; do { // Get the parent directory name. @@ -1325,7 +1325,7 @@ bool HeaderSearch::hasModuleMap(StringRef FileName, // If we hit the top of our search, we're done. if (Dir == Root) return false; - + // Keep track of all of the directories we checked, so we can mark them as // having module maps if we eventually do find a module map. FixUpDirectories.push_back(Dir); @@ -1385,7 +1385,7 @@ bool HeaderSearch::findUsableModuleForFrameworkHeader( SmallVector<std::string, 4> SubmodulePath; const DirectoryEntry *TopFrameworkDir = ::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath); - + // Determine the name of the top-level framework. StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName()); @@ -1532,16 +1532,16 @@ Module *HeaderSearch::loadFrameworkModule(StringRef Name, return ModMap.findModule(Name); } -HeaderSearch::LoadModuleMapResult +HeaderSearch::LoadModuleMapResult HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem, bool IsFramework) { if (const DirectoryEntry *Dir = FileMgr.getDirectory(DirName)) return loadModuleMapFile(Dir, IsSystem, IsFramework); - + return LMM_NoDirectory; } -HeaderSearch::LoadModuleMapResult +HeaderSearch::LoadModuleMapResult HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir, bool IsSystem, bool IsFramework) { auto KnownDir = DirectoryHasModuleMap.find(Dir); @@ -1610,7 +1610,7 @@ void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) { } // Populate the list of modules. - for (ModuleMap::module_iterator M = ModMap.module_begin(), + for (ModuleMap::module_iterator M = ModMap.module_begin(), MEnd = ModMap.module_end(); M != MEnd; ++M) { Modules.push_back(M->getValue()); diff --git a/lib/Lex/LiteralSupport.cpp b/lib/Lex/LiteralSupport.cpp index 966dafca2719..3f2af1a74e5a 100644 --- a/lib/Lex/LiteralSupport.cpp +++ b/lib/Lex/LiteralSupport.cpp @@ -30,7 +30,7 @@ #include <algorithm> #include <cassert> #include <cstddef> -#include <cstdint> +#include <cstdint> #include <cstring> #include <string> @@ -274,7 +274,7 @@ void clang::expandUCNs(SmallVectorImpl<char> &Buf, StringRef Input) { static bool ProcessUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf, const char *ThisTokEnd, uint32_t &UcnVal, unsigned short &UcnLen, - FullSourceLoc Loc, DiagnosticsEngine *Diags, + FullSourceLoc Loc, DiagnosticsEngine *Diags, const LangOptions &Features, bool in_char_string_literal = false) { const char *UcnBegin = ThisTokBuf; @@ -1539,7 +1539,7 @@ void StringLiteralParser::init(ArrayRef<Token> StringToks){ // that ThisTokBuf points to a buffer that is big enough for the whole token // and 'spelled' tokens can only shrink. bool StringInvalid = false; - unsigned ThisTokLen = + unsigned ThisTokLen = Lexer::getSpelling(StringToks[i], ThisTokBuf, SM, Features, &StringInvalid); if (StringInvalid) diff --git a/lib/Lex/MacroArgs.cpp b/lib/Lex/MacroArgs.cpp index 3b6e2dc2411a..dc2ba3074a8b 100644 --- a/lib/Lex/MacroArgs.cpp +++ b/lib/Lex/MacroArgs.cpp @@ -29,7 +29,7 @@ MacroArgs *MacroArgs::create(const MacroInfo *MI, "Can't have args for an object-like macro!"); MacroArgs **ResultEnt = nullptr; unsigned ClosestMatch = ~0U; - + // See if we have an entry with a big enough argument list to reuse on the // free list. If so, reuse it. for (MacroArgs **Entry = &PP.MacroArgCache; *Entry; @@ -37,7 +37,7 @@ MacroArgs *MacroArgs::create(const MacroInfo *MI, if ((*Entry)->NumUnexpArgTokens >= UnexpArgTokens.size() && (*Entry)->NumUnexpArgTokens < ClosestMatch) { ResultEnt = Entry; - + // If we have an exact match, use it. if ((*Entry)->NumUnexpArgTokens == UnexpArgTokens.size()) break; @@ -83,7 +83,7 @@ void MacroArgs::destroy(Preprocessor &PP) { // would deallocate the element vectors. for (unsigned i = 0, e = PreExpArgTokens.size(); i != e; ++i) PreExpArgTokens[i].clear(); - + // Add this to the preprocessor's free list. ArgCache = PP.MacroArgCache; PP.MacroArgCache = this; @@ -93,14 +93,14 @@ void MacroArgs::destroy(Preprocessor &PP) { /// its freelist. MacroArgs *MacroArgs::deallocate() { MacroArgs *Next = ArgCache; - + // Run the dtor to deallocate the vectors. this->~MacroArgs(); // Release the memory for the object. static_assert(std::is_trivially_destructible<Token>::value, "assume trivially destructible and forego destructors"); free(this); - + return Next; } @@ -125,7 +125,7 @@ const Token *MacroArgs::getUnexpArgument(unsigned Arg) const { // in memory. const Token *Start = getTrailingObjects<Token>(); const Token *Result = Start; - + // Scan to find Arg. for (; Arg; ++Result) { assert(Result < Start+NumUnexpArgTokens && "Invalid arg #"); @@ -171,7 +171,7 @@ const std::vector<Token> &MacroArgs::getPreExpArgument(unsigned Arg, // If we have already computed this, return it. if (PreExpArgTokens.size() < getNumMacroArguments()) PreExpArgTokens.resize(getNumMacroArguments()); - + std::vector<Token> &Result = PreExpArgTokens[Arg]; if (!Result.empty()) return Result; diff --git a/lib/Lex/ModuleMap.cpp b/lib/Lex/ModuleMap.cpp index f048a73a8ccc..87749f74734c 100644 --- a/lib/Lex/ModuleMap.cpp +++ b/lib/Lex/ModuleMap.cpp @@ -103,8 +103,8 @@ ModuleMap::headerKindToRole(Module::HeaderKind Kind) { llvm_unreachable("unknown header kind"); } -Module::ExportDecl -ModuleMap::resolveExport(Module *Mod, +Module::ExportDecl +ModuleMap::resolveExport(Module *Mod, const Module::UnresolvedExportDecl &Unresolved, bool Complain) const { // We may have just a wildcard. @@ -112,7 +112,7 @@ ModuleMap::resolveExport(Module *Mod, assert(Unresolved.Wildcard && "Invalid unresolved export"); return Module::ExportDecl(nullptr, true); } - + // Resolve the module-id. Module *Context = resolveModuleId(Unresolved.Id, Mod, Complain); if (!Context) @@ -151,7 +151,7 @@ Module *ModuleMap::resolveModuleId(const ModuleId &Id, Module *Mod, return Context; } -/// Append to \p Paths the set of paths needed to get to the +/// Append to \p Paths the set of paths needed to get to the /// subframework in which the given module lives. static void appendSubframeworkPaths(Module *Mod, SmallVectorImpl<char> &Path) { @@ -161,10 +161,10 @@ static void appendSubframeworkPaths(Module *Mod, if (Mod->IsFramework) Paths.push_back(Mod->Name); } - + if (Paths.empty()) return; - + // Add Frameworks/Name.framework for each subframework. for (unsigned I = Paths.size() - 1; I != 0; --I) llvm::sys::path::append(Path, "Frameworks", Paths[I-1] + ".framework"); @@ -325,7 +325,7 @@ ModuleMap::~ModuleMap() { } void ModuleMap::setTarget(const TargetInfo &Target) { - assert((!this->Target || this->Target == &Target) && + assert((!this->Target || this->Target == &Target) && "Improper target override"); this->Target = &Target; } @@ -528,7 +528,7 @@ void ModuleMap::diagnoseHeaderInclusion(Module *RequestingModule, << RequestingModule->getTopLevelModule()->Name << Filename; } else if (RequestingModule && RequestingModuleIsModuleInterface && LangOpts.isCompilingModule()) { - // Do not diagnose when we are not compiling a module. + // Do not diagnose when we are not compiling a module. diag::kind DiagID = RequestingModule->getTopLevelModule()->IsFramework ? diag::warn_non_modular_include_in_framework_module : diag::warn_non_modular_include_in_module; @@ -732,7 +732,7 @@ ModuleMap::isHeaderUnavailableInModule(const FileEntry *Header, if (IsUnavailable(Found)) return true; } - + // Infer a submodule with the same name as this header file. SmallString<32> NameBuf; StringRef Name = sanitizeFilenameAsIdentifier( @@ -745,18 +745,18 @@ ModuleMap::isHeaderUnavailableInModule(const FileEntry *Header, return IsUnavailable(Found); } - + SkippedDirs.push_back(Dir); - + // Retrieve our parent path. DirName = llvm::sys::path::parent_path(DirName); if (DirName.empty()) break; - + // Resolve the parent path to a directory entry. Dir = SourceMgr.getFileManager().getDirectory(DirName); } while (Dir); - + return false; } @@ -774,14 +774,14 @@ Module *ModuleMap::lookupModuleUnqualified(StringRef Name, if (Module *Sub = lookupModuleQualified(Name, Context)) return Sub; } - + return findModule(Name); } Module *ModuleMap::lookupModuleQualified(StringRef Name, Module *Context) const{ if (!Context) return findModule(Name); - + return Context->findSubmodule(Name); } @@ -892,7 +892,7 @@ Module *ModuleMap::inferFrameworkModule(const DirectoryEntry *FrameworkDir, // Check whether we've already found this module. if (Module *Mod = lookupModuleQualified(ModuleName, Parent)) return Mod; - + FileManager &FileMgr = SourceMgr.getFileManager(); // If the framework has a parent path from which we're allowed to infer @@ -953,7 +953,7 @@ Module *ModuleMap::inferFrameworkModule(const DirectoryEntry *FrameworkDir, SmallString<128> UmbrellaName = StringRef(FrameworkDir->getName()); llvm::sys::path::append(UmbrellaName, "Headers", ModuleName + ".h"); const FileEntry *UmbrellaHeader = FileMgr.getFile(UmbrellaName); - + // FIXME: If there's no umbrella header, we could probably scan the // framework to load *everything*. But, it's not clear that this is a good // idea. @@ -983,14 +983,14 @@ Module *ModuleMap::inferFrameworkModule(const DirectoryEntry *FrameworkDir, // The "Headers/" component of the name is implied because this is // a framework module. setUmbrellaHeader(Result, UmbrellaHeader, ModuleName + ".h"); - + // export * Result->Exports.push_back(Module::ExportDecl(nullptr, true)); // module * { export * } Result->InferSubmodules = true; Result->InferExportWildcard = true; - + // Look for subframeworks. std::error_code EC; SmallString<128> SubframeworksDirName @@ -1200,11 +1200,11 @@ void ModuleMap::setInferredModuleAllowedBy(Module *M, const FileEntry *ModMap) { LLVM_DUMP_METHOD void ModuleMap::dump() { llvm::errs() << "Modules:"; - for (llvm::StringMap<Module *>::iterator M = Modules.begin(), - MEnd = Modules.end(); + for (llvm::StringMap<Module *>::iterator M = Modules.begin(), + MEnd = Modules.end(); M != MEnd; ++M) M->getValue()->print(llvm::errs(), 2); - + llvm::errs() << "Headers:"; for (HeadersMap::iterator H = Headers.begin(), HEnd = Headers.end(); H != HEnd; ++H) { @@ -1299,7 +1299,7 @@ namespace clang { LSquare, RSquare } Kind; - + unsigned Location; unsigned StringLength; union { @@ -1309,16 +1309,16 @@ namespace clang { // If Kind == IntegerLiteral. uint64_t IntegerValue; }; - + void clear() { Kind = EndOfFile; Location = 0; StringLength = 0; StringData = nullptr; } - + bool is(TokenKind K) const { return Kind == K; } - + SourceLocation getLocation() const { return SourceLocation::getFromRawEncoding(Location); } @@ -1326,7 +1326,7 @@ namespace clang { uint64_t getInteger() const { return Kind == IntegerLiteral ? IntegerValue : 0; } - + StringRef getString() const { return Kind == IntegerLiteral ? StringRef() : StringRef(StringData, StringLength); @@ -1356,17 +1356,17 @@ namespace clang { /// Whether this module map is in a system header directory. bool IsSystem; - + /// Whether an error occurred. bool HadError = false; - + /// Stores string data for the various string literals referenced /// during parsing. llvm::BumpPtrAllocator StringData; - + /// The current token. MMToken Tok; - + /// The active module. Module *ActiveModule = nullptr; @@ -1413,7 +1413,7 @@ namespace clang { using Attributes = ModuleMap::Attributes; bool parseOptionalAttributes(Attributes &Attrs); - + public: explicit ModuleMapParser(Lexer &L, SourceManager &SourceMgr, const TargetInfo *Target, DiagnosticsEngine &Diags, @@ -1475,7 +1475,7 @@ retry: case tok::eof: Tok.Kind = MMToken::EndOfFile; break; - + case tok::l_brace: Tok.Kind = MMToken::LBrace; break; @@ -1483,27 +1483,27 @@ retry: case tok::l_square: Tok.Kind = MMToken::LSquare; break; - + case tok::period: Tok.Kind = MMToken::Period; break; - + case tok::r_brace: Tok.Kind = MMToken::RBrace; break; - + case tok::r_square: Tok.Kind = MMToken::RSquare; break; - + case tok::star: Tok.Kind = MMToken::Star; break; - + case tok::exclaim: Tok.Kind = MMToken::Exclaim; break; - + case tok::string_literal: { if (LToken.hasUDSuffix()) { Diags.Report(LToken.getLocation(), diag::err_invalid_string_udl); @@ -1516,13 +1516,13 @@ retry: StringLiteralParser StringLiteral(LToken, SourceMgr, LangOpts, *Target); if (StringLiteral.hadError) goto retry; - + // Copy the string literal into our string data allocator. unsigned Length = StringLiteral.GetStringLength(); char *Saved = StringData.Allocate<char>(Length + 1); memcpy(Saved, StringLiteral.GetString().data(), Length); Saved[Length] = 0; - + // Form the token. Tok.Kind = MMToken::StringLiteral; Tok.StringData = Saved; @@ -1548,7 +1548,7 @@ retry: Tok.IntegerValue = Value; break; } - + case tok::comment: goto retry; @@ -1576,7 +1576,7 @@ retry: HadError = true; goto retry; } - + return Result; } @@ -1591,14 +1591,14 @@ void ModuleMapParser::skipUntil(MMToken::TokenKind K) { case MMToken::LBrace: if (Tok.is(K) && braceDepth == 0 && squareDepth == 0) return; - + ++braceDepth; break; case MMToken::LSquare: if (Tok.is(K) && braceDepth == 0 && squareDepth == 0) return; - + ++squareDepth; break; @@ -1621,7 +1621,7 @@ void ModuleMapParser::skipUntil(MMToken::TokenKind K) { return; break; } - + consumeToken(); } while (true); } @@ -1643,13 +1643,13 @@ bool ModuleMapParser::parseModuleId(ModuleId &Id) { Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module_name); return true; } - + if (!Tok.is(MMToken::Period)) break; - + consumeToken(); } while (true); - + return false; } @@ -1740,7 +1740,7 @@ void ModuleMapParser::diagnosePrivateModules(SourceLocation ExplicitLoc, /// /// module-declaration: /// 'extern' 'module' module-id string-literal -/// 'explicit'[opt] 'framework'[opt] 'module' module-id attributes[opt] +/// 'explicit'[opt] 'framework'[opt] 'module' module-id attributes[opt] /// { module-member* } /// /// module-member: @@ -1778,8 +1778,8 @@ void ModuleMapParser::parseModuleDecl() { if (Tok.is(MMToken::FrameworkKeyword)) { FrameworkLoc = consumeToken(); Framework = true; - } - + } + // Parse 'module' keyword. if (!Tok.is(MMToken::ModuleKeyword)) { Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module); @@ -1790,10 +1790,10 @@ void ModuleMapParser::parseModuleDecl() { CurrModuleDeclLoc = consumeToken(); // 'module' keyword // If we have a wildcard for the module name, this is an inferred submodule. - // Parse it. + // Parse it. if (Tok.is(MMToken::Star)) return parseInferredModuleDecl(Framework, Explicit); - + // Parse the module name. ModuleId Id; if (parseModuleId(Id)) { @@ -1805,7 +1805,7 @@ void ModuleMapParser::parseModuleDecl() { if (Id.size() > 1) { Diags.Report(Id.front().second, diag::err_mmap_nested_submodule_id) << SourceRange(Id.front().second, Id.back().second); - + HadError = true; return; } @@ -1816,8 +1816,8 @@ void ModuleMapParser::parseModuleDecl() { ExplicitLoc = SourceLocation(); HadError = true; } - - Module *PreviousActiveModule = ActiveModule; + + Module *PreviousActiveModule = ActiveModule; if (Id.size() > 1) { // This module map defines a submodule. Go find the module of which it // is a submodule. @@ -1830,7 +1830,7 @@ void ModuleMapParser::parseModuleDecl() { ActiveModule = Next; continue; } - + if (ActiveModule) { Diags.Report(Id[I].second, diag::err_mmap_missing_module_qualified) << Id[I].first @@ -1849,10 +1849,10 @@ void ModuleMapParser::parseModuleDecl() { Map.addAdditionalModuleMapFile(TopLevelModule, ModuleMapFile); } } - + StringRef ModuleName = Id.back().first; SourceLocation ModuleNameLoc = Id.back().second; - + // Parse the optional attribute list. Attributes Attrs; if (parseOptionalAttributes(Attrs)) @@ -1864,9 +1864,9 @@ void ModuleMapParser::parseModuleDecl() { << ModuleName; HadError = true; return; - } + } SourceLocation LBraceLoc = consumeToken(); - + // Determine whether this (sub)module has already been defined. Module *ShadowingModule = nullptr; if (Module *Existing = Map.lookupModuleQualified(ModuleName, ActiveModule)) { @@ -1890,7 +1890,7 @@ void ModuleMapParser::parseModuleDecl() { else { Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace); Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match); - HadError = true; + HadError = true; } return; } @@ -1986,7 +1986,7 @@ void ModuleMapParser::parseModuleDecl() { case MMToken::UseKeyword: parseUseDecl(); break; - + case MMToken::RequiresKeyword: parseRequiresDecl(); break; @@ -2023,7 +2023,7 @@ void ModuleMapParser::parseModuleDecl() { default: Diags.Report(Tok.getLocation(), diag::err_mmap_expected_member); consumeToken(); - break; + break; } } while (!Done); @@ -2233,7 +2233,7 @@ void ModuleMapParser::parseHeaderDecl(MMToken::TokenKind LeadingToken, // Parse the header name. if (!Tok.is(MMToken::StringLiteral)) { - Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header) + Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header) << "header"; HadError = true; return; @@ -2330,7 +2330,7 @@ static int compareModuleHeaders(const Module::Header *A, void ModuleMapParser::parseUmbrellaDirDecl(SourceLocation UmbrellaLoc) { // Parse the directory name. if (!Tok.is(MMToken::StringLiteral)) { - Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header) + Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header) << "umbrella"; HadError = true; return; @@ -2338,7 +2338,7 @@ void ModuleMapParser::parseUmbrellaDirDecl(SourceLocation UmbrellaLoc) { std::string DirName = Tok.getString(); SourceLocation DirNameLoc = consumeToken(); - + // Check whether we already have an umbrella. if (ActiveModule->Umbrella) { Diags.Report(DirNameLoc, diag::err_mmap_umbrella_clash) @@ -2357,7 +2357,7 @@ void ModuleMapParser::parseUmbrellaDirDecl(SourceLocation UmbrellaLoc) { llvm::sys::path::append(PathName, DirName); Dir = SourceMgr.getFileManager().getDirectory(PathName); } - + if (!Dir) { Diags.Report(DirNameLoc, diag::warn_mmap_umbrella_dir_not_found) << DirName; @@ -2413,38 +2413,38 @@ void ModuleMapParser::parseUmbrellaDirDecl(SourceLocation UmbrellaLoc) { void ModuleMapParser::parseExportDecl() { assert(Tok.is(MMToken::ExportKeyword)); SourceLocation ExportLoc = consumeToken(); - + // Parse the module-id with an optional wildcard at the end. ModuleId ParsedModuleId; bool Wildcard = false; do { // FIXME: Support string-literal module names here. if (Tok.is(MMToken::Identifier)) { - ParsedModuleId.push_back(std::make_pair(Tok.getString(), + ParsedModuleId.push_back(std::make_pair(Tok.getString(), Tok.getLocation())); consumeToken(); - + if (Tok.is(MMToken::Period)) { consumeToken(); continue; - } - + } + break; } - + if(Tok.is(MMToken::Star)) { Wildcard = true; consumeToken(); break; } - + Diags.Report(Tok.getLocation(), diag::err_mmap_module_id); HadError = true; return; } while (true); - - Module::UnresolvedExportDecl Unresolved = { - ExportLoc, ParsedModuleId, Wildcard + + Module::UnresolvedExportDecl Unresolved = { + ExportLoc, ParsedModuleId, Wildcard }; ActiveModule->UnresolvedExports.push_back(Unresolved); } @@ -2468,7 +2468,7 @@ void ModuleMapParser::parseExportAsDecl() { consumeToken(); return; } - + if (!ActiveModule->ExportAsModule.empty()) { if (ActiveModule->ExportAsModule == Tok.getString()) { Diags.Report(Tok.getLocation(), diag::warn_mmap_redundant_export_as) @@ -2479,7 +2479,7 @@ void ModuleMapParser::parseExportAsDecl() { << Tok.getString(); } } - + ActiveModule->ExportAsModule = Tok.getString(); Map.addLinkAsDependency(ActiveModule); @@ -2666,7 +2666,7 @@ void ModuleMapParser::parseInferredModuleDecl(bool Framework, bool Explicit) { Diags.Report(StarLoc, diag::err_mmap_inferred_no_umbrella); Failed = true; } - + // Check for redefinition of an inferred module. if (!Failed && ActiveModule->InferSubmodules) { Diags.Report(StarLoc, diag::err_mmap_inferred_redef); @@ -2721,7 +2721,7 @@ void ModuleMapParser::parseInferredModuleDecl(bool Framework, bool Explicit) { Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace_wildcard); HadError = true; return; - } + } SourceLocation LBraceLoc = consumeToken(); // Parse the body of the inferred submodule. @@ -2762,10 +2762,10 @@ void ModuleMapParser::parseInferredModuleDecl(bool Framework, bool Explicit) { } consumeToken(); - if (Tok.is(MMToken::Star)) + if (Tok.is(MMToken::Star)) ActiveModule->InferExportWildcard = true; else - Diags.Report(Tok.getLocation(), + Diags.Report(Tok.getLocation(), diag::err_mmap_expected_export_wildcard); consumeToken(); break; @@ -2779,10 +2779,10 @@ void ModuleMapParser::parseInferredModuleDecl(bool Framework, bool Explicit) { Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member) << (ActiveModule != nullptr); consumeToken(); - break; + break; } } while (!Done); - + if (Tok.is(MMToken::RBrace)) consumeToken(); else { @@ -2806,7 +2806,7 @@ void ModuleMapParser::parseInferredModuleDecl(bool Framework, bool Explicit) { /// \returns true if an error occurred, false otherwise. bool ModuleMapParser::parseOptionalAttributes(Attributes &Attrs) { bool HadError = false; - + while (Tok.is(MMToken::LSquare)) { // Consume the '['. SourceLocation LSquareLoc = consumeToken(); @@ -2876,7 +2876,7 @@ bool ModuleMapParser::parseModuleMapFile() { switch (Tok.Kind) { case MMToken::EndOfFile: return HadError; - + case MMToken::ExplicitKeyword: case MMToken::ExternKeyword: case MMToken::ModuleKeyword: diff --git a/lib/Lex/PPDirectives.cpp b/lib/Lex/PPDirectives.cpp index d8dae73037a8..66a9faa6e60a 100644 --- a/lib/Lex/PPDirectives.cpp +++ b/lib/Lex/PPDirectives.cpp @@ -2597,13 +2597,13 @@ void Preprocessor::HandleDefineDirective( MacroInfo *const MI = ReadOptionalMacroParameterListAndBody( MacroNameTok, ImmediatelyAfterHeaderGuard); - + if (!MI) return; if (MacroShadowsKeyword && !isConfigurationPattern(MacroNameTok, MI, getLangOpts())) { Diag(MacroNameTok, diag::warn_pp_macro_hides_keyword); - } + } // Check that there is no paste (##) operator at the beginning or end of the // replacement list. unsigned NumTokens = MI->getNumTokens(); @@ -2716,7 +2716,7 @@ void Preprocessor::HandleUndefDirective() { auto *II = MacroNameTok.getIdentifierInfo(); auto MD = getMacroDefinition(II); UndefMacroDirective *Undef = nullptr; - + // If the macro is not defined, this is a noop undef. if (const MacroInfo *MI = MD.getMacroInfo()) { if (!MI->isUsed() && MI->isWarnIfUnused()) diff --git a/lib/Lex/PPExpressions.cpp b/lib/Lex/PPExpressions.cpp index b1ed0e10c6fc..ac01efad9bf6 100644 --- a/lib/Lex/PPExpressions.cpp +++ b/lib/Lex/PPExpressions.cpp @@ -273,7 +273,7 @@ static bool EvaluateValue(PPValue &Result, Token &PeekTok, DefinedTracker &DT, case tok::numeric_constant: { SmallString<64> IntegerBuffer; bool NumberInvalid = false; - StringRef Spelling = PP.getSpelling(PeekTok, IntegerBuffer, + StringRef Spelling = PP.getSpelling(PeekTok, IntegerBuffer, &NumberInvalid); if (NumberInvalid) return true; // a diagnostic was already reported @@ -832,11 +832,11 @@ Preprocessor::EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro) { // expression. bool DisableMacroExpansionAtStartOfDirective = DisableMacroExpansion; DisableMacroExpansion = false; - + // Peek ahead one token. Token Tok; LexNonComment(Tok); - + // C99 6.10.1p3 - All expressions are evaluated as intmax_t or uintmax_t. unsigned BitWidth = getTargetInfo().getIntMaxTWidth(); @@ -846,7 +846,7 @@ Preprocessor::EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro) { // Parse error, skip the rest of the macro line. if (Tok.isNot(tok::eod)) DiscardUntilEndOfDirective(); - + // Restore 'DisableMacroExpansion'. DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective; return {false, DT.IncludedUndefinedIds}; @@ -873,7 +873,7 @@ Preprocessor::EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro) { // Parse error, skip the rest of the macro line. if (Tok.isNot(tok::eod)) DiscardUntilEndOfDirective(); - + // Restore 'DisableMacroExpansion'. DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective; return {false, DT.IncludedUndefinedIds}; diff --git a/lib/Lex/PPLexerChange.cpp b/lib/Lex/PPLexerChange.cpp index 352814d715fa..6631b13b1583 100644 --- a/lib/Lex/PPLexerChange.cpp +++ b/lib/Lex/PPLexerChange.cpp @@ -82,10 +82,10 @@ bool Preprocessor::EnterSourceFile(FileID FID, const DirectoryLookup *CurDir, return false; } } - + // Get the MemoryBuffer for this FID, if it fails, we fail. bool Invalid = false; - const llvm::MemoryBuffer *InputFile = + const llvm::MemoryBuffer *InputFile = getSourceManager().getBuffer(FID, Loc, &Invalid); if (Invalid) { SourceLocation FileStart = SourceMgr.getLocForStartOfFile(FID); @@ -145,7 +145,7 @@ void Preprocessor::EnterSourceFileWithPTH(PTHLexer *PL, CurLexerSubmodule = nullptr; if (CurLexerKind != CLK_LexAfterModuleImport) CurLexerKind = CLK_PTHLexer; - + // Notify the client, if desired, that we are in a new source file. if (Callbacks) { FileID FID = CurPPLexer->getFileID(); @@ -240,15 +240,15 @@ static void computeRelativePath(FileManager &FM, const DirectoryEntry *Dir, if (const DirectoryEntry *CurDir = FM.getDirectory(Path)) { if (CurDir == Dir) { Result = FilePath.substr(Path.size()); - llvm::sys::path::append(Result, + llvm::sys::path::append(Result, llvm::sys::path::filename(File->getName())); return; } } - + Path = llvm::sys::path::parent_path(Path); } - + Result = File->getName(); } @@ -553,7 +553,7 @@ bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) { CurPTHLexer->getEOF(Result); CurPTHLexer.reset(); } - + if (!isIncrementalProcessingEnabled()) CurPPLexer = nullptr; diff --git a/lib/Lex/PPMacroExpansion.cpp b/lib/Lex/PPMacroExpansion.cpp index d9992e00f8c0..346dd947c028 100644 --- a/lib/Lex/PPMacroExpansion.cpp +++ b/lib/Lex/PPMacroExpansion.cpp @@ -1186,7 +1186,7 @@ static bool EvaluateHasIncludeCommon(Token &Tok, SmallString<128> FilenameBuffer; StringRef Filename; SourceLocation EndLoc; - + switch (Tok.getKind()) { case tok::eod: // If the token kind is EOD, the error has already been diagnosed. @@ -1260,7 +1260,7 @@ static bool EvaluateHasIncludeNext(Token &Tok, // __has_include_next is like __has_include, except that we start // searching after the current found directory. If we can't do this, // issue a diagnostic. - // FIXME: Factor out duplication with + // FIXME: Factor out duplication with // Preprocessor::HandleIncludeNextDirective. const DirectoryLookup *Lookup = PP.GetCurDirLookup(); const FileEntry *LookupFromFile = nullptr; @@ -1510,7 +1510,7 @@ void Preprocessor::ExpandBuiltinMacro(Token &Tok) { PLoc = SourceMgr.getPresumedLoc(NextLoc); if (PLoc.isInvalid()) break; - + NextLoc = PLoc.getIncludeLoc(); } } diff --git a/lib/Lex/Pragma.cpp b/lib/Lex/Pragma.cpp index 930c5f6b069c..37c0a23646c5 100644 --- a/lib/Lex/Pragma.cpp +++ b/lib/Lex/Pragma.cpp @@ -64,7 +64,7 @@ PragmaHandler::~PragmaHandler() = default; EmptyPragmaHandler::EmptyPragmaHandler(StringRef Name) : PragmaHandler(Name) {} -void EmptyPragmaHandler::HandlePragma(Preprocessor &PP, +void EmptyPragmaHandler::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &FirstToken) {} @@ -99,7 +99,7 @@ void PragmaNamespace::RemovePragmaHandler(PragmaHandler *Handler) { Handlers.erase(Handler->getName()); } -void PragmaNamespace::HandlePragma(Preprocessor &PP, +void PragmaNamespace::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &Tok) { // Read the 'namespace' that the directive is in, e.g. STDC. Do not macro @@ -141,7 +141,7 @@ void Preprocessor::HandlePragmaDirective(SourceLocation IntroducerLoc, PragmaHandlers->HandlePragma(*this, Introducer, Tok); // If the pragma handler didn't read the rest of the line, consume it now. - if ((CurTokenLexer && CurTokenLexer->isParsingPreprocessorDirective()) + if ((CurTokenLexer && CurTokenLexer->isParsingPreprocessorDirective()) || (CurPPLexer && CurPPLexer->ParsingPreprocessorDirective)) DiscardUntilEndOfDirective(); } @@ -468,7 +468,7 @@ void Preprocessor::HandlePragmaSystemHeader(Token &SysHeaderTok) { PresumedLoc PLoc = SourceMgr.getPresumedLoc(SysHeaderTok.getLocation()); if (PLoc.isInvalid()) return; - + unsigned FilenameID = SourceMgr.getLineTableFilenameID(PLoc.getFilename()); // Notify the client, if desired, that we are in a new source file. @@ -601,7 +601,7 @@ void Preprocessor::HandlePragmaPushMacro(Token &PushMacroTok) { // Get the MacroInfo associated with IdentInfo. MacroInfo *MI = getMacroInfo(IdentInfo); - + if (MI) { // Allow the original MacroInfo to be redefined later. MI->setIsAllowRedefinitionsWithoutWarning(true); @@ -653,7 +653,7 @@ void Preprocessor::HandlePragmaPopMacro(Token &PopMacroTok) { } void Preprocessor::HandlePragmaIncludeAlias(Token &Tok) { - // We will either get a quoted filename or a bracketed filename, and we + // We will either get a quoted filename or a bracketed filename, and we // have to track which we got. The first filename is the source name, // and the second name is the mapped filename. If the first is quoted, // the second must be as well (cannot mix and match quotes and brackets). @@ -675,7 +675,7 @@ void Preprocessor::HandlePragmaIncludeAlias(Token &Tok) { StringRef SourceFileName; SmallString<128> FileNameBuffer; - if (SourceFilenameTok.is(tok::string_literal) || + if (SourceFilenameTok.is(tok::string_literal) || SourceFilenameTok.is(tok::angle_string_literal)) { SourceFileName = getSpelling(SourceFilenameTok, FileNameBuffer); } else if (SourceFilenameTok.is(tok::less)) { @@ -706,7 +706,7 @@ void Preprocessor::HandlePragmaIncludeAlias(Token &Tok) { } StringRef ReplaceFileName; - if (ReplaceFilenameTok.is(tok::string_literal) || + if (ReplaceFilenameTok.is(tok::string_literal) || ReplaceFilenameTok.is(tok::angle_string_literal)) { ReplaceFileName = getSpelling(ReplaceFilenameTok, FileNameBuffer); } else if (ReplaceFilenameTok.is(tok::less)) { @@ -732,8 +732,8 @@ void Preprocessor::HandlePragmaIncludeAlias(Token &Tok) { // they're both of the same type (angled vs non-angled) StringRef OriginalSource = SourceFileName; - bool SourceIsAngled = - GetIncludeFilenameSpelling(SourceFilenameTok.getLocation(), + bool SourceIsAngled = + GetIncludeFilenameSpelling(SourceFilenameTok.getLocation(), SourceFileName); bool ReplaceIsAngled = GetIncludeFilenameSpelling(ReplaceFilenameTok.getLocation(), @@ -747,7 +747,7 @@ void Preprocessor::HandlePragmaIncludeAlias(Token &Tok) { DiagID = diag::warn_pragma_include_alias_mismatch_quote; Diag(SourceFilenameTok.getLocation(), DiagID) - << SourceFileName + << SourceFileName << ReplaceFileName; return; @@ -1615,7 +1615,7 @@ struct PragmaPopMacroHandler : public PragmaHandler { } }; -/// PragmaARCCFCodeAuditedHandler - +/// PragmaARCCFCodeAuditedHandler - /// \#pragma clang arc_cf_code_audited begin/end struct PragmaARCCFCodeAuditedHandler : public PragmaHandler { PragmaARCCFCodeAuditedHandler() : PragmaHandler("arc_cf_code_audited") {} @@ -1790,7 +1790,7 @@ void Preprocessor::RegisterBuiltinPragmas() { ModuleHandler->AddPragma(new PragmaModuleEndHandler()); ModuleHandler->AddPragma(new PragmaModuleBuildHandler()); ModuleHandler->AddPragma(new PragmaModuleLoadHandler()); - + // Add region pragmas. AddPragmaHandler(new PragmaRegionHandler("region")); AddPragmaHandler(new PragmaRegionHandler("endregion")); diff --git a/lib/Lex/PreprocessingRecord.cpp b/lib/Lex/PreprocessingRecord.cpp index b59820003b56..b37a8cf1ced4 100644 --- a/lib/Lex/PreprocessingRecord.cpp +++ b/lib/Lex/PreprocessingRecord.cpp @@ -67,7 +67,7 @@ PreprocessingRecord::getPreprocessedEntitiesInRange(SourceRange Range) { } std::pair<int, int> Res = getPreprocessedEntitiesInRangeSlow(Range); - + CachedRangeQuery.Range = Range; CachedRangeQuery.Result = Res; @@ -138,28 +138,28 @@ std::pair<int, int> PreprocessingRecord::getPreprocessedEntitiesInRangeSlow(SourceRange Range) { assert(Range.isValid()); assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin())); - + std::pair<unsigned, unsigned> Local = findLocalPreprocessedEntitiesInRange(Range); - + // Check if range spans local entities. if (!ExternalSource || SourceMgr.isLocalSourceLocation(Range.getBegin())) return std::make_pair(Local.first, Local.second); - + std::pair<unsigned, unsigned> Loaded = ExternalSource->findPreprocessedEntitiesInRange(Range); - + // Check if range spans local entities. if (Loaded.first == Loaded.second) return std::make_pair(Local.first, Local.second); - + unsigned TotalLoaded = LoadedPreprocessedEntities.size(); - + // Check if range spans loaded entities. if (Local.first == Local.second) return std::make_pair(int(Loaded.first)-TotalLoaded, int(Loaded.second)-TotalLoaded); - + // Range spands loaded and local entities. return std::make_pair(int(Loaded.first)-TotalLoaded, Local.second); } @@ -324,7 +324,7 @@ void PreprocessingRecord::SetExternalSource( unsigned PreprocessingRecord::allocateLoadedEntities(unsigned NumEntities) { unsigned Result = LoadedPreprocessedEntities.size(); - LoadedPreprocessedEntities.resize(LoadedPreprocessedEntities.size() + LoadedPreprocessedEntities.resize(LoadedPreprocessedEntities.size() + NumEntities); return Result; } @@ -371,7 +371,7 @@ PreprocessedEntity *PreprocessingRecord::getPreprocessedEntity(PPEntityID PPID){ /// Retrieve the loaded preprocessed entity at the given index. PreprocessedEntity * PreprocessingRecord::getLoadedPreprocessedEntity(unsigned Index) { - assert(Index < LoadedPreprocessedEntities.size() && + assert(Index < LoadedPreprocessedEntities.size() && "Out-of bounds loaded preprocessed entity"); assert(ExternalSource && "No external source to load from"); PreprocessedEntity *&Entity = LoadedPreprocessedEntities[Index]; @@ -471,27 +471,27 @@ void PreprocessingRecord::InclusionDirective( const FileEntry *File, StringRef SearchPath, StringRef RelativePath, - const Module *Imported, + const Module *Imported, SrcMgr::CharacteristicKind FileType) { InclusionDirective::InclusionKind Kind = InclusionDirective::Include; - + switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) { - case tok::pp_include: - Kind = InclusionDirective::Include; + case tok::pp_include: + Kind = InclusionDirective::Include; break; - - case tok::pp_import: - Kind = InclusionDirective::Import; + + case tok::pp_import: + Kind = InclusionDirective::Import; break; - - case tok::pp_include_next: - Kind = InclusionDirective::IncludeNext; + + case tok::pp_include_next: + Kind = InclusionDirective::IncludeNext; break; - - case tok::pp___include_macros: + + case tok::pp___include_macros: Kind = InclusionDirective::IncludeMacros; break; - + default: llvm_unreachable("Unknown include directive kind"); } diff --git a/lib/Lex/Preprocessor.cpp b/lib/Lex/Preprocessor.cpp index 0217a2e60ede..def47b2f1095 100644 --- a/lib/Lex/Preprocessor.cpp +++ b/lib/Lex/Preprocessor.cpp @@ -95,12 +95,12 @@ Preprocessor::Preprocessor(std::shared_ptr<PreprocessorOptions> PPOpts, TUKind(TUKind), SkipMainFilePreamble(0, true), CurSubmoduleState(&NullSubmoduleState) { OwnsHeaderSearch = OwnsHeaders; - + // Default to discarding comments. KeepComments = false; KeepMacroComments = false; SuppressIncludeNotFoundError = false; - + // Macro expansion is enabled. DisableMacroExpansion = false; MacroExpansionInDirectivesOverride = false; @@ -127,10 +127,10 @@ Preprocessor::Preprocessor(std::shared_ptr<PreprocessorOptions> PPOpts, // Initialize the pragma handlers. RegisterBuiltinPragmas(); - + // Initialize builtin macros like __LINE__ and friends. RegisterBuiltinMacros(); - + if(LangOpts.Borland) { Ident__exception_info = getIdentifierInfo("_exception_info"); Ident___exception_info = getIdentifierInfo("__exception_info"); @@ -379,7 +379,7 @@ void Preprocessor::recomputeCurLexerKind() { CurLexerKind = CLK_PTHLexer; else if (CurTokenLexer) CurLexerKind = CLK_TokenLexer; - else + else CurLexerKind = CLK_CachingLexer; } @@ -772,7 +772,7 @@ bool Preprocessor::HandleIdentifier(Token &Identifier) { if (IsSpecialVariadicMacro) II.setIsPoisoned(CurrentIsPoisoned); } - + // If this identifier was poisoned, and if it was not produced from a macro // expansion, emit an error. if (II.isPoisoned() && CurPPLexer) { @@ -818,7 +818,7 @@ bool Preprocessor::HandleIdentifier(Token &Identifier) { // like "#define TY typeof", "TY(1) x". if (II.isExtensionToken() && !DisableMacroExpansion) Diag(Identifier, diag::ext_token_used); - + // If this is the 'import' contextual keyword following an '@', note // that the next token indicates a module name. // @@ -881,15 +881,15 @@ void Preprocessor::Lex(Token &Result) { void Preprocessor::LexAfterModuleImport(Token &Result) { // Figure out what kind of lexer we actually have. recomputeCurLexerKind(); - + // Lex the next token. Lex(Result); - // The token sequence + // The token sequence // // import identifier (. identifier)* // - // indicates a module import directive. We already saw the 'import' + // indicates a module import directive. We already saw the 'import' // contextual keyword, so now we're looking for the identifiers. if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) { // We expected to see an identifier here, and we did; continue handling @@ -900,7 +900,7 @@ void Preprocessor::LexAfterModuleImport(Token &Result) { CurLexerKind = CLK_LexAfterModuleImport; return; } - + // If we're expecting a '.' or a ';', and we got a '.', then wait until we // see the next identifier. (We can also see a '[[' that begins an // attribute-specifier-seq here under the C++ Modules TS.) @@ -1056,7 +1056,7 @@ CodeCompletionHandler::~CodeCompletionHandler() = default; void Preprocessor::createPreprocessingRecord() { if (Record) return; - + Record = new PreprocessingRecord(getSourceManager()); addPPCallbacks(std::unique_ptr<PPCallbacks>(Record)); } diff --git a/lib/Lex/TokenLexer.cpp b/lib/Lex/TokenLexer.cpp index 184b1b390287..608e0dedebb7 100644 --- a/lib/Lex/TokenLexer.cpp +++ b/lib/Lex/TokenLexer.cpp @@ -248,7 +248,7 @@ void TokenLexer::ExpandFunctionArguments() { ActualArgs->invokedWithVariadicArgument(Macro); VAOptExpansionContext VCtx(PP); - + for (unsigned I = 0, E = NumTokens; I != E; ++I) { const Token &CurTok = Tokens[I]; // We don't want a space for the next token after a paste @@ -268,7 +268,7 @@ void TokenLexer::ExpandFunctionArguments() { ++I; // Skip the l_paren VCtx.sawVAOptFollowedByOpeningParens(CurTok.getLocation(), ResultToks.size()); - + continue; } @@ -336,14 +336,14 @@ void TokenLexer::ExpandFunctionArguments() { } // If we found the stringify operator, get the argument stringified. The - // preprocessor already verified that the following token is a macro + // preprocessor already verified that the following token is a macro // parameter or __VA_OPT__ when the #define was lexed. - + if (CurTok.isOneOf(tok::hash, tok::hashat)) { int ArgNo = Macro->getParameterNum(Tokens[I+1].getIdentifierInfo()); assert((ArgNo != -1 || VCtx.isVAOptToken(Tokens[I + 1])) && "Token following # is not an argument or __VA_OPT__!"); - + if (ArgNo == -1) { // Handle the __VA_OPT__ case. VCtx.sawHashOrHashAtBefore(NextTokGetsSpace, @@ -706,7 +706,7 @@ bool TokenLexer::pasteTokens(Token &LHSTok, ArrayRef<Token> TokenStream, if (PP.getLangOpts().MicrosoftExt && (CurIdx >= 2) && TokenStream[CurIdx - 2].is(tok::hashhash)) LHSTok.clearFlag(Token::LeadingSpace); - + SmallString<128> Buffer; const char *ResultTokStrPtr = nullptr; SourceLocation StartLoc = LHSTok.getLocation(); @@ -845,7 +845,7 @@ bool TokenLexer::pasteTokens(Token &LHSTok, ArrayRef<Token> TokenStream, // Transfer properties of the LHS over the Result. Result.setFlagValue(Token::StartOfLine , LHSTok.isAtStartOfLine()); Result.setFlagValue(Token::LeadingSpace, LHSTok.hasLeadingSpace()); - + // Finally, replace LHS with the result, consume the RHS, and iterate. ++CurIdx; LHSTok = Result; @@ -868,7 +868,7 @@ bool TokenLexer::pasteTokens(Token &LHSTok, ArrayRef<Token> TokenStream, StartLoc = SM.getImmediateExpansionRange(StartLoc).getBegin(); while (SM.getFileID(EndLoc) != MacroFID) EndLoc = SM.getImmediateExpansionRange(EndLoc).getEnd(); - + LHSTok.setLocation(SM.createExpansionLoc(LHSTok.getLocation(), StartLoc, EndLoc, LHSTok.getLength())); @@ -927,7 +927,7 @@ TokenLexer::getExpansionLocForMacroDefLoc(SourceLocation loc) const { assert(ExpandLocStart.isValid() && MacroExpansionStart.isValid() && "Not appropriate for token streams"); assert(loc.isValid() && loc.isFileID()); - + SourceManager &SM = PP.getSourceManager(); assert(SM.isInSLocAddrSpace(loc, MacroDefStart, MacroDefLength) && "Expected loc to come from the macro definition"); @@ -1019,7 +1019,7 @@ void TokenLexer::updateLocForMacroArgTokens(SourceLocation ArgIdSpellLoc, SourceLocation InstLoc = getExpansionLocForMacroDefLoc(ArgIdSpellLoc); - + while (begin_tokens < end_tokens) { // If there's only one token just create a SLocEntry for it. if (end_tokens - begin_tokens == 1) { diff --git a/lib/Parse/ParseAST.cpp b/lib/Parse/ParseAST.cpp index 696506099e58..e71b5a9d1e6d 100644 --- a/lib/Parse/ParseAST.cpp +++ b/lib/Parse/ParseAST.cpp @@ -107,7 +107,7 @@ void clang::ParseAST(Preprocessor &PP, ASTConsumer *Consumer, // Recover resources if we crash before exiting this method. llvm::CrashRecoveryContextCleanupRegistrar<Sema> CleanupSema(S.get()); - + ParseAST(*S.get(), PrintStats, SkipFunctionBodies); } @@ -166,7 +166,7 @@ void clang::ParseAST(Sema &S, bool PrintStats, bool SkipFunctionBodies) { // Process any TopLevelDecls generated by #pragma weak. for (Decl *D : S.WeakTopLevelDecls()) Consumer->HandleTopLevelDecl(DeclGroupRef(D)); - + Consumer->HandleTranslationUnit(S.getASTContext()); // Finalize the template instantiation observer chain. diff --git a/lib/Parse/ParseCXXInlineMethods.cpp b/lib/Parse/ParseCXXInlineMethods.cpp index 27d48be0e3eb..5898120cab46 100644 --- a/lib/Parse/ParseCXXInlineMethods.cpp +++ b/lib/Parse/ParseCXXInlineMethods.cpp @@ -590,9 +590,9 @@ void Parser::ParseLexedMemberInitializers(ParsingClass &Class) { if (!Class.LateParsedDeclarations.empty()) { // C++11 [expr.prim.general]p4: - // Otherwise, if a member-declarator declares a non-static data member + // Otherwise, if a member-declarator declares a non-static data member // (9.2) of a class X, the expression this is a prvalue of type "pointer - // to X" within the optional brace-or-equal-initializer. It shall not + // to X" within the optional brace-or-equal-initializer. It shall not // appear elsewhere in the member-declarator. Sema::CXXThisScopeRAII ThisScope(Actions, Class.TagOrTemplate, /*TypeQuals=*/(unsigned)0); @@ -601,7 +601,7 @@ void Parser::ParseLexedMemberInitializers(ParsingClass &Class) { Class.LateParsedDeclarations[i]->ParseLexedMemberInitializers(); } } - + if (!AlreadyHasClassScope) Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(), Class.TagOrTemplate); @@ -627,7 +627,7 @@ void Parser::ParseLexedMemberInitializer(LateParsedMemberInitializer &MI) { Actions.ActOnStartCXXInClassMemberInitializer(); - ExprResult Init = ParseCXXMemberInitializer(MI.Field, /*IsFunction=*/false, + ExprResult Init = ParseCXXMemberInitializer(MI.Field, /*IsFunction=*/false, EqualLoc); Actions.ActOnFinishCXXInClassMemberInitializer(MI.Field, EqualLoc, diff --git a/lib/Parse/ParseDecl.cpp b/lib/Parse/ParseDecl.cpp index 4f6bb08bdc64..6e57c7bbba91 100644 --- a/lib/Parse/ParseDecl.cpp +++ b/lib/Parse/ParseDecl.cpp @@ -757,7 +757,7 @@ void Parser::ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs) { if (!getLangOpts().ObjC1) Diag(AttrNameLoc, diag::ext_nullability) << AttrName; - attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0, + attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0, ParsedAttr::AS_Keyword); break; } @@ -867,7 +867,7 @@ VersionTuple Parser::ParseVersionTuple(SourceRange &Range) { StopAtSemi | StopBeforeMatch | StopAtCodeCompletion); return VersionTuple(); } - + // Warn if separators, be it '.' or '_', do not match. if (AfterMajorSeparator != AfterMinorSeparator) Diag(Tok, diag::warn_expected_consistent_version_separator); @@ -1047,7 +1047,7 @@ void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability, continue; } } - + SourceRange VersionRange; VersionTuple Version = ParseVersionTuple(VersionRange); @@ -1259,7 +1259,7 @@ void Parser::ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated, Diag(Tok, diag::err_expected) << tok::l_paren; return; } - + // Parse the related class name. if (Tok.isNot(tok::identifier)) { Diag(Tok, diag::err_objcbridge_related_expected_related_class); @@ -1292,7 +1292,7 @@ void Parser::ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated, SkipUntil(tok::r_paren, StopAtSemi); return; } - + // Parse instance method name. Also non-optional but empty string is // permitted. IdentifierLoc *InstanceMethod = nullptr; @@ -1303,14 +1303,14 @@ void Parser::ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated, SkipUntil(tok::r_paren, StopAtSemi); return; } - + // Closing ')'. if (T.consumeClose()) return; - + if (endLoc) *endLoc = T.getCloseLocation(); - + // Record this attribute attrs.addNew(&ObjCBridgeRelated, SourceRange(ObjCBridgeRelatedLoc, T.getCloseLocation()), @@ -2032,7 +2032,7 @@ Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS, DeclsInGroup.push_back(FirstDecl); bool ExpectSemi = Context != DeclaratorContext::ForContext; - + // If we don't have a comma, it is either the end of the list (a ';') or an // error, bail out. SourceLocation CommaLoc; @@ -3815,7 +3815,7 @@ void Parser::ParseDeclarationSpecifiers(DeclSpec &DS, PrevSpec, DiagID, Type.get(), Actions.getASTContext().getPrintingPolicy())) Diag(StartLoc, DiagID) << PrevSpec; - + DS.SetRangeEnd(EndLoc); } else { DS.SetTypeSpecError(); @@ -5627,7 +5627,7 @@ void Parser::ParseDirectDeclarator(Declarator &D) { } else { AllowConstructorName = (D.getContext() == DeclaratorContext::MemberContext); - AllowDeductionGuide = + AllowDeductionGuide = (D.getContext() == DeclaratorContext::FileContext || D.getContext() == DeclaratorContext::MemberContext); } @@ -6082,13 +6082,13 @@ void Parser::ParseFunctionDeclarator(Declarator &D, LocalEndLoc = RParenLoc; EndLoc = RParenLoc; - // If there are attributes following the identifier list, parse them and + // If there are attributes following the identifier list, parse them and // prohibit them. MaybeParseCXX11Attributes(FnAttrs); ProhibitAttributes(FnAttrs); } else { if (Tok.isNot(tok::r_paren)) - ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo, + ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo, EllipsisLoc); else if (RequiresArg) Diag(Tok, diag::err_argument_required_after_attribute); @@ -6391,8 +6391,8 @@ void Parser::ParseParameterDeclarationClause( ParseDeclarationSpecifiers(DS); - // Parse the declarator. This is "PrototypeContext" or - // "LambdaExprParameterContext", because we must accept either + // Parse the declarator. This is "PrototypeContext" or + // "LambdaExprParameterContext", because we must accept either // 'declarator' or 'abstract-declarator' here. Declarator ParmDeclarator( DS, D.getContext() == DeclaratorContext::LambdaExprContext @@ -6484,7 +6484,7 @@ void Parser::ParseParameterDeclarationClause( } ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII, - ParmDeclarator.getIdentifierLoc(), + ParmDeclarator.getIdentifierLoc(), Param, std::move(DefArgToks))); } diff --git a/lib/Parse/ParseDeclCXX.cpp b/lib/Parse/ParseDeclCXX.cpp index 7c4c83d032b6..9ba44d07aba8 100644 --- a/lib/Parse/ParseDeclCXX.cpp +++ b/lib/Parse/ParseDeclCXX.cpp @@ -61,7 +61,7 @@ Parser::DeclGroupPtrTy Parser::ParseNamespace(DeclaratorContext Context, assert(Tok.is(tok::kw_namespace) && "Not a namespace!"); SourceLocation NamespaceLoc = ConsumeToken(); // eat the 'namespace'. ObjCDeclContextSwitch ObjCDC(*this); - + if (Tok.is(tok::code_completion)) { Actions.CodeCompleteNamespaceDecl(getCurScope()); cutOffParsing(); @@ -130,8 +130,8 @@ Parser::DeclGroupPtrTy Parser::ParseNamespace(DeclaratorContext Context, return nullptr; } - if (getCurScope()->isClassScope() || getCurScope()->isTemplateParamScope() || - getCurScope()->isInObjcMethodScope() || getCurScope()->getBlockParent() || + if (getCurScope()->isClassScope() || getCurScope()->isTemplateParamScope() || + getCurScope()->isInObjcMethodScope() || getCurScope()->getBlockParent() || getCurScope()->getFnParent()) { Diag(T.getOpenLocation(), diag::err_namespace_nonnamespace_scope); SkipUntil(tok::r_brace); @@ -190,7 +190,7 @@ Parser::DeclGroupPtrTy Parser::ParseNamespace(DeclaratorContext Context, PrettyDeclStackTraceEntry CrashInfo(Actions.Context, NamespcDecl, NamespaceLoc, "parsing namespace"); - // Parse the contents of the namespace. This includes parsing recovery on + // Parse the contents of the namespace. This includes parsing recovery on // any improperly nested namespaces. ParseInnerNamespace(ExtraIdentLoc, ExtraIdent, ExtraNamespaceLoc, 0, InlineLoc, attrs, T); @@ -200,8 +200,8 @@ Parser::DeclGroupPtrTy Parser::ParseNamespace(DeclaratorContext Context, DeclEnd = T.getCloseLocation(); Actions.ActOnFinishNamespaceDef(NamespcDecl, DeclEnd); - - return Actions.ConvertDeclToDeclGroup(NamespcDecl, + + return Actions.ConvertDeclToDeclGroup(NamespcDecl, ImplicitUsingDirectiveDecl); } @@ -236,7 +236,7 @@ void Parser::ParseInnerNamespace(std::vector<SourceLocation> &IdentLoc, getCurScope(), SourceLocation(), NamespaceLoc[index], IdentLoc[index], Ident[index], Tracker.getOpenLocation(), attrs, ImplicitUsingDirectiveDecl); - assert(!ImplicitUsingDirectiveDecl && + assert(!ImplicitUsingDirectiveDecl && "nested namespace definition cannot define anonymous namespace"); ParseInnerNamespace(IdentLoc, Ident, NamespaceLoc, ++index, InlineLoc, @@ -438,7 +438,7 @@ Parser::ParseUsingDirectiveOrDeclaration(DeclaratorContext Context, ParsedAttributesWithRange &attrs) { assert(Tok.is(tok::kw_using) && "Not using token"); ObjCDeclContextSwitch ObjCDC(*this); - + // Eat 'using'. SourceLocation UsingLoc = ConsumeToken(); @@ -896,7 +896,7 @@ Decl *Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){ SourceLocation Parser::ParseDecltypeSpecifier(DeclSpec &DS) { assert(Tok.isOneOf(tok::kw_decltype, tok::annot_decltype) && "Not a decltype specifier"); - + ExprResult Result; SourceLocation StartLoc = Tok.getLocation(); SourceLocation EndLoc; @@ -999,7 +999,7 @@ SourceLocation Parser::ParseDecltypeSpecifier(DeclSpec &DS) { return EndLoc; } -void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec& DS, +void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec& DS, SourceLocation StartLoc, SourceLocation EndLoc) { // make sure we have a token we can turn into an annotation token @@ -1050,9 +1050,9 @@ void Parser::ParseUnderlyingTypeSpecifier(DeclSpec &DS) { } /// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is either a -/// class name or decltype-specifier. Note that we only check that the result -/// names a type; semantic analysis will need to verify that the type names a -/// class. The result is either a type or null, depending on whether a type +/// class name or decltype-specifier. Note that we only check that the result +/// names a type; semantic analysis will need to verify that the type names a +/// class. The result is either a type or null, depending on whether a type /// name was found. /// /// base-type-specifier: [C++11 class.derived] @@ -1083,7 +1083,7 @@ TypeResult Parser::ParseBaseTypeSpecifier(SourceLocation &BaseLoc, BaseLoc = Tok.getLocation(); // Parse decltype-specifier - // tok == kw_decltype is just error recovery, it can only happen when SS + // tok == kw_decltype is just error recovery, it can only happen when SS // isn't empty if (Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) { if (SS.isNotEmpty()) @@ -1348,8 +1348,8 @@ bool Parser::isValidAfterTypeSpecifier(bool CouldBeBitfield) { void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation StartLoc, DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo, - AccessSpecifier AS, - bool EnteringContext, DeclSpecContext DSC, + AccessSpecifier AS, + bool EnteringContext, DeclSpecContext DSC, ParsedAttributesWithRange &Attributes) { DeclSpec::TST TagType; if (TagTokKind == tok::kw_struct) @@ -2061,7 +2061,7 @@ BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) { if (BaseType.isInvalid()) return true; - // Parse the optional ellipsis (for a pack expansion). The ellipsis is + // Parse the optional ellipsis (for a pack expansion). The ellipsis is // actually part of the base-specifier-list grammar productions, but we // parse it here for convenience. SourceLocation EllipsisLoc; @@ -2229,7 +2229,7 @@ void Parser::ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, bool Parser::isCXX11FinalKeyword() const { VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier(); return Specifier == VirtSpecifiers::VS_Final || - Specifier == VirtSpecifiers::VS_GNU_Final || + Specifier == VirtSpecifiers::VS_GNU_Final || Specifier == VirtSpecifiers::VS_Sealed; } @@ -2397,7 +2397,7 @@ void Parser::MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq( /// override /// final /// [MS] sealed -/// +/// /// pure-specifier: /// '= 0' /// @@ -2648,9 +2648,9 @@ Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS, } DeclaratorInfo.setFunctionDefinitionKind(DefinitionKind); - // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains + // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains // to a friend declaration, that declaration shall be a definition. - if (DeclaratorInfo.isFunctionDeclarator() && + if (DeclaratorInfo.isFunctionDeclarator() && DefinitionKind != FDK_Definition && DS.isFriendSpecified()) { // Diagnose attributes that appear before decl specifier: // [[]] friend int foo(); @@ -3142,7 +3142,7 @@ void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc, if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) { VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier(Tok); assert((Specifier == VirtSpecifiers::VS_Final || - Specifier == VirtSpecifiers::VS_GNU_Final || + Specifier == VirtSpecifiers::VS_GNU_Final || Specifier == VirtSpecifiers::VS_Sealed) && "not a class definition"); FinalLoc = ConsumeToken(); @@ -3457,7 +3457,7 @@ MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) { TryConsumeToken(tok::ellipsis, EllipsisLoc); return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II, - TemplateTypeTy, DS, IdLoc, + TemplateTypeTy, DS, IdLoc, InitList.get(), EllipsisLoc); } else if(Tok.is(tok::l_paren)) { BalancedDelimiterTracker T(*this, tok::l_paren); @@ -3506,7 +3506,7 @@ Parser::tryParseExceptionSpecification(bool Delayed, CachedTokens *&ExceptionSpecTokens) { ExceptionSpecificationType Result = EST_None; ExceptionSpecTokens = nullptr; - + // Handle delayed parsing of exception-specifications. if (Delayed) { if (Tok.isNot(tok::kw_throw) && Tok.isNot(tok::kw_noexcept)) @@ -3525,11 +3525,11 @@ Parser::tryParseExceptionSpecification(bool Delayed, NoexceptExpr = nullptr; return EST_BasicNoexcept; } - + Diag(Tok, diag::err_expected_lparen_after) << "throw"; return EST_DynamicNone; } - + // Cache the tokens for the exception-specification. ExceptionSpecTokens = new CachedTokens; ExceptionSpecTokens->push_back(StartTok); // 'throw' or 'noexcept' @@ -3543,7 +3543,7 @@ Parser::tryParseExceptionSpecification(bool Delayed, return EST_Unparsed; } - + // See if there's a dynamic specification. if (Tok.is(tok::kw_throw)) { Result = ParseDynamicExceptionSpecification(SpecificationRange, @@ -3660,7 +3660,7 @@ ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification( if (Tok.is(tok::ellipsis)) { // C++0x [temp.variadic]p5: - // - In a dynamic-exception-specification (15.4); the pattern is a + // - In a dynamic-exception-specification (15.4); the pattern is a // type-id. SourceLocation Ellipsis = ConsumeToken(); Range.setEnd(Ellipsis); @@ -4207,7 +4207,7 @@ void Parser::ParseMicrosoftIfExistsClassDeclaration( IfExistsCondition Result; if (ParseMicrosoftIfExistsCondition(Result)) return; - + BalancedDelimiterTracker Braces(*this, tok::l_brace); if (Braces.consumeOpen()) { Diag(Tok, diag::err_expected) << tok::l_brace; @@ -4218,13 +4218,13 @@ void Parser::ParseMicrosoftIfExistsClassDeclaration( case IEB_Parse: // Parse the declarations below. break; - + case IEB_Dependent: Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists) << Result.IsIfExists; // Fall through to skip. LLVM_FALLTHROUGH; - + case IEB_Skip: Braces.skipToEnd(); return; @@ -4262,6 +4262,6 @@ void Parser::ParseMicrosoftIfExistsClassDeclaration( // Parse all the comma separated declarators. ParseCXXClassMemberDeclaration(CurAS, AccessAttrs); } - + Braces.consumeClose(); } diff --git a/lib/Parse/ParseExpr.cpp b/lib/Parse/ParseExpr.cpp index 4a0e1c5e3413..2a65eec8a0f6 100644 --- a/lib/Parse/ParseExpr.cpp +++ b/lib/Parse/ParseExpr.cpp @@ -441,7 +441,7 @@ Parser::ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec) { // is okay, to bind exactly as tightly. For example, compile A=B=C=D as // A=(B=(C=D)), where each paren is a level of recursion here. // The function takes ownership of the RHS. - RHS = ParseRHSOfBinaryExpression(RHS, + RHS = ParseRHSOfBinaryExpression(RHS, static_cast<prec::Level>(ThisPrec + !isRightAssoc)); RHSIsInitList = false; @@ -656,14 +656,14 @@ class CastExpressionIdValidator : public CorrectionCandidateCallback { /// /// id-expression: [C++ 5.1] /// unqualified-id -/// qualified-id +/// qualified-id /// /// unqualified-id: [C++ 5.1] /// identifier /// operator-function-id /// conversion-function-id -/// '~' class-name -/// template-id +/// '~' class-name +/// template-id /// /// new-expression: [C++ 5.3.4] /// '::'[opt] 'new' new-placement[opt] new-type-id @@ -729,7 +729,7 @@ class CastExpressionIdValidator : public CorrectionCandidateCallback { /// '__trivially_copyable' /// /// binary-type-trait: -/// [GNU] '__is_base_of' +/// [GNU] '__is_base_of' /// [MS] '__is_convertible_to' /// '__is_convertible' /// '__is_same' @@ -789,6 +789,10 @@ ExprResult Parser::ParseCastExpression(bool isUnaryExpression, // We have parsed the cast-expression and no postfix-expr pieces are // following. return Res; + case FoldExpr: + // We only parsed a fold-expression. There might be postfix-expr pieces + // afterwards; parse them now. + break; } break; @@ -807,7 +811,7 @@ ExprResult Parser::ParseCastExpression(bool isUnaryExpression, case tok::kw_false: Res = ParseCXXBoolLiteral(); break; - + case tok::kw___objc_yes: case tok::kw___objc_no: return ParseObjCBoolLiteral(); @@ -831,7 +835,7 @@ ExprResult Parser::ParseCastExpression(bool isUnaryExpression, return ExprError(); assert(Tok.isNot(tok::kw_decltype) && Tok.isNot(tok::kw___super)); return ParseCastExpression(isUnaryExpression, isAddressOfOperand); - + case tok::identifier: { // primary-expression: identifier // unqualified-id: identifier // constant: enumeration-constant @@ -953,14 +957,14 @@ ExprResult Parser::ParseCastExpression(bool isUnaryExpression, return ExprError(); } // Allow either an identifier or the keyword 'class' (in C++). - if (Tok.isNot(tok::identifier) && + if (Tok.isNot(tok::identifier) && !(getLangOpts().CPlusPlus && Tok.is(tok::kw_class))) { Diag(Tok, diag::err_expected_property_name); return ExprError(); } IdentifierInfo &PropertyName = *Tok.getIdentifierInfo(); SourceLocation PropertyLoc = ConsumeToken(); - + Res = Actions.ActOnClassPropertyRefExpr(II, PropertyName, ILoc, PropertyLoc); break; @@ -969,7 +973,7 @@ ExprResult Parser::ParseCastExpression(bool isUnaryExpression, // In an Objective-C method, if we have "super" followed by an identifier, // the token sequence is ill-formed. However, if there's a ':' or ']' after // that identifier, this is probably a message send with a missing open - // bracket. Treat it as such. + // bracket. Treat it as such. if (getLangOpts().ObjC1 && &II == Ident_super && !InMessageExpression && getCurScope()->isInObjcMethodScope() && ((Tok.is(tok::identifier) && @@ -979,17 +983,17 @@ ExprResult Parser::ParseCastExpression(bool isUnaryExpression, nullptr); break; } - + // If we have an Objective-C class name followed by an identifier // and either ':' or ']', this is an Objective-C class message // send that's missing the opening '['. Recovery // appropriately. Also take this path if we're performing code // completion after an Objective-C class name. - if (getLangOpts().ObjC1 && - ((Tok.is(tok::identifier) && !InMessageExpression) || + if (getLangOpts().ObjC1 && + ((Tok.is(tok::identifier) && !InMessageExpression) || Tok.is(tok::code_completion))) { const Token& Next = NextToken(); - if (Tok.is(tok::code_completion) || + if (Tok.is(tok::code_completion) || Next.is(tok::colon) || Next.is(tok::r_square)) if (ParsedType Typ = Actions.getTypeName(II, ILoc, getCurScope())) if (Typ.get()->isObjCObjectOrInterfaceType()) { @@ -1001,24 +1005,24 @@ ExprResult Parser::ParseCastExpression(bool isUnaryExpression, unsigned DiagID; DS.SetTypeSpecType(TST_typename, ILoc, PrevSpec, DiagID, Typ, Actions.getASTContext().getPrintingPolicy()); - + Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext); - TypeResult Ty = Actions.ActOnTypeName(getCurScope(), + TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); if (Ty.isInvalid()) break; - Res = ParseObjCMessageExpressionBody(SourceLocation(), - SourceLocation(), + Res = ParseObjCMessageExpressionBody(SourceLocation(), + SourceLocation(), Ty.get(), nullptr); break; } } - + // Make sure to pass down the right value for isAddressOfOperand. if (isAddressOfOperand && isPostfixExpressionSuffixStart()) isAddressOfOperand = false; - + // Function designators are allowed to be undeclared (C99 6.5.1p2), so we // need to know whether or not this identifier is a function designator or // not. @@ -1175,7 +1179,7 @@ ExprResult Parser::ParseCastExpression(bool isUnaryExpression, if (getCurScope()->getFnParent() == nullptr) return ExprError(Diag(Tok, diag::err_address_of_label_outside_fn)); - + Diag(AmpAmpLoc, diag::ext_gnu_address_of_label); LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(), Tok.getLocation()); @@ -1380,7 +1384,7 @@ ExprResult Parser::ParseCastExpression(bool isUnaryExpression, T.consumeClose(); if (!Result.isInvalid()) - Result = Actions.ActOnNoexceptExpr(KeyLoc, T.getOpenLocation(), + Result = Actions.ActOnNoexceptExpr(KeyLoc, T.getOpenLocation(), Result.get(), T.getCloseLocation()); return Result; } @@ -1389,7 +1393,7 @@ ExprResult Parser::ParseCastExpression(bool isUnaryExpression, case tok::kw_##Spelling: #include "clang/Basic/TokenKinds.def" return ParseTypeTrait(); - + case tok::kw___array_rank: case tok::kw___array_extent: return ParseArrayTypeTrait(); @@ -1397,7 +1401,7 @@ ExprResult Parser::ParseCastExpression(bool isUnaryExpression, case tok::kw___is_lvalue_expr: case tok::kw___is_rvalue_expr: return ParseExpressionTrait(); - + case tok::at: { SourceLocation AtLoc = ConsumeToken(); return ParseObjCAtExpression(AtLoc); @@ -1485,16 +1489,16 @@ Parser::ParsePostfixExpressionSuffix(ExprResult LHS) { case tok::code_completion: if (InMessageExpression) return LHS; - + Actions.CodeCompletePostfixExpression(getCurScope(), LHS); cutOffParsing(); return ExprError(); - + case tok::identifier: // If we see identifier: after an expression, and we're not already in a // message send, then this is probably a message send with a missing // opening bracket '['. - if (getLangOpts().ObjC1 && !InMessageExpression && + if (getLangOpts().ObjC1 && !InMessageExpression && (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) { LHS = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(), nullptr, LHS.get()); @@ -1616,8 +1620,8 @@ Parser::ParsePostfixExpressionSuffix(ExprResult LHS) { if (!LHS.isInvalid()) { ExprResult ECResult = Actions.ActOnCUDAExecConfigExpr(getCurScope(), - OpenLoc, - ExecConfigExprs, + OpenLoc, + ExecConfigExprs, CloseLoc); if (ECResult.isInvalid()) LHS = ExprError(); @@ -1631,7 +1635,7 @@ Parser::ParsePostfixExpressionSuffix(ExprResult LHS) { ExprVector ArgExprs; CommaLocsTy CommaLocs; - + if (Tok.is(tok::code_completion)) { Actions.CodeCompleteCall(getCurScope(), LHS.get(), None); cutOffParsing(); @@ -1671,7 +1675,7 @@ Parser::ParsePostfixExpressionSuffix(ExprResult LHS) { PT.consumeClose(); LHS = ExprError(); } else { - assert((ArgExprs.size() == 0 || + assert((ArgExprs.size() == 0 || ArgExprs.size()-1 == CommaLocs.size())&& "Unexpected number of commas!"); LHS = Actions.ActOnCallExpr(getCurScope(), LHS.get(), Loc, @@ -1712,7 +1716,7 @@ Parser::ParsePostfixExpressionSuffix(ExprResult LHS) { if (LHS.isInvalid()) break; - ParseOptionalCXXScopeSpecifier(SS, ObjectType, + ParseOptionalCXXScopeSpecifier(SS, ObjectType, /*EnteringContext=*/false, &MayBePseudoDestructor); if (SS.isNotEmpty()) @@ -1745,7 +1749,7 @@ Parser::ParsePostfixExpressionSuffix(ExprResult LHS) { } if (MayBePseudoDestructor && !LHS.isInvalid()) { - LHS = ParseCXXPseudoDestructor(LHS.get(), OpLoc, OpKind, SS, + LHS = ParseCXXPseudoDestructor(LHS.get(), OpLoc, OpKind, SS, ObjectType); break; } @@ -1766,24 +1770,24 @@ Parser::ParsePostfixExpressionSuffix(ExprResult LHS) { // 'class' as if it were an identifier. // // This hack allows property access to the 'class' method because it is - // such a common method name. For other C++ keywords that are + // such a common method name. For other C++ keywords that are // Objective-C method names, one must use the message send syntax. IdentifierInfo *Id = Tok.getIdentifierInfo(); SourceLocation Loc = ConsumeToken(); Name.setIdentifier(Id, Loc); - } else if (ParseUnqualifiedId(SS, - /*EnteringContext=*/false, + } else if (ParseUnqualifiedId(SS, + /*EnteringContext=*/false, /*AllowDestructorName=*/true, /*AllowConstructorName=*/ - getLangOpts().MicrosoftExt, + getLangOpts().MicrosoftExt, /*AllowDeductionGuide=*/false, ObjectType, &TemplateKWLoc, Name)) { (void)Actions.CorrectDelayedTyposInExpr(LHS); LHS = ExprError(); } - + if (!LHS.isInvalid()) - LHS = Actions.ActOnMemberAccessExpr(getCurScope(), LHS.get(), OpLoc, + LHS = Actions.ActOnMemberAccessExpr(getCurScope(), LHS.get(), OpLoc, OpKind, SS, TemplateKWLoc, Name, CurParsedObjCImpl ? CurParsedObjCImpl->Dcl : nullptr); @@ -1878,7 +1882,7 @@ Parser::ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok, ParenParseOption ExprType = CastExpr; SourceLocation LParenLoc = Tok.getLocation(), RParenLoc; - Operand = ParseParenExpression(ExprType, true/*stopIfCastExpr*/, + Operand = ParseParenExpression(ExprType, true/*stopIfCastExpr*/, false, CastTy, RParenLoc); CastRange = SourceRange(LParenLoc, RParenLoc); @@ -1892,7 +1896,7 @@ Parser::ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok, if (getLangOpts().CPlusPlus || OpTok.isNot(tok::kw_typeof)) { // GNU typeof in C requires the expression to be parenthesized. Not so for // sizeof/alignof or in C++. Therefore, the parenthesized expression is - // the start of a unary-expression, but doesn't include any postfix + // the start of a unary-expression, but doesn't include any postfix // pieces. Parse these now if present. if (!Operand.isInvalid()) Operand = ParsePostfixExpressionSuffix(Operand.get()); @@ -1958,7 +1962,7 @@ ExprResult Parser::ParseUnaryExprOrTypeTraitExpression() { } else { Diag(Tok, diag::err_sizeof_parameter_pack); } - + if (!Name) return ExprError(); @@ -1967,7 +1971,7 @@ ExprResult Parser::ParseUnaryExprOrTypeTraitExpression() { Sema::ReuseLambdaContextDecl); return Actions.ActOnSizeofParameterPackExpr(getCurScope(), - OpTok.getLocation(), + OpTok.getLocation(), *Name, NameLoc, RParenLoc); } @@ -2202,15 +2206,15 @@ ExprResult Parser::ParseBuiltinPrimaryExpression() { TypeResult DestTy = ParseTypeName(); if (DestTy.isInvalid()) return ExprError(); - + // Attempt to consume the r-paren. if (Tok.isNot(tok::r_paren)) { Diag(Tok, diag::err_expected) << tok::r_paren; SkipUntil(tok::r_paren, StopAtSemi); return ExprError(); } - - Res = Actions.ActOnAsTypeExpr(Expr.get(), DestTy.get(), StartLoc, + + Res = Actions.ActOnAsTypeExpr(Expr.get(), DestTy.get(), StartLoc, ConsumeParen()); break; } @@ -2231,15 +2235,15 @@ ExprResult Parser::ParseBuiltinPrimaryExpression() { TypeResult DestTy = ParseTypeName(); if (DestTy.isInvalid()) return ExprError(); - + // Attempt to consume the r-paren. if (Tok.isNot(tok::r_paren)) { Diag(Tok, diag::err_expected) << tok::r_paren; SkipUntil(tok::r_paren, StopAtSemi); return ExprError(); } - - Res = Actions.ActOnConvertVectorExpr(Expr.get(), DestTy.get(), StartLoc, + + Res = Actions.ActOnConvertVectorExpr(Expr.get(), DestTy.get(), StartLoc, ConsumeParen()); break; } @@ -2294,7 +2298,7 @@ Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, CastTy = nullptr; if (Tok.is(tok::code_completion)) { - Actions.CodeCompleteOrdinaryName(getCurScope(), + Actions.CodeCompleteOrdinaryName(getCurScope(), ExprType >= CompoundLiteral? Sema::PCC_ParenthesizedExpression : Sema::PCC_Expression); cutOffParsing(); @@ -2318,7 +2322,7 @@ Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, } BridgeCast = false; } - + // None of these cases should fall through with an invalid Result // unless they've already reported an error. if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) { @@ -2372,16 +2376,16 @@ Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge_retained"); } - + TypeResult Ty = ParseTypeName(); T.consumeClose(); ColonProtection.restore(); RParenLoc = T.getCloseLocation(); ExprResult SubExpr = ParseCastExpression(/*isUnaryExpression=*/false); - + if (Ty.isInvalid() || SubExpr.isInvalid()) return ExprError(); - + return Actions.ActOnObjCBridgedCast(getCurScope(), OpenLoc, Kind, BridgeKeywordLoc, Ty.get(), RParenLoc, SubExpr.get()); @@ -2407,8 +2411,8 @@ Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, ParseSpecifierQualifierList(DS); Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext); ParseDeclarator(DeclaratorInfo); - - // If our type is followed by an identifier and either ':' or ']', then + + // If our type is followed by an identifier and either ':' or ']', then // this is probably an Objective-C message send where the leading '[' is // missing. Recover as if that were the case. if (!DeclaratorInfo.isInvalidType() && Tok.is(tok::identifier) && @@ -2419,10 +2423,10 @@ Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, InMessageExpressionRAIIObject InMessage(*this, false); Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); } - Result = ParseObjCMessageExpressionBody(SourceLocation(), - SourceLocation(), + Result = ParseObjCMessageExpressionBody(SourceLocation(), + SourceLocation(), Ty.get(), nullptr); - } else { + } else { // Match the ')'. T.consumeClose(); ColonProtection.restore(); @@ -2499,7 +2503,7 @@ Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, // Reject the cast of super idiom in ObjC. if (Tok.is(tok::identifier) && getLangOpts().ObjC1 && - Tok.getIdentifierInfo() == Ident_super && + Tok.getIdentifierInfo() == Ident_super && getCurScope()->isInObjcMethodScope() && GetLookAheadToken(1).isNot(tok::period)) { Diag(Tok.getLocation(), diag::err_illegal_super_cast) @@ -2514,7 +2518,7 @@ Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, /*isTypeCast=*/IsTypeCast); if (!Result.isInvalid()) { Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc, - DeclaratorInfo, CastTy, + DeclaratorInfo, CastTy, RParenLoc, Result.get()); } return Result; @@ -2523,8 +2527,9 @@ Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, Diag(Tok, diag::err_expected_lbrace_in_compound_literal); return ExprError(); } - } else if (Tok.is(tok::ellipsis) && + } else if (ExprType >= FoldExpr && Tok.is(tok::ellipsis) && isFoldOperator(NextToken().getKind())) { + ExprType = FoldExpr; return ParseFoldExpression(ExprResult(), T); } else if (isTypeCast) { // Parse the expression-list. @@ -2536,9 +2541,11 @@ Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, if (!ParseSimpleExpressionList(ArgExprs, CommaLocs)) { // FIXME: If we ever support comma expressions as operands to // fold-expressions, we'll need to allow multiple ArgExprs here. - if (ArgExprs.size() == 1 && isFoldOperator(Tok.getKind()) && - NextToken().is(tok::ellipsis)) + if (ExprType >= FoldExpr && ArgExprs.size() == 1 && + isFoldOperator(Tok.getKind()) && NextToken().is(tok::ellipsis)) { + ExprType = FoldExpr; return ParseFoldExpression(ArgExprs[0], T); + } ExprType = SimpleExpr; Result = Actions.ActOnParenListExpr(OpenLoc, Tok.getLocation(), @@ -2553,10 +2560,13 @@ Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, // expressions are parsed correctly. Result = Actions.CorrectDelayedTyposInExpr(Result); } - ExprType = SimpleExpr; - if (isFoldOperator(Tok.getKind()) && NextToken().is(tok::ellipsis)) + if (ExprType >= FoldExpr && isFoldOperator(Tok.getKind()) && + NextToken().is(tok::ellipsis)) { + ExprType = FoldExpr; return ParseFoldExpression(Result, T); + } + ExprType = SimpleExpr; // Don't build a paren expression unless we actually match a ')'. if (!Result.isInvalid() && Tok.is(tok::r_paren)) @@ -2712,7 +2722,7 @@ ExprResult Parser::ParseGenericSelectionExpression() { if (T.getCloseLocation().isInvalid()) return ExprError(); - return Actions.ActOnGenericSelectionExpr(KeyLoc, DefaultLoc, + return Actions.ActOnGenericSelectionExpr(KeyLoc, DefaultLoc, T.getCloseLocation(), ControllingExpr.get(), Types, Exprs); @@ -2815,7 +2825,7 @@ bool Parser::ParseExpressionList(SmallVectorImpl<Expr *> &Exprs, Expr = ParseAssignmentExpression(); if (Tok.is(tok::ellipsis)) - Expr = Actions.ActOnPackExpansion(Expr.get(), ConsumeToken()); + Expr = Actions.ActOnPackExpansion(Expr.get(), ConsumeToken()); if (Expr.isInvalid()) { SkipUntil(tok::comma, tok::r_paren, StopBeforeMatch); SawError = true; @@ -2882,7 +2892,7 @@ void Parser::ParseBlockId(SourceLocation CaretLoc) { Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type); return cutOffParsing(); } - + // Parse the specifier-qualifier-list piece. DeclSpec DS(AttrFactory); ParseSpecifierQualifierList(DS); diff --git a/lib/Parse/ParseExprCXX.cpp b/lib/Parse/ParseExprCXX.cpp index 26e75999518a..663c397ee049 100644 --- a/lib/Parse/ParseExprCXX.cpp +++ b/lib/Parse/ParseExprCXX.cpp @@ -306,13 +306,13 @@ bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS, } // If the next token is not '<', we have a qualified-id that refers - // to a template name, such as T::template apply, but is not a + // to a template name, such as T::template apply, but is not a // template-id. if (Tok.isNot(tok::less)) { TPA.Revert(); break; - } - + } + // Commit to parsing the template-id. TPA.Commit(); TemplateTy Template; @@ -366,7 +366,7 @@ bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS, TemplateId->RAngleLoc, CCLoc, EnteringContext)) { - SourceLocation StartLoc + SourceLocation StartLoc = SS.getBeginLoc().isValid()? SS.getBeginLoc() : TemplateId->TemplateNameLoc; SS.SetInvalid(SourceRange(StartLoc, CCLoc)); @@ -480,7 +480,7 @@ bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS, UnqualifiedId TemplateName; TemplateName.setIdentifier(&II, Tok.getLocation()); bool MemberOfUnknownSpecialization; - if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS, + if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS, /*hasTemplateKeyword=*/false, TemplateName, ObjectType, @@ -500,16 +500,16 @@ bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS, continue; } - if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) && + if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) && (IsTypename || IsTemplateArgumentList(1))) { - // We have something like t::getAs<T>, where getAs is a + // We have something like t::getAs<T>, where getAs is a // member of an unknown specialization. However, this will only // parse correctly as a template, so suggest the keyword 'template' // before 'getAs' and treat this as a dependent template name. unsigned DiagID = diag::err_missing_dependent_template_keyword; if (getLangOpts().MicrosoftExt) DiagID = diag::warn_missing_dependent_template_keyword; - + Diag(Tok.getLocation(), DiagID) << II.getName() << FixItHint::CreateInsertion(Tok.getLocation(), "template "); @@ -524,9 +524,9 @@ bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS, return true; } else - return true; - - continue; + return true; + + continue; } } @@ -719,7 +719,7 @@ ExprResult Parser::TryParseLambdaExpression() { if (Next.is(tok::identifier) && After.is(tok::identifier)) { return ExprEmpty(); } - + // Here, we're stuck: lambda introducers and Objective-C message sends are // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of @@ -776,7 +776,7 @@ Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro, if (Tok.is(tok::code_completion) && !(getLangOpts().ObjC1 && Intro.Default == LCD_None && !Intro.Captures.empty())) { - Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro, + Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro, /*AfterAmpersand=*/false); cutOffParsing(); break; @@ -793,14 +793,14 @@ Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro, if (getLangOpts().ObjC1 && first) Actions.CodeCompleteObjCMessageReceiver(getCurScope()); else - Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro, + Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro, /*AfterAmpersand=*/false); cutOffParsing(); break; } first = false; - + // Parse capture. LambdaCaptureKind Kind = LCK_ByCopy; LambdaCaptureInitKind InitKind = LambdaCaptureInitKind::NoInit; @@ -811,10 +811,10 @@ Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro, SourceLocation LocStart = Tok.getLocation(); if (Tok.is(tok::star)) { - Loc = ConsumeToken(); + Loc = ConsumeToken(); if (Tok.is(tok::kw_this)) { - ConsumeToken(); - Kind = LCK_StarThis; + ConsumeToken(); + Kind = LCK_StarThis; } else { return DiagResult(diag::err_expected_star_this_capture); } @@ -827,7 +827,7 @@ Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro, ConsumeToken(); if (Tok.is(tok::code_completion)) { - Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro, + Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro, /*AfterAmpersand=*/true); cutOffParsing(); break; @@ -1090,7 +1090,7 @@ ExprResult Parser::ParseLambdaExpressionAfterIntroducer( PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc, "lambda expression parsing"); - + // FIXME: Call into Actions to add any init-capture declarations to the // scope while parsing the lambda-declarator and compound-statement. @@ -1135,13 +1135,13 @@ ExprResult Parser::ParseLambdaExpressionAfterIntroducer( // Parse parameter-declaration-clause. SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo; SourceLocation EllipsisLoc; - + if (Tok.isNot(tok::r_paren)) { Actions.RecordParsingTemplateParameterDepth(TemplateParameterDepth); ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc); - // For a generic lambda, each 'auto' within the parameter declaration + // For a generic lambda, each 'auto' within the parameter declaration // clause creates a template type parameter, so increment the depth. - if (Actions.getCurGenericLambda()) + if (Actions.getCurGenericLambda()) ++CurTemplateDepthTracker; } T.consumeClose(); @@ -1161,7 +1161,7 @@ ExprResult Parser::ParseLambdaExpressionAfterIntroducer( SourceLocation ConstexprLoc; tryConsumeMutableOrConstexprToken(*this, MutableLoc, ConstexprLoc, DeclEndLoc); - + addConstexprToLambdaDeclSpecifier(*this, ConstexprLoc, DS); // Parse exception-specification[opt]. @@ -1376,7 +1376,7 @@ ExprResult Parser::ParseCXXCasts() { Result = Actions.ActOnCXXNamedCast(OpLoc, Kind, LAngleBracketLoc, DeclaratorInfo, RAngleBracketLoc, - T.getOpenLocation(), Result.get(), + T.getOpenLocation(), Result.get(), T.getCloseLocation()); return Result; @@ -1477,7 +1477,7 @@ ExprResult Parser::ParseCXXUuidof() { return ExprError(); Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true, - Ty.get().getAsOpaquePtr(), + Ty.get().getAsOpaquePtr(), T.getCloseLocation()); } else { EnterExpressionEvaluationContext Unevaluated( @@ -1507,13 +1507,13 @@ ExprResult Parser::ParseCXXUuidof() { /// postfix-expression . pseudo-destructor-name /// postfix-expression -> pseudo-destructor-name /// -/// pseudo-destructor-name: -/// ::[opt] nested-name-specifier[opt] type-name :: ~type-name -/// ::[opt] nested-name-specifier template simple-template-id :: -/// ~type-name +/// pseudo-destructor-name: +/// ::[opt] nested-name-specifier[opt] type-name :: ~type-name +/// ::[opt] nested-name-specifier template simple-template-id :: +/// ~type-name /// ::[opt] nested-name-specifier[opt] ~type-name -/// -ExprResult +/// +ExprResult Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, @@ -1562,13 +1562,13 @@ Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc, Diag(Tok, diag::err_destructor_tilde_identifier); return ExprError(); } - + // Parse the second type. UnqualifiedId SecondTypeName; IdentifierInfo *Name = Tok.getIdentifierInfo(); SourceLocation NameLoc = ConsumeToken(); SecondTypeName.setIdentifier(Name, NameLoc); - + // If there is a '<', the second type name is a template-id. Parse // it as such. if (Tok.is(tok::less) && @@ -1821,7 +1821,7 @@ Sema::ConditionResult Parser::ParseCXXCondition(StmtResult *InitStmt, MaybeParseGNUAttributes(DeclaratorInfo); // Type-check the declaration itself. - DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(), + DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(), DeclaratorInfo); if (Dcl.isInvalid()) return Sema::ConditionError(); @@ -1909,10 +1909,10 @@ void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) { getTypeAnnotation(Tok), Policy); else DS.SetTypeSpecError(); - + DS.SetRangeEnd(Tok.getAnnotationEndLoc()); ConsumeAnnotationToken(); - + DS.Finish(Actions, Policy); return; } @@ -2009,7 +2009,7 @@ bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) { } /// Finish parsing a C++ unqualified-id that is a template-id of -/// some form. +/// some form. /// /// This routine is invoked when a '<' is encountered after an identifier or /// operator-function-id is parsed by \c ParseUnqualifiedId() to determine @@ -2023,10 +2023,10 @@ bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) { /// \param Name for constructor and destructor names, this is the actual /// identifier that may be a template-name. /// -/// \param NameLoc the location of the class-name in a constructor or +/// \param NameLoc the location of the class-name in a constructor or /// destructor. /// -/// \param EnteringContext whether we're entering the scope of the +/// \param EnteringContext whether we're entering the scope of the /// nested-name-specifier. /// /// \param ObjectType if this unqualified-id occurs within a member access @@ -2035,9 +2035,9 @@ bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) { /// \param Id as input, describes the template-name or operator-function-id /// that precedes the '<'. If template arguments were parsed successfully, /// will be updated with the template-id. -/// +/// /// \param AssumeTemplateId When true, this routine will assume that the name -/// refers to a template without performing name lookup to verify. +/// refers to a template without performing name lookup to verify. /// /// \returns true if a parse error occurred, false otherwise. bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS, @@ -2070,10 +2070,10 @@ bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS, TemplateKWLoc.isValid(), Id, ObjectType, EnteringContext, Template, MemberOfUnknownSpecialization); - + if (TNK == TNK_Non_template && MemberOfUnknownSpecialization && ObjectType && IsTemplateArgumentList()) { - // We have something like t->getAs<T>(), where getAs is a + // We have something like t->getAs<T>(), where getAs is a // member of an unknown specialization. However, this will only // parse correctly as a template, so suggest the keyword 'template' // before 'getAs' and treat this as a dependent template name. @@ -2094,22 +2094,22 @@ bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS, getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext, Template, /*AllowInjectedClassName*/ true); if (TNK == TNK_Non_template) - return true; + return true; } } break; - + case UnqualifiedIdKind::IK_ConstructorName: { UnqualifiedId TemplateName; bool MemberOfUnknownSpecialization; TemplateName.setIdentifier(Name, NameLoc); TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(), - TemplateName, ObjectType, + TemplateName, ObjectType, EnteringContext, Template, MemberOfUnknownSpecialization); break; } - + case UnqualifiedIdKind::IK_DestructorName: { UnqualifiedId TemplateName; bool MemberOfUnknownSpecialization; @@ -2122,26 +2122,26 @@ bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS, return true; } else { TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(), - TemplateName, ObjectType, + TemplateName, ObjectType, EnteringContext, Template, MemberOfUnknownSpecialization); - + if (TNK == TNK_Non_template && !Id.DestructorName.get()) { Diag(NameLoc, diag::err_destructor_template_id) << Name << SS.getRange(); - return true; + return true; } } break; } - + default: return false; } - + if (TNK == TNK_Non_template) return false; - + // Parse the enclosed template argument list. SourceLocation LAngleLoc, RAngleLoc; TemplateArgList TemplateArgs; @@ -2183,12 +2183,12 @@ bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS, /*IsCtorOrDtorName=*/true); if (Type.isInvalid()) return true; - + if (Id.getKind() == UnqualifiedIdKind::IK_ConstructorName) Id.setConstructorName(Type.get(), NameLoc, RAngleLoc); else Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc); - + return false; } @@ -2223,7 +2223,7 @@ bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS, /// \param SS The nested-name-specifier that preceded this unqualified-id. If /// non-empty, then we are parsing the unqualified-id of a qualified-id. /// -/// \param EnteringContext whether we are entering the scope of the +/// \param EnteringContext whether we are entering the scope of the /// nested-name-specifier. /// /// \param ObjectType if this unqualified-id occurs within a member access @@ -2236,10 +2236,10 @@ bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext, ParsedType ObjectType, UnqualifiedId &Result) { assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword"); - + // Consume the 'operator' keyword. SourceLocation KeywordLoc = ConsumeToken(); - + // Determine what kind of operator name we have. unsigned SymbolIdx = 0; SourceLocation SymbolLocations[3]; @@ -2259,7 +2259,7 @@ bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext, T.consumeClose(); if (T.getCloseLocation().isInvalid()) return true; - + SymbolLocations[SymbolIdx++] = T.getOpenLocation(); SymbolLocations[SymbolIdx++] = T.getCloseLocation(); Op = isNew? OO_Array_New : OO_Array_Delete; @@ -2268,7 +2268,7 @@ bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext, } break; } - + #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ case tok::Token: \ SymbolLocations[SymbolIdx++] = ConsumeToken(); \ @@ -2276,7 +2276,7 @@ bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext, break; #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly) #include "clang/Basic/OperatorKinds.def" - + case tok::l_paren: { // Consume the '(' and ')'. BalancedDelimiterTracker T(*this, tok::l_paren); @@ -2284,13 +2284,13 @@ bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext, T.consumeClose(); if (T.getCloseLocation().isInvalid()) return true; - + SymbolLocations[SymbolIdx++] = T.getOpenLocation(); SymbolLocations[SymbolIdx++] = T.getCloseLocation(); Op = OO_Call; break; } - + case tok::l_square: { // Consume the '[' and ']'. BalancedDelimiterTracker T(*this, tok::l_square); @@ -2298,25 +2298,25 @@ bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext, T.consumeClose(); if (T.getCloseLocation().isInvalid()) return true; - + SymbolLocations[SymbolIdx++] = T.getOpenLocation(); SymbolLocations[SymbolIdx++] = T.getCloseLocation(); Op = OO_Subscript; break; } - + case tok::code_completion: { // Code completion for the operator name. Actions.CodeCompleteOperatorName(getCurScope()); - cutOffParsing(); + cutOffParsing(); // Don't try to parse any further. return true; } - + default: break; } - + if (Op != OO_None) { // We have parsed an operator-function-id. Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations); @@ -2409,12 +2409,12 @@ bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext, // // conversion-declarator: // ptr-operator conversion-declarator[opt] - + // Parse the type-specifier-seq. DeclSpec DS(AttrFactory); if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType? return true; - + // Parse the conversion-declarator, which is merely a sequence of // ptr-operators. Declarator D(DS, DeclaratorContext::ConversionIdContext); @@ -2424,11 +2424,11 @@ bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext, TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D); if (Ty.isInvalid()) return true; - + // Note that this is a conversion-function-id. - Result.setConversionFunctionId(KeywordLoc, Ty.get(), + Result.setConversionFunctionId(KeywordLoc, Ty.get(), D.getSourceRange().getEnd()); - return false; + return false; } /// Parse a C++ unqualified-id (or a C identifier), which describes the @@ -2448,7 +2448,7 @@ bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext, /// \param SS The nested-name-specifier that preceded this unqualified-id. If /// non-empty, then we are parsing the unqualified-id of a qualified-id. /// -/// \param EnteringContext whether we are entering the scope of the +/// \param EnteringContext whether we are entering the scope of the /// nested-name-specifier. /// /// \param AllowDestructorName whether we allow parsing of a destructor name. @@ -2503,7 +2503,7 @@ bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext, } ParsedTemplateTy TemplateName; - if (AllowConstructorName && + if (AllowConstructorName && Actions.isCurrentClassName(*Id, getCurScope(), &SS)) { // We have parsed a constructor name. ParsedType Ty = Actions.getConstructorName(*Id, IdLoc, getCurScope(), SS, @@ -2519,7 +2519,7 @@ bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext, Result.setDeductionGuideName(TemplateName, IdLoc); } else { // We have parsed an identifier. - Result.setIdentifier(Id, IdLoc); + Result.setIdentifier(Id, IdLoc); } // If the next token is a '<', we may have a template. @@ -2537,13 +2537,13 @@ bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext, return false; } - + // unqualified-id: // template-id (already parsed and annotated) if (Tok.is(tok::annot_template_id)) { TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); - // If the template-name names the current class, then this is a constructor + // If the template-name names the current class, then this is a constructor if (AllowConstructorName && TemplateId->Name && Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) { if (SS.isSet()) { @@ -2551,7 +2551,7 @@ bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext, // is taken as the constructor name where a constructor can be // declared. Thus, the template arguments are extraneous, so // complain about them and remove them entirely. - Diag(TemplateId->TemplateNameLoc, + Diag(TemplateId->TemplateNameLoc, diag::err_out_of_line_constructor_template_id) << TemplateId->Name << FixItHint::CreateRemoval( @@ -2586,17 +2586,17 @@ bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext, ConsumeAnnotationToken(); return false; } - + // unqualified-id: // operator-function-id // conversion-function-id if (Tok.is(tok::kw_operator)) { if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result)) return true; - + // If we have an operator-function-id or a literal-operator-id and the next // token is a '<', we may have a - // + // // template-id: // operator-function-id < template-argument-list[opt] > TemplateTy Template; @@ -2616,14 +2616,14 @@ bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext, return false; } - - if (getLangOpts().CPlusPlus && + + if (getLangOpts().CPlusPlus && (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) { // C++ [expr.unary.op]p10: - // There is an ambiguity in the unary-expression ~X(), where X is a - // class-name. The ambiguity is resolved in favor of treating ~ as a + // There is an ambiguity in the unary-expression ~X(), where X is a + // class-name. The ambiguity is resolved in favor of treating ~ as a // unary complement rather than treating ~X as referring to a destructor. - + // Parse the '~'. SourceLocation TildeLoc = ConsumeToken(); @@ -2637,7 +2637,7 @@ bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext, } return true; } - + // Parse the class-name. if (Tok.isNot(tok::identifier)) { Diag(Tok, diag::err_destructor_tilde_identifier); @@ -2688,7 +2688,7 @@ bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext, } // Note that this is a destructor name. - ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName, + ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName, ClassNameLoc, getCurScope(), SS, ObjectType, EnteringContext); @@ -2698,7 +2698,7 @@ bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext, Result.setDestructorName(TildeLoc, Ty, ClassNameLoc); return false; } - + Diag(Tok, diag::err_expected_unqualified_id) << getLangOpts().CPlusPlus; return true; @@ -3002,7 +3002,7 @@ static unsigned TypeTraitArity(tok::TokenKind kind) { } } -/// Parse the built-in type-trait pseudo-functions that allow +/// Parse the built-in type-trait pseudo-functions that allow /// implementation of the TR1/C++11 type traits templates. /// /// primary-expression: @@ -3018,7 +3018,7 @@ ExprResult Parser::ParseTypeTrait() { unsigned Arity = TypeTraitArity(Kind); SourceLocation Loc = ConsumeToken(); - + BalancedDelimiterTracker Parens(*this, tok::l_paren); if (Parens.expectAndConsume()) return ExprError(); @@ -3040,7 +3040,7 @@ ExprResult Parser::ParseTypeTrait() { return ExprError(); } } - + // Add this type to the list of arguments. Args.push_back(Ty.get()); } while (TryConsumeToken(tok::comma)); @@ -3266,7 +3266,7 @@ Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType, ExprType = SimpleExpr; Result = ParseExpression(); if (!Result.isInvalid() && Tok.is(tok::r_paren)) - Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(), + Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(), Tok.getLocation(), Result.get()); // Match the ')'. diff --git a/lib/Parse/ParseInit.cpp b/lib/Parse/ParseInit.cpp index 90f3561cb963..0cd550bc6a47 100644 --- a/lib/Parse/ParseInit.cpp +++ b/lib/Parse/ParseInit.cpp @@ -20,21 +20,21 @@ using namespace clang; -/// MayBeDesignationStart - Return true if the current token might be the start -/// of a designator. If we can tell it is impossible that it is a designator, +/// MayBeDesignationStart - Return true if the current token might be the start +/// of a designator. If we can tell it is impossible that it is a designator, /// return false. bool Parser::MayBeDesignationStart() { switch (Tok.getKind()) { - default: + default: return false; - + case tok::period: // designator: '.' identifier return true; - + case tok::l_square: { // designator: array-designator if (!PP.getLangOpts().CPlusPlus11) return true; - + // C++11 lambda expressions and C99 designators can be ambiguous all the // way through the closing ']' and to the next character. Handle the easy // cases here, and fall back to tentative parsing if those fail. @@ -43,28 +43,28 @@ bool Parser::MayBeDesignationStart() { case tok::r_square: // Definitely starts a lambda expression. return false; - + case tok::amp: case tok::kw_this: case tok::identifier: // We have to do additional analysis, because these could be the // start of a constant expression or a lambda capture list. break; - + default: - // Anything not mentioned above cannot occur following a '[' in a + // Anything not mentioned above cannot occur following a '[' in a // lambda expression. - return true; + return true; } - + // Handle the complicated case below. - break; + break; } case tok::identifier: // designation: identifier ':' return PP.LookAhead(0).is(tok::colon); } - - // Parse up to (at most) the token after the closing ']' to determine + + // Parse up to (at most) the token after the closing ']' to determine // whether this is a C99 designator or a lambda. TentativeParsingAction Tentative(*this); @@ -198,7 +198,7 @@ ExprResult Parser::ParseInitializerWithPotentialDesignator() { // it will be rejected because a constant-expression cannot begin with a // lambda-expression. InMessageExpressionRAIIObject InMessage(*this, true); - + BalancedDelimiterTracker T(*this, tok::l_square); T.consumeOpen(); SourceLocation StartLoc = T.getOpenLocation(); @@ -212,7 +212,7 @@ ExprResult Parser::ParseInitializerWithPotentialDesignator() { if (getLangOpts().ObjC1 && getLangOpts().CPlusPlus) { // Send to 'super'. if (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_super && - NextToken().isNot(tok::period) && + NextToken().isNot(tok::period) && getCurScope()->isInObjcMethodScope()) { CheckArrayDesignatorSyntax(*this, StartLoc, Desig); return ParseAssignmentExprWithObjCMessageExprStart( @@ -226,13 +226,13 @@ ExprResult Parser::ParseInitializerWithPotentialDesignator() { SkipUntil(tok::r_square, StopAtSemi); return ExprError(); } - + // If the receiver was a type, we have a class message; parse // the rest of it. if (!IsExpr) { CheckArrayDesignatorSyntax(*this, StartLoc, Desig); - return ParseAssignmentExprWithObjCMessageExprStart(StartLoc, - SourceLocation(), + return ParseAssignmentExprWithObjCMessageExprStart(StartLoc, + SourceLocation(), ParsedType::getFromOpaquePtr(TypeOrExpr), nullptr); } @@ -281,8 +281,8 @@ ExprResult Parser::ParseInitializerWithPotentialDesignator() { } return ParseAssignmentExprWithObjCMessageExprStart(StartLoc, - SourceLocation(), - ReceiverType, + SourceLocation(), + ReceiverType, nullptr); case Sema::ObjCInstanceMessage: @@ -387,7 +387,7 @@ ExprResult Parser::ParseInitializerWithPotentialDesignator() { /// ExprResult Parser::ParseBraceInitializer() { InMessageExpressionRAIIObject InMessage(*this, false); - + BalancedDelimiterTracker T(*this, tok::l_brace); T.consumeOpen(); SourceLocation LBraceLoc = T.getOpenLocation(); @@ -485,7 +485,7 @@ bool Parser::ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs, IfExistsCondition Result; if (ParseMicrosoftIfExistsCondition(Result)) return false; - + BalancedDelimiterTracker Braces(*this, tok::l_brace); if (Braces.consumeOpen()) { Diag(Tok, diag::err_expected) << tok::l_brace; @@ -496,7 +496,7 @@ bool Parser::ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs, case IEB_Parse: // Parse the declarations below. break; - + case IEB_Dependent: Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists) << Result.IsIfExists; @@ -520,7 +520,7 @@ bool Parser::ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs, if (Tok.is(tok::ellipsis)) SubElt = Actions.ActOnPackExpansion(SubElt.get(), ConsumeToken()); - + // If we couldn't parse the subelement, bail out. if (!SubElt.isInvalid()) InitExprs.push_back(SubElt.get()); diff --git a/lib/Parse/ParseObjc.cpp b/lib/Parse/ParseObjc.cpp index 5c5b3cdfcf33..99e5edb9d4a3 100644 --- a/lib/Parse/ParseObjc.cpp +++ b/lib/Parse/ParseObjc.cpp @@ -247,7 +247,7 @@ Decl *Parser::ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc, if (Tok.is(tok::l_paren) && !isKnownToBeTypeSpecifier(GetLookAheadToken(1))) { // we have a category. - + BalancedDelimiterTracker T(*this, tok::l_paren); T.consumeOpen(); @@ -258,7 +258,7 @@ Decl *Parser::ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc, cutOffParsing(); return nullptr; } - + // For ObjC2, the category name is optional (not an error). if (Tok.is(tok::identifier)) { categoryId = Tok.getIdentifierInfo(); @@ -269,11 +269,11 @@ Decl *Parser::ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc, << tok::identifier; // missing category name. return nullptr; } - + T.consumeClose(); if (T.getCloseLocation().isInvalid()) return nullptr; - + // Next, we need to check for any protocol references. assert(LAngleLoc.isInvalid() && "Cannot have already parsed protocols"); SmallVector<Decl *, 8> ProtocolRefs; @@ -291,7 +291,7 @@ Decl *Parser::ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc, if (Tok.is(tok::l_brace)) ParseObjCClassInstanceVariables(CategoryType, tok::objc_private, AtLoc); - + ParseObjCInterfaceDeclList(tok::objc_not_keyword, CategoryType); return CategoryType; @@ -592,14 +592,14 @@ ObjCTypeParamList *Parser::parseObjCTypeParamList() { /// @required /// @optional /// -void Parser::ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey, +void Parser::ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey, Decl *CDecl) { SmallVector<Decl *, 32> allMethods; SmallVector<DeclGroupPtrTy, 8> allTUVariables; tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword; SourceRange AtEnd; - + while (1) { // If this is a method prototype, parse it. if (Tok.isOneOf(tok::minus, tok::plus)) { @@ -618,8 +618,8 @@ void Parser::ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey, } if (Tok.is(tok::l_paren)) { Diag(Tok, diag::err_expected_minus_or_plus); - ParseObjCMethodDecl(Tok.getLocation(), - tok::minus, + ParseObjCMethodDecl(Tok.getLocation(), + tok::minus, MethodImplKind, false); continue; } @@ -635,12 +635,12 @@ void Parser::ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey, // Code completion within an Objective-C interface. if (Tok.is(tok::code_completion)) { - Actions.CodeCompleteOrdinaryName(getCurScope(), + Actions.CodeCompleteOrdinaryName(getCurScope(), CurParsedObjCImpl? Sema::PCC_ObjCImplementation : Sema::PCC_ObjCInterface); return cutOffParsing(); } - + // If we don't have an @ directive, parse it as a function definition. if (Tok.isNot(tok::at)) { // The code below does not consume '}'s because it is afraid of eating the @@ -685,7 +685,7 @@ void Parser::ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey, // Skip until we see an '@' or '}' or ';'. SkipUntil(tok::r_brace, tok::at, StopAtSemi); break; - + case tok::objc_implementation: case tok::objc_interface: Diag(AtLoc, diag::err_objc_missing_end) @@ -694,7 +694,7 @@ void Parser::ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey, << (int) Actions.getObjCContainerKind(); ConsumeToken(); break; - + case tok::objc_required: case tok::objc_optional: // This is only valid on protocols. @@ -1021,7 +1021,7 @@ IdentifierInfo *Parser::ParseObjCSelectorPiece(SourceLocation &SelectorLoc) { } return nullptr; } - + case tok::identifier: case tok::kw_asm: case tok::kw_auto: @@ -1134,11 +1134,11 @@ void Parser::ParseObjCTypeQualifierList(ObjCDeclSpec &DS, while (1) { if (Tok.is(tok::code_completion)) { - Actions.CodeCompleteObjCPassingType(getCurScope(), DS, + Actions.CodeCompleteObjCPassingType(getCurScope(), DS, Context == DeclaratorContext::ObjCParameterContext); return cutOffParsing(); } - + if (Tok.isNot(tok::identifier)) return; @@ -1160,17 +1160,17 @@ void Parser::ParseObjCTypeQualifierList(ObjCDeclSpec &DS, case objc_bycopy: Qual = ObjCDeclSpec::DQ_Bycopy; break; case objc_byref: Qual = ObjCDeclSpec::DQ_Byref; break; - case objc_nonnull: + case objc_nonnull: Qual = ObjCDeclSpec::DQ_CSNullability; Nullability = NullabilityKind::NonNull; break; - case objc_nullable: + case objc_nullable: Qual = ObjCDeclSpec::DQ_CSNullability; Nullability = NullabilityKind::Nullable; break; - case objc_null_unspecified: + case objc_null_unspecified: Qual = ObjCDeclSpec::DQ_CSNullability; Nullability = NullabilityKind::Unspecified; break; @@ -1222,7 +1222,7 @@ static void takeDeclAttributes(ParsedAttributes &attrs, /// '(' objc-type-qualifiers[opt] type-name ')' /// '(' objc-type-qualifiers[opt] ')' /// -ParsedType Parser::ParseObjCTypeName(ObjCDeclSpec &DS, +ParsedType Parser::ParseObjCTypeName(ObjCDeclSpec &DS, DeclaratorContext context, ParsedAttributes *paramAttrs) { assert(context == DeclaratorContext::ObjCParameterContext || @@ -1343,7 +1343,7 @@ Decl *Parser::ParseObjCMethodDecl(SourceLocation mLoc, MaybeParseCXX11Attributes(methodAttrs); if (Tok.is(tok::code_completion)) { - Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus, + Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus, ReturnType); cutOffParsing(); return nullptr; @@ -1409,7 +1409,7 @@ Decl *Parser::ParseObjCMethodDecl(SourceLocation mLoc, // Code completion for the next piece of the selector. if (Tok.is(tok::code_completion)) { KeyIdents.push_back(SelIdent); - Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(), + Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(), mType == tok::minus, /*AtParameterName=*/true, ReturnType, KeyIdents); @@ -1433,14 +1433,14 @@ Decl *Parser::ParseObjCMethodDecl(SourceLocation mLoc, // Code completion for the next piece of the selector. if (Tok.is(tok::code_completion)) { - Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(), + Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(), mType == tok::minus, /*AtParameterName=*/false, ReturnType, KeyIdents); cutOffParsing(); return nullptr; } - + // Check for another keyword selector. SelIdent = ParseObjCSelectorPiece(selLoc); if (!SelIdent && Tok.isNot(tok::colon)) @@ -1478,7 +1478,7 @@ Decl *Parser::ParseObjCMethodDecl(SourceLocation mLoc, IdentifierInfo *ParmII = ParmDecl.getIdentifier(); Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl); CParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII, - ParmDecl.getIdentifierLoc(), + ParmDecl.getIdentifierLoc(), Param, nullptr)); } @@ -1614,7 +1614,7 @@ void Parser::parseObjCTypeArgsOrProtocolQualifiers( // FIXME: Also include types here. SmallVector<IdentifierLocPair, 4> identifierLocPairs; for (unsigned i = 0, n = identifiers.size(); i != n; ++i) { - identifierLocPairs.push_back(IdentifierLocPair(identifiers[i], + identifierLocPairs.push_back(IdentifierLocPair(identifiers[i], identifierLocs[i])); } @@ -1800,10 +1800,10 @@ void Parser::parseObjCTypeArgsAndProtocolQualifiers( << SourceRange(protocolLAngleLoc, protocolRAngleLoc); SkipUntil(tok::greater, tok::greatergreater, skipFlags); } else { - ParseObjCProtocolReferences(protocols, protocolLocs, + ParseObjCProtocolReferences(protocols, protocolLocs, /*WarnOnDeclarations=*/false, /*ForObjCContainer=*/false, - protocolLAngleLoc, protocolRAngleLoc, + protocolLAngleLoc, protocolRAngleLoc, consumeLastToken); } } @@ -1857,7 +1857,7 @@ void Parser::HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocatio bool RBraceMissing) { if (!RBraceMissing) T.consumeClose(); - + Actions.ActOnObjCContainerStartDefinition(interfaceDecl); Actions.ActOnLastBitfield(T.getCloseLocation(), AllIvarDecls); Actions.ActOnObjCContainerFinishDefinition(); @@ -1893,7 +1893,7 @@ void Parser::ParseObjCClassInstanceVariables(Decl *interfaceDecl, SourceLocation atLoc) { assert(Tok.is(tok::l_brace) && "expected {"); SmallVector<Decl *, 32> AllIvarDecls; - + ParseScope ClassScope(this, Scope::DeclScope|Scope::ClassScope); ObjCDeclContextSwitch ObjCDC(*this); @@ -1915,7 +1915,7 @@ void Parser::ParseObjCClassInstanceVariables(Decl *interfaceDecl, Actions.CodeCompleteObjCAtVisibility(getCurScope()); return cutOffParsing(); } - + switch (Tok.getObjCKeywordID()) { case tok::objc_private: case tok::objc_public: @@ -1934,7 +1934,7 @@ void Parser::ParseObjCClassInstanceVariables(Decl *interfaceDecl, HelperActionsForIvarDeclarations(interfaceDecl, atLoc, T, AllIvarDecls, true); return; - + default: Diag(Tok, diag::err_objc_illegal_visibility_spec); continue; @@ -1942,7 +1942,7 @@ void Parser::ParseObjCClassInstanceVariables(Decl *interfaceDecl, } if (Tok.is(tok::code_completion)) { - Actions.CodeCompleteOrdinaryName(getCurScope(), + Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_ObjCInstanceVariableList); return cutOffParsing(); } @@ -1992,7 +1992,7 @@ void Parser::ParseObjCClassInstanceVariables(Decl *interfaceDecl, /// "\@protocol identifier ;" should be resolved as "\@protocol /// identifier-list ;": objc-interface-decl-list may not start with a /// semicolon in the first alternative if objc-protocol-refs are omitted. -Parser::DeclGroupPtrTy +Parser::DeclGroupPtrTy Parser::ParseObjCAtProtocolDeclaration(SourceLocation AtLoc, ParsedAttributes &attrs) { assert(Tok.isObjCAtKeyword(tok::objc_protocol) && @@ -2125,7 +2125,7 @@ Parser::ParseObjCAtImplementationDeclaration(SourceLocation AtLoc) { cutOffParsing(); return nullptr; } - + if (Tok.is(tok::identifier)) { categoryId = Tok.getIdentifierInfo(); categoryLoc = ConsumeToken(); @@ -2145,7 +2145,7 @@ Parser::ParseObjCAtImplementationDeclaration(SourceLocation AtLoc) { SourceLocation protocolLAngleLoc, protocolRAngleLoc; SmallVector<Decl *, 4> protocols; SmallVector<SourceLocation, 4> protocolLocs; - (void)ParseObjCProtocolReferences(protocols, protocolLocs, + (void)ParseObjCProtocolReferences(protocols, protocolLocs, /*warnOnIncompleteProtocols=*/false, /*ForObjCContainer=*/false, protocolLAngleLoc, protocolRAngleLoc, @@ -2169,7 +2169,7 @@ Parser::ParseObjCAtImplementationDeclaration(SourceLocation AtLoc) { ObjCImpDecl = Actions.ActOnStartClassImplementation( AtLoc, nameId, nameLoc, superClassId, superClassLoc); - + if (Tok.is(tok::l_brace)) // we have ivars ParseObjCClassInstanceVariables(ObjCImpDecl, tok::objc_private, AtLoc); else if (Tok.is(tok::less)) { // we have illegal '<' try to recover @@ -2178,7 +2178,7 @@ Parser::ParseObjCAtImplementationDeclaration(SourceLocation AtLoc) { SourceLocation protocolLAngleLoc, protocolRAngleLoc; SmallVector<Decl *, 4> protocols; SmallVector<SourceLocation, 4> protocolLocs; - (void)ParseObjCProtocolReferences(protocols, protocolLocs, + (void)ParseObjCProtocolReferences(protocols, protocolLocs, /*warnOnIncompleteProtocols=*/false, /*ForObjCContainer=*/false, protocolLAngleLoc, protocolRAngleLoc, @@ -2235,16 +2235,16 @@ void Parser::ObjCImplParsingDataRAII::finish(SourceRange AtEnd) { assert(!Finished); P.Actions.DefaultSynthesizeProperties(P.getCurScope(), Dcl, AtEnd.getBegin()); for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i) - P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i], + P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i], true/*Methods*/); P.Actions.ActOnAtEnd(P.getCurScope(), AtEnd); if (HasCFunction) for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i) - P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i], + P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i], false/*c-functions*/); - + /// Clear and free the cached objc methods. for (LateParsedObjCMethodContainer::iterator I = LateParsedObjCMethods.begin(), @@ -2297,7 +2297,7 @@ Decl *Parser::ParseObjCPropertySynthesize(SourceLocation atLoc) { cutOffParsing(); return nullptr; } - + if (Tok.isNot(tok::identifier)) { Diag(Tok, diag::err_synthesized_property_name); SkipUntil(tok::semi); @@ -2380,7 +2380,7 @@ Decl *Parser::ParseObjCPropertyDynamic(SourceLocation atLoc) { SkipUntil(tok::semi); return nullptr; } - + IdentifierInfo *propertyId = Tok.getIdentifierInfo(); SourceLocation propertyLoc = ConsumeToken(); // consume property name Actions.ActOnPropertyImplDecl( @@ -2538,14 +2538,14 @@ StmtResult Parser::ParseObjCTryStmt(SourceLocation atLoc) { Diag(Tok, diag::err_expected) << tok::l_brace; if (CatchBody.isInvalid()) CatchBody = Actions.ActOnNullStmt(Tok.getLocation()); - + StmtResult Catch = Actions.ActOnObjCAtCatchStmt(AtCatchFinallyLoc, - RParenLoc, - FirstPart, + RParenLoc, + FirstPart, CatchBody.get()); if (!Catch.isInvalid()) CatchStmts.push_back(Catch.get()); - + } else { Diag(AtCatchFinallyLoc, diag::err_expected_lparen_after) << "@catch clause"; @@ -2588,8 +2588,8 @@ StmtResult Parser::ParseObjCTryStmt(SourceLocation atLoc) { Diag(atLoc, diag::err_missing_catch_finally); return StmtError(); } - - return Actions.ActOnObjCAtTryStmt(atLoc, TryBody.get(), + + return Actions.ActOnObjCAtTryStmt(atLoc, TryBody.get(), CatchStmts, FinallyStmt.get()); } @@ -2613,11 +2613,11 @@ Parser::ParseObjCAutoreleasePoolStmt(SourceLocation atLoc) { BodyScope.Exit(); if (AutoreleasePoolBody.isInvalid()) AutoreleasePoolBody = Actions.ActOnNullStmt(Tok.getLocation()); - return Actions.ActOnObjCAutoreleasePoolStmt(atLoc, + return Actions.ActOnObjCAutoreleasePoolStmt(atLoc, AutoreleasePoolBody.get()); } -/// StashAwayMethodOrFunctionBodyTokens - Consume the tokens and store them +/// StashAwayMethodOrFunctionBodyTokens - Consume the tokens and store them /// for later parsing. void Parser::StashAwayMethodOrFunctionBodyTokens(Decl *MDecl) { if (SkipFunctionBodies && (!MDecl || Actions.canSkipFunctionBody(MDecl)) && @@ -2698,7 +2698,7 @@ Decl *Parser::ParseObjCMethodDefinition() { // Allow the rest of sema to find private method decl implementations. Actions.AddAnyMethodToGlobalPool(MDecl); - assert (CurParsedObjCImpl + assert (CurParsedObjCImpl && "ParseObjCMethodDefinition - Method out of @implementation"); // Consume the tokens and store them for later parsing. StashAwayMethodOrFunctionBodyTokens(MDecl); @@ -2711,13 +2711,13 @@ StmtResult Parser::ParseObjCAtStatement(SourceLocation AtLoc) { cutOffParsing(); return StmtError(); } - + if (Tok.isObjCAtKeyword(tok::objc_try)) return ParseObjCTryStmt(AtLoc); - + if (Tok.isObjCAtKeyword(tok::objc_throw)) return ParseObjCThrowStmt(AtLoc); - + if (Tok.isObjCAtKeyword(tok::objc_synchronized)) return ParseObjCSynchronizedStmt(AtLoc); @@ -2739,7 +2739,7 @@ StmtResult Parser::ParseObjCAtStatement(SourceLocation AtLoc) { SkipUntil(tok::semi); return StmtError(); } - + // Otherwise, eat the semicolon. ExpectAndConsumeSemi(diag::err_expected_semi_after_expr); return Actions.ActOnExprStmt(Res); @@ -2789,7 +2789,7 @@ ExprResult Parser::ParseObjCAtExpression(SourceLocation AtLoc) { case tok::char_constant: return ParsePostfixExpressionSuffix(ParseObjCCharacterLiteral(AtLoc)); - + case tok::numeric_constant: return ParsePostfixExpressionSuffix(ParseObjCNumericLiteral(AtLoc)); @@ -2799,19 +2799,19 @@ ExprResult Parser::ParseObjCAtExpression(SourceLocation AtLoc) { case tok::kw_false: // Objective-C++, etc. case tok::kw___objc_no: // c/c++/objc/objc++ __objc_no return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, false)); - + case tok::l_square: // Objective-C array literal return ParsePostfixExpressionSuffix(ParseObjCArrayLiteral(AtLoc)); - + case tok::l_brace: // Objective-C dictionary literal return ParsePostfixExpressionSuffix(ParseObjCDictionaryLiteral(AtLoc)); - + case tok::l_paren: // Objective-C boxed expression return ParsePostfixExpressionSuffix(ParseObjCBoxedExpr(AtLoc)); - + default: if (Tok.getIdentifierInfo() == nullptr) return ExprError(Diag(AtLoc, diag::err_unexpected_at)); @@ -2833,14 +2833,14 @@ ExprResult Parser::ParseObjCAtExpression(SourceLocation AtLoc) { if (GetLookAheadToken(1).is(tok::l_brace) && ExprStatementTokLoc == AtLoc) { char ch = Tok.getIdentifierInfo()->getNameStart()[0]; - str = - ch == 't' ? "try" - : (ch == 'f' ? "finally" + str = + ch == 't' ? "try" + : (ch == 'f' ? "finally" : (ch == 'a' ? "autoreleasepool" : nullptr)); } if (str) { SourceLocation kwLoc = Tok.getLocation(); - return ExprError(Diag(AtLoc, diag::err_unexpected_at) << + return ExprError(Diag(AtLoc, diag::err_unexpected_at) << FixItHint::CreateReplacement(kwLoc, str)); } else @@ -2856,7 +2856,7 @@ ExprResult Parser::ParseObjCAtExpression(SourceLocation AtLoc) { /// Objective-C++ either as a type or as an expression. Note that this /// routine must not be called to parse a send to 'super', since it /// has no way to return such a result. -/// +/// /// \param IsExpr Whether the receiver was parsed as an expression. /// /// \param TypeOrExpr If the receiver was parsed as an expression (\c @@ -2900,7 +2900,7 @@ bool Parser::ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr) { // expression (that starts with one of the above) DeclSpec DS(AttrFactory); ParseCXXSimpleTypeSpecifier(DS); - + if (Tok.is(tok::l_paren)) { // If we see an opening parentheses at this point, we are // actually parsing an expression that starts with a @@ -2926,7 +2926,7 @@ bool Parser::ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr) { TypeOrExpr = Receiver.get(); return false; } - + // We have a class message. Turn the simple-type-specifier or // typename-specifier we parsed into a type and parse the // remainder of the class message. @@ -2953,26 +2953,26 @@ bool Parser::isSimpleObjCMessageExpression() { } bool Parser::isStartOfObjCClassMessageMissingOpenBracket() { - if (!getLangOpts().ObjC1 || !NextToken().is(tok::identifier) || + if (!getLangOpts().ObjC1 || !NextToken().is(tok::identifier) || InMessageExpression) return false; - + ParsedType Type; - if (Tok.is(tok::annot_typename)) + if (Tok.is(tok::annot_typename)) Type = getTypeAnnotation(Tok); else if (Tok.is(tok::identifier)) - Type = Actions.getTypeName(*Tok.getIdentifierInfo(), Tok.getLocation(), + Type = Actions.getTypeName(*Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope()); else return false; - + if (!Type.get().isNull() && Type.get()->isObjCObjectOrInterfaceType()) { const Token &AfterNext = GetLookAheadToken(2); if (AfterNext.isOneOf(tok::colon, tok::r_square)) { if (Tok.is(tok::identifier)) TryAnnotateTypeOrScopeToken(); - + return Tok.is(tok::annot_typename); } } @@ -2998,14 +2998,14 @@ ExprResult Parser::ParseObjCMessageExpression() { cutOffParsing(); return ExprError(); } - + InMessageExpressionRAIIObject InMessage(*this, true); - + if (getLangOpts().CPlusPlus) { // We completely separate the C and C++ cases because C++ requires - // more complicated (read: slower) parsing. - - // Handle send to super. + // more complicated (read: slower) parsing. + + // Handle send to super. // FIXME: This doesn't benefit from the same typo-correction we // get in Objective-C. if (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_super && @@ -3025,11 +3025,11 @@ ExprResult Parser::ParseObjCMessageExpression() { return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), nullptr, static_cast<Expr *>(TypeOrExpr)); - return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), + return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), ParsedType::getFromOpaquePtr(TypeOrExpr), nullptr); } - + if (Tok.is(tok::identifier)) { IdentifierInfo *Name = Tok.getIdentifierInfo(); SourceLocation NameLoc = Tok.getLocation(); @@ -3065,7 +3065,7 @@ ExprResult Parser::ParseObjCMessageExpression() { ReceiverType = NewReceiverType.get(); } - return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), + return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), ReceiverType, nullptr); case Sema::ObjCInstanceMessage: @@ -3073,7 +3073,7 @@ ExprResult Parser::ParseObjCMessageExpression() { break; } } - + // Otherwise, an arbitrary expression can be the receiver of a send. ExprResult Res = Actions.CorrectDelayedTyposInExpr(ParseExpression()); if (Res.isInvalid()) { @@ -3143,11 +3143,11 @@ Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc, cutOffParsing(); return ExprError(); } - + // Parse objc-selector SourceLocation Loc; IdentifierInfo *selIdent = ParseObjCSelectorPiece(Loc); - + SmallVector<IdentifierInfo *, 12> KeyIdents; SmallVector<SourceLocation, 12> KeyLocs; ExprVector KeyExprs; @@ -3167,10 +3167,10 @@ Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc, } /// Parse the expression after ':' - + if (Tok.is(tok::code_completion)) { if (SuperLoc.isValid()) - Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, + Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, KeyIdents, /*AtArgumentEpression=*/true); else if (ReceiverType) @@ -3185,14 +3185,14 @@ Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc, cutOffParsing(); return ExprError(); } - + ExprResult Expr; if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) { Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists); Expr = ParseBraceInitializer(); } else Expr = ParseAssignmentExpression(); - + ExprResult Res(Expr); if (Res.isInvalid()) { // We must manually skip to a ']', otherwise the expression skipper will @@ -3208,7 +3208,7 @@ Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc, // Code completion after each argument. if (Tok.is(tok::code_completion)) { if (SuperLoc.isValid()) - Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, + Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, KeyIdents, /*AtArgumentEpression=*/false); else if (ReceiverType) @@ -3222,7 +3222,7 @@ Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc, cutOffParsing(); return ExprError(); } - + // Check for another keyword selector. selIdent = ParseObjCSelectorPiece(Loc); if (!selIdent && Tok.isNot(tok::colon)) @@ -3260,7 +3260,7 @@ Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc, SkipUntil(tok::r_square, StopAtSemi); return ExprError(); } - + if (Tok.isNot(tok::r_square)) { Diag(Tok, diag::err_expected) << (Tok.is(tok::identifier) ? tok::colon : tok::r_square); @@ -3270,7 +3270,7 @@ Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc, SkipUntil(tok::r_square, StopAtSemi); return ExprError(); } - + SourceLocation RBracLoc = ConsumeBracket(); // consume ']' unsigned nKeys = KeyIdents.size(); @@ -3324,7 +3324,7 @@ ExprResult Parser::ParseObjCStringLiteral(SourceLocation AtLoc) { /// ; /// boolean-keyword: 'true' | 'false' | '__objc_yes' | '__objc_no' /// ; -ExprResult Parser::ParseObjCBooleanLiteral(SourceLocation AtLoc, +ExprResult Parser::ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue) { SourceLocation EndLoc = ConsumeToken(); // consume the keyword. return Actions.ActOnObjCBoolLiteral(AtLoc, EndLoc, ArgValue); @@ -3395,15 +3395,15 @@ ExprResult Parser::ParseObjCArrayLiteral(SourceLocation AtLoc) { // the enclosing expression. SkipUntil(tok::r_square, StopAtSemi); return Res; - } - + } + Res = Actions.CorrectDelayedTyposInExpr(Res.get()); if (Res.isInvalid()) HasInvalidEltExpr = true; // Parse the ellipsis that indicates a pack expansion. if (Tok.is(tok::ellipsis)) - Res = Actions.ActOnPackExpansion(Res.get(), ConsumeToken()); + Res = Actions.ActOnPackExpansion(Res.get(), ConsumeToken()); if (Res.isInvalid()) HasInvalidEltExpr = true; @@ -3447,7 +3447,7 @@ ExprResult Parser::ParseObjCDictionaryLiteral(SourceLocation AtLoc) { SkipUntil(tok::r_brace, StopAtSemi); return ExprError(); } - + ExprResult ValueExpr(ParseAssignmentExpression()); if (ValueExpr.isInvalid()) { // We must manually skip to a '}', otherwise the expression skipper will @@ -3456,7 +3456,7 @@ ExprResult Parser::ParseObjCDictionaryLiteral(SourceLocation AtLoc) { SkipUntil(tok::r_brace, StopAtSemi); return ValueExpr; } - + // Check the key and value for possible typos KeyExpr = Actions.CorrectDelayedTyposInExpr(KeyExpr.get()); ValueExpr = Actions.CorrectDelayedTyposInExpr(ValueExpr.get()); @@ -3472,8 +3472,8 @@ ExprResult Parser::ParseObjCDictionaryLiteral(SourceLocation AtLoc) { // We have a valid expression. Collect it in a vector so we can // build the argument list. - ObjCDictionaryElement Element = { - KeyExpr.get(), ValueExpr.get(), EllipsisLoc, None + ObjCDictionaryElement Element = { + KeyExpr.get(), ValueExpr.get(), EllipsisLoc, None }; Elements.push_back(Element); @@ -3485,7 +3485,7 @@ ExprResult Parser::ParseObjCDictionaryLiteral(SourceLocation AtLoc) { if (HasInvalidEltExpr) return ExprError(); - + // Create the ObjCDictionaryLiteral. return Actions.BuildObjCDictionaryLiteral(SourceRange(AtLoc, EndLoc), Elements); @@ -3551,26 +3551,26 @@ ExprResult Parser::ParseObjCSelectorExpression(SourceLocation AtLoc) { SmallVector<IdentifierInfo *, 12> KeyIdents; SourceLocation sLoc; - + BalancedDelimiterTracker T(*this, tok::l_paren); T.consumeOpen(); bool HasOptionalParen = Tok.is(tok::l_paren); if (HasOptionalParen) ConsumeParen(); - + if (Tok.is(tok::code_completion)) { Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents); cutOffParsing(); return ExprError(); } - + IdentifierInfo *SelIdent = ParseObjCSelectorPiece(sLoc); if (!SelIdent && // missing selector name. Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon)) return ExprError(Diag(Tok, diag::err_expected) << tok::identifier); KeyIdents.push_back(SelIdent); - + unsigned nColons = 0; if (Tok.isNot(tok::r_paren)) { while (1) { @@ -3583,7 +3583,7 @@ ExprResult Parser::ParseObjCSelectorExpression(SourceLocation AtLoc) { if (Tok.is(tok::r_paren)) break; - + if (Tok.is(tok::code_completion)) { Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents); cutOffParsing(); @@ -3611,12 +3611,12 @@ ExprResult Parser::ParseObjCSelectorExpression(SourceLocation AtLoc) { void Parser::ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod) { // MCDecl might be null due to error in method or c-function prototype, etc. Decl *MCDecl = LM.D; - bool skip = MCDecl && + bool skip = MCDecl && ((parseMethod && !Actions.isObjCMethodDecl(MCDecl)) || (!parseMethod && Actions.isObjCMethodDecl(MCDecl))); if (skip) return; - + // Save the current token position. SourceLocation OrigLoc = Tok.getLocation(); @@ -3636,15 +3636,15 @@ void Parser::ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod) { // Consume the previously pushed token. ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true); - - assert(Tok.isOneOf(tok::l_brace, tok::kw_try, tok::colon) && + + assert(Tok.isOneOf(tok::l_brace, tok::kw_try, tok::colon) && "Inline objective-c method not starting with '{' or 'try' or ':'"); // Enter a scope for the method or c-function body. ParseScope BodyScope(this, (parseMethod ? Scope::ObjCMethodScope : 0) | Scope::FnScope | Scope::DeclScope | Scope::CompoundStmtScope); - // Tell the actions module that we have entered a method or c-function definition + // Tell the actions module that we have entered a method or c-function definition // with the specified Declarator for the method/function. if (parseMethod) Actions.ActOnStartOfObjCMethodDef(getCurScope(), MCDecl); diff --git a/lib/Parse/ParsePragma.cpp b/lib/Parse/ParsePragma.cpp index 9a25f9c25c03..07f48e0779dc 100644 --- a/lib/Parse/ParsePragma.cpp +++ b/lib/Parse/ParsePragma.cpp @@ -1492,7 +1492,7 @@ void Parser::HandlePragmaAttribute() { // #pragma GCC visibility comes in two variants: // 'push' '(' [visibility] ')' // 'pop' -void PragmaGCCVisibilityHandler::HandlePragma(Preprocessor &PP, +void PragmaGCCVisibilityHandler::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &VisTok) { SourceLocation VisLoc = VisTok.getLocation(); @@ -1552,7 +1552,7 @@ void PragmaGCCVisibilityHandler::HandlePragma(Preprocessor &PP, // pack '(' [integer] ')' // pack '(' 'show' ')' // pack '(' ('push' | 'pop') [',' identifier] [, integer] ')' -void PragmaPackHandler::HandlePragma(Preprocessor &PP, +void PragmaPackHandler::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &PackTok) { SourceLocation PackLoc = PackTok.getLocation(); @@ -1663,7 +1663,7 @@ void PragmaPackHandler::HandlePragma(Preprocessor &PP, // #pragma ms_struct on // #pragma ms_struct off -void PragmaMSStructHandler::HandlePragma(Preprocessor &PP, +void PragmaMSStructHandler::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &MSStructTok) { PragmaMSStructKind Kind = PMSST_OFF; @@ -1686,7 +1686,7 @@ void PragmaMSStructHandler::HandlePragma(Preprocessor &PP, PP.Diag(Tok.getLocation(), diag::warn_pragma_ms_struct); return; } - + if (Tok.isNot(tok::eod)) { PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) << "ms_struct"; @@ -1817,20 +1817,20 @@ static void ParseAlignPragma(Preprocessor &PP, Token &FirstTok, PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true); } -void PragmaAlignHandler::HandlePragma(Preprocessor &PP, +void PragmaAlignHandler::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &AlignTok) { ParseAlignPragma(PP, AlignTok, /*IsOptions=*/false); } -void PragmaOptionsHandler::HandlePragma(Preprocessor &PP, +void PragmaOptionsHandler::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &OptionsTok) { ParseAlignPragma(PP, OptionsTok, /*IsOptions=*/true); } // #pragma unused(identifier) -void PragmaUnusedHandler::HandlePragma(Preprocessor &PP, +void PragmaUnusedHandler::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &UnusedTok) { // FIXME: Should we be expanding macros here? My guess is no. @@ -1911,7 +1911,7 @@ void PragmaUnusedHandler::HandlePragma(Preprocessor &PP, // #pragma weak identifier // #pragma weak identifier '=' identifier -void PragmaWeakHandler::HandlePragma(Preprocessor &PP, +void PragmaWeakHandler::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &WeakTok) { SourceLocation WeakLoc = WeakTok.getLocation(); @@ -1970,7 +1970,7 @@ void PragmaWeakHandler::HandlePragma(Preprocessor &PP, } // #pragma redefine_extname identifier identifier -void PragmaRedefineExtnameHandler::HandlePragma(Preprocessor &PP, +void PragmaRedefineExtnameHandler::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &RedefToken) { SourceLocation RedefLoc = RedefToken.getLocation(); @@ -2015,7 +2015,7 @@ void PragmaRedefineExtnameHandler::HandlePragma(Preprocessor &PP, void -PragmaFPContractHandler::HandlePragma(Preprocessor &PP, +PragmaFPContractHandler::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &Tok) { tok::OnOffSwitch OOS; @@ -2033,8 +2033,8 @@ PragmaFPContractHandler::HandlePragma(Preprocessor &PP, PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true); } -void -PragmaOpenCLExtensionHandler::HandlePragma(Preprocessor &PP, +void +PragmaOpenCLExtensionHandler::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &Tok) { PP.LexUnexpandedToken(Tok); @@ -2095,7 +2095,7 @@ PragmaOpenCLExtensionHandler::HandlePragma(Preprocessor &PP, PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true); if (PP.getPPCallbacks()) - PP.getPPCallbacks()->PragmaOpenCLExtension(NameLoc, Ext, + PP.getPPCallbacks()->PragmaOpenCLExtension(NameLoc, Ext, StateLoc, State); } @@ -2523,7 +2523,7 @@ void PragmaCommentHandler::HandlePragma(Preprocessor &PP, // #pragma clang optimize off // #pragma clang optimize on -void PragmaOptimizeHandler::HandlePragma(Preprocessor &PP, +void PragmaOptimizeHandler::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &FirstToken) { Token Tok; @@ -2549,7 +2549,7 @@ void PragmaOptimizeHandler::HandlePragma(Preprocessor &PP, return; } PP.Lex(Tok); - + if (Tok.isNot(tok::eod)) { PP.Diag(Tok.getLocation(), diag::err_pragma_optimize_extra_argument) << PP.getSpelling(Tok); diff --git a/lib/Parse/ParseStmtAsm.cpp b/lib/Parse/ParseStmtAsm.cpp index 290723c29532..9b96c5150e56 100644 --- a/lib/Parse/ParseStmtAsm.cpp +++ b/lib/Parse/ParseStmtAsm.cpp @@ -7,7 +7,7 @@ // //===----------------------------------------------------------------------===// // -// This file implements parsing for GCC and Microsoft inline assembly. +// This file implements parsing for GCC and Microsoft inline assembly. // //===----------------------------------------------------------------------===// diff --git a/lib/Parse/ParseTemplate.cpp b/lib/Parse/ParseTemplate.cpp index f7a69c482e17..063f7ccea320 100644 --- a/lib/Parse/ParseTemplate.cpp +++ b/lib/Parse/ParseTemplate.cpp @@ -27,7 +27,7 @@ Decl *Parser::ParseDeclarationStartingWithTemplate( DeclaratorContext Context, SourceLocation &DeclEnd, ParsedAttributes &AccessAttrs, AccessSpecifier AS) { ObjCDeclContextSwitch ObjCDC(*this); - + if (Tok.is(tok::kw_template) && NextToken().isNot(tok::less)) { return ParseExplicitInstantiation(Context, SourceLocation(), ConsumeToken(), DeclEnd, AccessAttrs, AS); @@ -360,7 +360,7 @@ bool Parser::ParseTemplateParameterList(const unsigned Depth, SmallVectorImpl<NamedDecl*> &TemplateParams) { while (1) { - + if (NamedDecl *TmpParam = ParseTemplateParameter(Depth, TemplateParams.size())) { TemplateParams.push_back(TmpParam); @@ -403,23 +403,23 @@ bool Parser::isStartOfTemplateTypeParameter() { case tok::greatergreater: case tok::ellipsis: return true; - + case tok::identifier: - // This may be either a type-parameter or an elaborated-type-specifier. + // This may be either a type-parameter or an elaborated-type-specifier. // We have to look further. break; - + default: return false; } - + switch (GetLookAheadToken(2).getKind()) { case tok::equal: case tok::comma: case tok::greater: case tok::greatergreater: return true; - + default: return false; } @@ -464,7 +464,7 @@ bool Parser::isStartOfTemplateTypeParameter() { /// 'class' identifier[opt] '=' type-id /// 'typename' ...[opt] identifier[opt] /// 'typename' identifier[opt] '=' type-id -/// 'template' '<' template-parameter-list '>' +/// 'template' '<' template-parameter-list '>' /// 'class' ...[opt] identifier[opt] /// 'template' '<' template-parameter-list '>' 'class' identifier[opt] /// = id-expression @@ -617,7 +617,7 @@ Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) { getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_variadic_templates : diag::ext_variadic_templates); - + // Get the identifier, if given. SourceLocation NameLoc; IdentifierInfo *ParamName = nullptr; @@ -652,16 +652,16 @@ Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) { if (TryConsumeToken(tok::equal, EqualLoc)) { DefaultArg = ParseTemplateTemplateArgument(); if (DefaultArg.isInvalid()) { - Diag(Tok.getLocation(), + Diag(Tok.getLocation(), diag::err_default_template_template_parameter_not_template); SkipUntil(tok::comma, tok::greater, tok::greatergreater, StopAtSemi | StopBeforeMatch); } } - + return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc, - ParamList, EllipsisLoc, - ParamName, NameLoc, Depth, + ParamList, EllipsisLoc, + ParamName, NameLoc, Depth, Position, EqualLoc, DefaultArg); } @@ -714,8 +714,8 @@ Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) { } // Create the parameter. - return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl, - Depth, Position, EqualLoc, + return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl, + Depth, Position, EqualLoc, DefaultArg.get()); } @@ -1045,7 +1045,7 @@ bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK, // Build a template-id annotation token that can be processed // later. Tok.setKind(tok::annot_template_id); - + IdentifierInfo *TemplateII = TemplateName.getKind() == UnqualifiedIdKind::IK_Identifier ? TemplateName.Identifier @@ -1059,7 +1059,7 @@ bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK, TemplateIdAnnotation *TemplateId = TemplateIdAnnotation::Create( SS, TemplateKWLoc, TemplateNameLoc, TemplateII, OpKind, Template, TNK, LAngleLoc, RAngleLoc, TemplateArgs, TemplateIds); - + Tok.setAnnotationValue(TemplateId); if (TemplateKWLoc.isValid()) Tok.setLocation(TemplateKWLoc); @@ -1135,13 +1135,13 @@ ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() { // C++0x [temp.arg.template]p1: // A template-argument for a template template-parameter shall be the name // of a class template or an alias template, expressed as id-expression. - // + // // We parse an id-expression that refers to a class template or alias // template. The grammar we parse is: // // nested-name-specifier[opt] template[opt] identifier ...[opt] // - // followed by a token that terminates a template argument, such as ',', + // followed by a token that terminates a template argument, such as ',', // '>', or (in some cases) '>>'. CXXScopeSpec SS; // nested-name-specifier, if present ParseOptionalCXXScopeSpecifier(SS, nullptr, @@ -1150,10 +1150,10 @@ ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() { ParsedTemplateArgument Result; SourceLocation EllipsisLoc; if (SS.isSet() && Tok.is(tok::kw_template)) { - // Parse the optional 'template' keyword following the + // Parse the optional 'template' keyword following the // nested-name-specifier. SourceLocation TemplateKWLoc = ConsumeToken(); - + if (Tok.is(tok::identifier)) { // We appear to have a dependent template name. UnqualifiedId Name; @@ -1191,16 +1191,16 @@ ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() { /*EnteringContext=*/false, Template, MemberOfUnknownSpecialization); if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) { // We have an id-expression that refers to a class template or - // (C++0x) alias template. + // (C++0x) alias template. Result = ParsedTemplateArgument(SS, Template, Name.StartLocation); } } } - + // If this is a pack expansion, build it as such. if (EllipsisLoc.isValid() && !Result.isInvalid()) Result = Actions.ActOnPackExpansion(Result, EllipsisLoc); - + return Result; } @@ -1230,7 +1230,7 @@ ParsedTemplateArgument Parser::ParseTemplateArgument() { /*Range=*/nullptr, DeclaratorContext::TemplateArgContext); return Actions.ActOnTemplateTypeArgument(TypeArg); } - + // Try to parse a template template argument. { TentativeParsingAction TPA(*this); @@ -1241,35 +1241,35 @@ ParsedTemplateArgument Parser::ParseTemplateArgument() { TPA.Commit(); return TemplateTemplateArgument; } - + // Revert this tentative parse to parse a non-type template argument. TPA.Revert(); } - - // Parse a non-type template argument. + + // Parse a non-type template argument. SourceLocation Loc = Tok.getLocation(); ExprResult ExprArg = ParseConstantExpressionInExprEvalContext(MaybeTypeCast); if (ExprArg.isInvalid() || !ExprArg.get()) return ParsedTemplateArgument(); - return ParsedTemplateArgument(ParsedTemplateArgument::NonType, + return ParsedTemplateArgument(ParsedTemplateArgument::NonType, ExprArg.get(), Loc); } -/// Determine whether the current tokens can only be parsed as a -/// template argument list (starting with the '<') and never as a '<' +/// Determine whether the current tokens can only be parsed as a +/// template argument list (starting with the '<') and never as a '<' /// expression. bool Parser::IsTemplateArgumentList(unsigned Skip) { struct AlwaysRevertAction : TentativeParsingAction { AlwaysRevertAction(Parser &P) : TentativeParsingAction(P) { } ~AlwaysRevertAction() { Revert(); } } Tentative(*this); - + while (Skip) { ConsumeAnyToken(); --Skip; } - + // '<' if (!TryConsumeToken(tok::less)) return false; @@ -1277,11 +1277,11 @@ bool Parser::IsTemplateArgumentList(unsigned Skip) { // An empty template argument list. if (Tok.is(tok::greater)) return true; - + // See whether we have declaration specifiers, which indicate a type. while (isCXXDeclarationSpecifier() == TPResult::True) ConsumeAnyToken(); - + // If we have a '>' or a ',' then this is a template argument list. return Tok.isOneOf(tok::greater, tok::comma); } @@ -1294,7 +1294,7 @@ bool Parser::IsTemplateArgumentList(unsigned Skip) { /// template-argument-list ',' template-argument bool Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) { - + ColonProtectionRAIIObject ColonProtection(*this, false); do { @@ -1310,7 +1310,7 @@ Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) { // Save this template argument. TemplateArgs.push_back(Arg); - + // If the next token is a comma, consume it and keep reading // arguments. } while (TryConsumeToken(tok::comma)); diff --git a/lib/Parse/ParseTentative.cpp b/lib/Parse/ParseTentative.cpp index 0603d8e75eea..dfd1f8c3b2e6 100644 --- a/lib/Parse/ParseTentative.cpp +++ b/lib/Parse/ParseTentative.cpp @@ -80,10 +80,10 @@ bool Parser::isCXXDeclarationStatement() { /// (if AllowForRangeDecl specified) /// for ( for-range-declaration : for-range-initializer ) statement /// -/// for-range-declaration: +/// for-range-declaration: /// decl-specifier-seq declarator /// decl-specifier-seq ref-qualifier[opt] '[' identifier-list ']' -/// +/// /// In any of the above cases there can be a preceding attribute-specifier-seq, /// but the caller is expected to handle that. bool Parser::isCXXSimpleDeclaration(bool AllowForRangeDecl) { @@ -132,7 +132,7 @@ bool Parser::isCXXSimpleDeclaration(bool AllowForRangeDecl) { // Ok, we have a simple-type-specifier/typename-specifier followed by a '(', // or an identifier which doesn't resolve as anything. We need tentative // parsing... - + { RevertingTentativeParsingAction PA(*this); TPR = TryParseSimpleDeclaration(AllowForRangeDecl); @@ -236,7 +236,7 @@ Parser::TPResult Parser::TryConsumeDeclarationSpecifier() { /// /// (if AllowForRangeDecl specified) /// for ( for-range-declaration : for-range-initializer ) statement -/// for-range-declaration: +/// for-range-declaration: /// attribute-specifier-seqopt type-specifier-seq declarator /// Parser::TPResult Parser::TryParseSimpleDeclaration(bool AllowForRangeDecl) { @@ -964,7 +964,7 @@ Parser::TPResult Parser::TryParseDeclarator(bool mayBeAbstract, return TPResult::Ambiguous; } -Parser::TPResult +Parser::TPResult Parser::isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind) { switch (Kind) { // Obviously starts an expression. @@ -1026,7 +1026,7 @@ Parser::isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind) { case tok::kw_##Spelling: #include "clang/Basic/TokenKinds.def" return TPResult::True; - + // Obviously starts a type-specifier-seq: case tok::kw_char: case tok::kw_const: @@ -1084,7 +1084,7 @@ Parser::isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind) { default: break; } - + return TPResult::Ambiguous; } @@ -1338,7 +1338,7 @@ Parser::isCXXDeclarationSpecifier(Parser::TPResult BracedCastResult, // Debugger support case tok::kw___unknown_anytype: - + // type-specifier: // simple-type-specifier // class-specifier @@ -1395,7 +1395,7 @@ Parser::isCXXDeclarationSpecifier(Parser::TPResult BracedCastResult, // Borland case tok::kw___pascal: return TPResult::True; - + // AltiVec case tok::kw___vector: return TPResult::True; @@ -1510,24 +1510,24 @@ Parser::isCXXDeclarationSpecifier(Parser::TPResult BracedCastResult, // Tentatively parse the protocol qualifiers. RevertingTentativeParsingAction PA(*this); ConsumeAnyToken(); // The type token - + TPResult TPR = TryParseProtocolQualifiers(); bool isFollowedByParen = Tok.is(tok::l_paren); bool isFollowedByBrace = Tok.is(tok::l_brace); - + if (TPR == TPResult::Error) return TPResult::Error; - + if (isFollowedByParen) return TPResult::Ambiguous; if (getLangOpts().CPlusPlus11 && isFollowedByBrace) return BracedCastResult; - + return TPResult::True; } LLVM_FALLTHROUGH; - + case tok::kw_char: case tok::kw_wchar_t: case tok::kw_char8_t: @@ -1562,7 +1562,7 @@ Parser::isCXXDeclarationSpecifier(Parser::TPResult BracedCastResult, if (isStartOfObjCClassMessageMissingOpenBracket()) return TPResult::False; - + return TPResult::True; // GNU typeof support. @@ -1681,18 +1681,18 @@ Parser::TPResult Parser::TryParseProtocolQualifiers() { if (Tok.isNot(tok::identifier)) return TPResult::Error; ConsumeToken(); - + if (Tok.is(tok::comma)) { ConsumeToken(); continue; } - + if (Tok.is(tok::greater)) { ConsumeToken(); return TPResult::Ambiguous; } } while (false); - + return TPResult::Error; } @@ -1910,7 +1910,7 @@ Parser::TPResult Parser::TryParseFunctionDeclarator() { // ref-qualifier[opt] if (Tok.isOneOf(tok::amp, tok::ampamp)) ConsumeToken(); - + // exception-specification if (Tok.is(tok::kw_throw)) { ConsumeToken(); diff --git a/lib/Parse/Parser.cpp b/lib/Parse/Parser.cpp index 7a0b29cbae86..c3085654f529 100644 --- a/lib/Parse/Parser.cpp +++ b/lib/Parse/Parser.cpp @@ -41,7 +41,7 @@ public: } // end anonymous namespace IdentifierInfo *Parser::getSEHExceptKeyword() { - // __except is accepted as a (contextual) keyword + // __except is accepted as a (contextual) keyword if (!Ident__except && (getLangOpts().MicrosoftExt || getLangOpts().Borland)) Ident__except = PP.getIdentifierInfo("__except"); @@ -50,7 +50,7 @@ IdentifierInfo *Parser::getSEHExceptKeyword() { Parser::Parser(Preprocessor &pp, Sema &actions, bool skipFunctionBodies) : PP(pp), Actions(actions), Diags(PP.getDiagnostics()), - GreaterThanIsOperator(true), ColonIsSacred(false), + GreaterThanIsOperator(true), ColonIsSacred(false), InMessageExpression(false), TemplateParameterDepth(0), ParsingInObjCContainer(false) { SkipFunctionBodies = pp.isCodeCompletionEnabled() || skipFunctionBodies; @@ -161,8 +161,8 @@ bool Parser::ExpectAndConsumeSemi(unsigned DiagID) { handleUnexpectedCodeCompletionToken(); return false; } - - if ((Tok.is(tok::r_paren) || Tok.is(tok::r_square)) && + + if ((Tok.is(tok::r_paren) || Tok.is(tok::r_square)) && NextToken().is(tok::semi)) { Diag(Tok, diag::err_extraneous_token_before_semi) << PP.getSpelling(Tok) @@ -171,7 +171,7 @@ bool Parser::ExpectAndConsumeSemi(unsigned DiagID) { ConsumeToken(); // The ';'. return false; } - + return ExpectAndConsume(tok::semi, DiagID); } @@ -291,7 +291,7 @@ bool Parser::SkipUntil(ArrayRef<tok::TokenKind> Toks, SkipUntilFlags Flags) { if (!HasFlagsSet(Flags, StopAtCodeCompletion)) handleUnexpectedCodeCompletionToken(); return false; - + case tok::l_paren: // Recursively skip properly-nested parens. ConsumeParen(); @@ -796,17 +796,17 @@ Parser::ParseExternalDeclaration(ParsedAttributesWithRange &attrs, return ParseDeclaration(DeclaratorContext::FileContext, DeclEnd, attrs); } goto dont_know; - + case tok::kw_inline: if (getLangOpts().CPlusPlus) { tok::TokenKind NextKind = NextToken().getKind(); - + // Inline namespaces. Allowed as an extension even in C++03. if (NextKind == tok::kw_namespace) { SourceLocation DeclEnd; return ParseDeclaration(DeclaratorContext::FileContext, DeclEnd, attrs); } - + // Parse (then ignore) 'inline' prior to a template instantiation. This is // a GCC extension that we intentionally do not support. if (NextKind == tok::kw_template) { @@ -867,7 +867,7 @@ bool Parser::isDeclarationAfterDeclarator() { if (KW.is(tok::kw_default) || KW.is(tok::kw_delete)) return false; } - + return Tok.is(tok::equal) || // int X()= -> not a function def Tok.is(tok::comma) || // int X(), -> not a function def Tok.is(tok::semi) || // int X(); -> not a function def @@ -883,17 +883,17 @@ bool Parser::isStartOfFunctionDefinition(const ParsingDeclarator &Declarator) { assert(Declarator.isFunctionDeclarator() && "Isn't a function declarator"); if (Tok.is(tok::l_brace)) // int X() {} return true; - + // Handle K&R C argument lists: int X(f) int f; {} if (!getLangOpts().CPlusPlus && - Declarator.getFunctionTypeInfo().isKNRPrototype()) + Declarator.getFunctionTypeInfo().isKNRPrototype()) return isDeclarationSpecifier(); if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) { const Token &KW = NextToken(); return KW.is(tok::kw_default) || KW.is(tok::kw_delete); } - + return Tok.is(tok::colon) || // X() : Base() {} (used for ctors) Tok.is(tok::kw_try); // X() try { ... } } @@ -947,7 +947,7 @@ Parser::ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs, default: llvm_unreachable("we only expect to get the length of the class/struct/union/enum"); } - + }; // Suggest correct location to fix '[[attrib]] struct' to 'struct [[attrib]]' SourceLocation CorrectLocationForAttributes = @@ -1072,7 +1072,7 @@ Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D, // We should have either an opening brace or, in a C++ constructor, // we may have a colon. - if (Tok.isNot(tok::l_brace) && + if (Tok.isNot(tok::l_brace) && (!getLangOpts().CPlusPlus || (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) && Tok.isNot(tok::equal)))) { @@ -1128,10 +1128,10 @@ Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D, } return DP; } - else if (CurParsedObjCImpl && + else if (CurParsedObjCImpl && !TemplateInfo.TemplateParams && (Tok.is(tok::l_brace) || Tok.is(tok::kw_try) || - Tok.is(tok::colon)) && + Tok.is(tok::colon)) && Actions.CurContext->isTranslationUnit()) { ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope | Scope::CompoundStmtScope); @@ -1171,7 +1171,7 @@ Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D, // Break out of the ParsingDeclarator context before we parse the body. D.complete(Res); - + // Break out of the ParsingDeclSpec context, too. This const_cast is // safe because we're always the sole owner. D.getMutableDeclSpec().abort(); @@ -1710,7 +1710,7 @@ bool Parser::TryAnnotateTypeOrScopeToken() { TypeResult Ty; if (Tok.is(tok::identifier)) { // FIXME: check whether the next token is '<', first! - Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS, + Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS, *Tok.getIdentifierInfo(), Tok.getLocation()); } else if (Tok.is(tok::annot_template_id)) { @@ -1926,14 +1926,14 @@ SourceLocation Parser::handleUnexpectedCodeCompletionToken() { cutOffParsing(); return PrevTokLocation; } - + if (S->getFlags() & Scope::ClassScope) { Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Class); cutOffParsing(); return PrevTokLocation; } } - + Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Namespace); cutOffParsing(); return PrevTokLocation; @@ -1953,7 +1953,7 @@ void Parser::CodeCompleteMacroName(bool IsDefinition) { Actions.CodeCompletePreprocessorMacroName(IsDefinition); } -void Parser::CodeCompletePreprocessorExpression() { +void Parser::CodeCompletePreprocessorExpression() { Actions.CodeCompletePreprocessorExpression(); } @@ -1976,11 +1976,11 @@ bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) { BalancedDelimiterTracker T(*this, tok::l_paren); if (T.consumeOpen()) { - Diag(Tok, diag::err_expected_lparen_after) + Diag(Tok, diag::err_expected_lparen_after) << (Result.IsIfExists? "__if_exists" : "__if_not_exists"); return true; } - + // Parse nested-name-specifier. if (getLangOpts().CPlusPlus) ParseOptionalCXXScopeSpecifier(Result.SS, nullptr, @@ -2004,7 +2004,7 @@ bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) { if (T.consumeClose()) return true; - + // Check if the symbol exists. switch (Actions.CheckMicrosoftIfExistsSymbol(getCurScope(), Result.KeywordLoc, Result.IsIfExists, Result.SS, @@ -2020,7 +2020,7 @@ bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) { case Sema::IER_Dependent: Result.Behavior = IEB_Dependent; break; - + case Sema::IER_Error: return true; } @@ -2032,7 +2032,7 @@ void Parser::ParseMicrosoftIfExistsExternalDeclaration() { IfExistsCondition Result; if (ParseMicrosoftIfExistsCondition(Result)) return; - + BalancedDelimiterTracker Braces(*this, tok::l_brace); if (Braces.consumeOpen()) { Diag(Tok, diag::err_expected) << tok::l_brace; @@ -2043,10 +2043,10 @@ void Parser::ParseMicrosoftIfExistsExternalDeclaration() { case IEB_Parse: // Parse declarations below. break; - + case IEB_Dependent: llvm_unreachable("Cannot have a dependent external declaration"); - + case IEB_Skip: Braces.skipToEnd(); return; @@ -2109,7 +2109,7 @@ Parser::DeclGroupPtrTy Parser::ParseModuleDecl() { /// Parse a module import declaration. This is essentially the same for /// Objective-C and the C++ Modules TS, except for the leading '@' (in ObjC) /// and the trailing optional attributes (in C++). -/// +/// /// [ObjC] @import declaration: /// '@' 'import' module-name ';' /// [ModTS] module-import-declaration: @@ -2121,7 +2121,7 @@ Decl *Parser::ParseModuleImport(SourceLocation AtLoc) { bool IsObjCAtImport = Tok.isObjCAtKeyword(tok::objc_import); SourceLocation ImportLoc = ConsumeToken(); SourceLocation StartLoc = AtLoc.isInvalid() ? ImportLoc : AtLoc; - + SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path; if (ParseModuleName(ImportLoc, Path, /*IsImport*/true)) return nullptr; @@ -2174,12 +2174,12 @@ bool Parser::ParseModuleName( cutOffParsing(); return true; } - + Diag(Tok, diag::err_module_expected_ident) << IsImport; SkipUntil(tok::semi); return true; } - + // Record this part of the module path. Path.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation())); ConsumeToken(); @@ -2258,7 +2258,7 @@ bool BalancedDelimiterTracker::expectAndConsume(unsigned DiagID, if (getDepth() < P.getLangOpts().BracketDepth) return false; - + return diagnoseOverflow(); } diff --git a/lib/Rewrite/DeltaTree.cpp b/lib/Rewrite/DeltaTree.cpp index 1dfc26cc918f..06f3b4fb4a66 100644 --- a/lib/Rewrite/DeltaTree.cpp +++ b/lib/Rewrite/DeltaTree.cpp @@ -50,7 +50,7 @@ namespace { return Delta; } }; - + /// DeltaTreeNode - The common part of all nodes. /// class DeltaTreeNode { @@ -59,7 +59,7 @@ namespace { DeltaTreeNode *LHS, *RHS; SourceDelta Split; }; - + private: friend class DeltaTreeInteriorNode; diff --git a/lib/Rewrite/HTMLRewrite.cpp b/lib/Rewrite/HTMLRewrite.cpp index d93961f3582e..12d7a16a2fc8 100644 --- a/lib/Rewrite/HTMLRewrite.cpp +++ b/lib/Rewrite/HTMLRewrite.cpp @@ -49,7 +49,7 @@ void html::HighlightRange(Rewriter &R, SourceLocation B, SourceLocation E, const char *BufferStart = SM.getBufferData(FID, &Invalid).data(); if (Invalid) return; - + HighlightRange(R.getEditBuffer(FID), BOffset, EOffset, BufferStart, StartTag, EndTag); } diff --git a/lib/Rewrite/Rewriter.cpp b/lib/Rewrite/Rewriter.cpp index cb59a161fe68..a5421ec807b7 100644 --- a/lib/Rewrite/Rewriter.cpp +++ b/lib/Rewrite/Rewriter.cpp @@ -88,7 +88,7 @@ void RewriteBuffer::RemoveText(unsigned OrigOffset, unsigned Size, } ++posI; } - + unsigned lineSize = 0; posI = curLineStart; while (posI != end() && isWhitespaceExceptNL(*posI)) { @@ -353,10 +353,10 @@ bool Rewriter::IncreaseIndentation(CharSourceRange range, unsigned parentLineNo = SourceMgr->getLineNumber(FID, parentOff) - 1; unsigned startLineNo = SourceMgr->getLineNumber(FID, StartOff) - 1; unsigned endLineNo = SourceMgr->getLineNumber(FID, EndOff) - 1; - + const SrcMgr::ContentCache * Content = SourceMgr->getSLocEntry(FID).getFile().getContentCache(); - + // Find where the lines start. unsigned parentLineOffs = Content->SourceLineCache[parentLineNo]; unsigned startLineOffs = Content->SourceLineCache[startLineNo]; diff --git a/lib/Sema/AnalysisBasedWarnings.cpp b/lib/Sema/AnalysisBasedWarnings.cpp index 82d9df25d934..ed240f4ed292 100644 --- a/lib/Sema/AnalysisBasedWarnings.cpp +++ b/lib/Sema/AnalysisBasedWarnings.cpp @@ -90,7 +90,7 @@ namespace { } S.Diag(L, diag) << R1 << R2; - + SourceLocation Open = SilenceableCondVal.getBegin(); if (Open.isValid()) { SourceLocation Close = SilenceableCondVal.getEnd(); @@ -330,7 +330,7 @@ static void EmitDiagForCXXThrowInNonThrowingFunc(Sema &S, SourceLocation OpLoc, S.Diag(FD->getLocation(), diag::note_throw_in_dtor) << !isa<CXXDestructorDecl>(FD) << !Ty->hasExceptionSpec() << FD->getExceptionSpecSourceRange(); - } else + } else S.Diag(FD->getLocation(), diag::note_throw_in_function) << FD->getExceptionSpecSourceRange(); } @@ -525,18 +525,18 @@ struct CheckFallThroughDiagnostics { bool isVirtualMethod = false; if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func)) isVirtualMethod = Method->isVirtual(); - + // Don't suggest that template instantiations be marked "noreturn" bool isTemplateInstantiation = false; if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func)) isTemplateInstantiation = Function->isTemplateInstantiation(); - + if (!isVirtualMethod && !isTemplateInstantiation) D.diag_NeverFallThroughOrReturn = diag::warn_suggest_noreturn_function; else D.diag_NeverFallThroughOrReturn = 0; - + D.funMode = Function; return D; } @@ -1226,7 +1226,7 @@ static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC, bool PerFunction) { // Only perform this analysis when using [[]] attributes. There is no good // workflow for this warning when not using C++11. There is no good way to - // silence the warning (no attribute is available) unless we are using + // silence the warning (no attribute is available) unless we are using // [[]] attributes. One could use pragmas to silence the warning, but as a // general solution that is gross and not in the spirit of this warning. // @@ -1492,7 +1492,7 @@ class UninitValsDiagReporter : public UninitVariablesHandler { // order of diagnostics when calling flushDiagnostics(). typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap; UsesMap uses; - + public: UninitValsDiagReporter(Sema &S) : S(S) {} ~UninitValsDiagReporter() override { flushDiagnostics(); } @@ -1508,11 +1508,11 @@ public: const UninitUse &use) override { getUses(vd).getPointer()->push_back(use); } - + void handleSelfInit(const VarDecl *vd) override { getUses(vd).setInt(true); } - + void flushDiagnostics() { for (const auto &P : uses) { const VarDecl *vd = P.first; @@ -1521,7 +1521,7 @@ public: UsesVec *vec = V.getPointer(); bool hasSelfInit = V.getInt(); - // Specially handle the case where we have uses of an uninitialized + // Specially handle the case where we have uses of an uninitialized // variable, but the root cause is an idiomatic self-init. We want // to report the diagnostic at the self-init since that is the root cause. if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec)) @@ -1551,7 +1551,7 @@ public: break; } } - + // Release the uses vector. delete vec; } @@ -1865,10 +1865,10 @@ namespace clang { namespace consumed { namespace { class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase { - + Sema &S; DiagList Warnings; - + public: ConsumedWarningsHandler(Sema &S) : S(S) {} @@ -1889,28 +1889,28 @@ public: Warnings.emplace_back(std::move(Warning), OptionalNotes()); } - + void warnParamReturnTypestateMismatch(SourceLocation Loc, StringRef VariableName, StringRef ExpectedState, StringRef ObservedState) override { - + PartialDiagnosticAt Warning(Loc, S.PDiag( diag::warn_param_return_typestate_mismatch) << VariableName << ExpectedState << ObservedState); Warnings.emplace_back(std::move(Warning), OptionalNotes()); } - + void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState, StringRef ObservedState) override { - + PartialDiagnosticAt Warning(Loc, S.PDiag( diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState); Warnings.emplace_back(std::move(Warning), OptionalNotes()); } - + void warnReturnTypestateForUnconsumableType(SourceLocation Loc, StringRef TypeName) override { PartialDiagnosticAt Warning(Loc, S.PDiag( @@ -1918,28 +1918,28 @@ public: Warnings.emplace_back(std::move(Warning), OptionalNotes()); } - + void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState, StringRef ObservedState) override { - + PartialDiagnosticAt Warning(Loc, S.PDiag( diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState); Warnings.emplace_back(std::move(Warning), OptionalNotes()); } - + void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State, SourceLocation Loc) override { - + PartialDiagnosticAt Warning(Loc, S.PDiag( diag::warn_use_of_temp_in_invalid_state) << MethodName << State); Warnings.emplace_back(std::move(Warning), OptionalNotes()); } - + void warnUseInInvalidState(StringRef MethodName, StringRef VariableName, StringRef State, SourceLocation Loc) override { - + PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_in_invalid_state) << MethodName << VariableName << State); @@ -2027,7 +2027,7 @@ AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P, flushDiagnostics(S, fscope); return; } - + const Stmt *Body = D->getBody(); assert(Body); @@ -2113,7 +2113,7 @@ AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P, if (!analyzed) flushDiagnostics(S, fscope); } - + // Warning: check missing 'return' if (P.enableCheckFallThrough) { const CheckFallThroughDiagnostics &CD = diff --git a/lib/Sema/CMakeLists.txt b/lib/Sema/CMakeLists.txt index bad42a2ce252..3d21d79f2b85 100644 --- a/lib/Sema/CMakeLists.txt +++ b/lib/Sema/CMakeLists.txt @@ -5,6 +5,7 @@ set(LLVM_LINK_COMPONENTS if (MSVC) set_source_files_properties(SemaDeclAttr.cpp PROPERTIES COMPILE_FLAGS /bigobj) set_source_files_properties(SemaExpr.cpp PROPERTIES COMPILE_FLAGS /bigobj) + set_source_files_properties(SemaTemplate.cpp PROPERTIES COMPILE_FLAGS /bigobj) endif() add_clang_library(clangSema diff --git a/lib/Sema/CodeCompleteConsumer.cpp b/lib/Sema/CodeCompleteConsumer.cpp index 9c4d315a692f..8af54b993932 100644 --- a/lib/Sema/CodeCompleteConsumer.cpp +++ b/lib/Sema/CodeCompleteConsumer.cpp @@ -49,7 +49,7 @@ bool CodeCompletionContext::wantConstructorResults() const { case CCC_ObjCMessageReceiver: case CCC_ParenthesizedExpression: return true; - + case CCC_TopLevel: case CCC_ObjCInterface: case CCC_ObjCImplementation: @@ -164,7 +164,7 @@ StringRef clang::getCompletionKindString(CodeCompletionContext::Kind Kind) { // Code completion string implementation //===----------------------------------------------------------------------===// -CodeCompletionString::Chunk::Chunk(ChunkKind Kind, const char *Text) +CodeCompletionString::Chunk::Chunk(ChunkKind Kind, const char *Text) : Kind(Kind), Text("") { switch (Kind) { case CK_TypedText: @@ -178,7 +178,7 @@ CodeCompletionString::Chunk::Chunk(ChunkKind Kind, const char *Text) case CK_Optional: llvm_unreachable("Optional strings cannot be created from text"); - + case CK_LeftParen: this->Text = "("; break; @@ -190,11 +190,11 @@ CodeCompletionString::Chunk::Chunk(ChunkKind Kind, const char *Text) case CK_LeftBracket: this->Text = "["; break; - + case CK_RightBracket: this->Text = "]"; break; - + case CK_LeftBrace: this->Text = "{"; break; @@ -206,11 +206,11 @@ CodeCompletionString::Chunk::Chunk(ChunkKind Kind, const char *Text) case CK_LeftAngle: this->Text = "<"; break; - + case CK_RightAngle: this->Text = ">"; break; - + case CK_Comma: this->Text = ", "; break; @@ -242,7 +242,7 @@ CodeCompletionString::Chunk::CreateText(const char *Text) { return Chunk(CK_Text, Text); } -CodeCompletionString::Chunk +CodeCompletionString::Chunk CodeCompletionString::Chunk::CreateOptional(CodeCompletionString *Optional) { Chunk Result; Result.Kind = CK_Optional; @@ -250,30 +250,30 @@ CodeCompletionString::Chunk::CreateOptional(CodeCompletionString *Optional) { return Result; } -CodeCompletionString::Chunk +CodeCompletionString::Chunk CodeCompletionString::Chunk::CreatePlaceholder(const char *Placeholder) { return Chunk(CK_Placeholder, Placeholder); } -CodeCompletionString::Chunk +CodeCompletionString::Chunk CodeCompletionString::Chunk::CreateInformative(const char *Informative) { return Chunk(CK_Informative, Informative); } -CodeCompletionString::Chunk +CodeCompletionString::Chunk CodeCompletionString::Chunk::CreateResultType(const char *ResultType) { return Chunk(CK_ResultType, ResultType); } -CodeCompletionString::Chunk +CodeCompletionString::Chunk CodeCompletionString::Chunk::CreateCurrentParameter( const char *CurrentParameter) { return Chunk(CK_CurrentParameter, CurrentParameter); } -CodeCompletionString::CodeCompletionString(const Chunk *Chunks, +CodeCompletionString::CodeCompletionString(const Chunk *Chunks, unsigned NumChunks, - unsigned Priority, + unsigned Priority, CXAvailabilityKind Availability, const char **Annotations, unsigned NumAnnotations, @@ -281,7 +281,7 @@ CodeCompletionString::CodeCompletionString(const Chunk *Chunks, const char *BriefComment) : NumChunks(NumChunks), NumAnnotations(NumAnnotations), Priority(Priority), Availability(Availability), - ParentName(ParentName), BriefComment(BriefComment) { + ParentName(ParentName), BriefComment(BriefComment) { assert(NumChunks <= 0xffff); assert(NumAnnotations <= 0xffff); @@ -308,17 +308,17 @@ const char *CodeCompletionString::getAnnotation(unsigned AnnotationNr) const { std::string CodeCompletionString::getAsString() const { std::string Result; llvm::raw_string_ostream OS(Result); - + for (iterator C = begin(), CEnd = end(); C != CEnd; ++C) { switch (C->Kind) { case CK_Optional: OS << "{#" << C->Optional->getAsString() << "#}"; break; case CK_Placeholder: OS << "<#" << C->Text << "#>"; break; - - case CK_Informative: + + case CK_Informative: case CK_ResultType: - OS << "[#" << C->Text << "#]"; + OS << "[#" << C->Text << "#]"; break; - + case CK_CurrentParameter: OS << "<#" << C->Text << "#>"; break; default: OS << C->Text; break; } @@ -350,7 +350,7 @@ StringRef CodeCompletionTUInfo::getParentName(const DeclContext *DC) { const NamedDecl *ND = dyn_cast<NamedDecl>(DC); if (!ND) return {}; - + // Check whether we've already cached the parent name. StringRef &CachedParentName = ParentNames[DC]; if (!CachedParentName.empty()) @@ -368,7 +368,7 @@ StringRef CodeCompletionTUInfo::getParentName(const DeclContext *DC) { if (ND->getIdentifier()) Contexts.push_back(DC); } - + DC = DC->getParent(); } @@ -382,11 +382,11 @@ StringRef CodeCompletionTUInfo::getParentName(const DeclContext *DC) { else { OS << "::"; } - + const DeclContext *CurDC = Contexts[I-1]; if (const ObjCCategoryImplDecl *CatImpl = dyn_cast<ObjCCategoryImplDecl>(CurDC)) CurDC = CatImpl->getCategoryDecl(); - + if (const ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(CurDC)) { const ObjCInterfaceDecl *Interface = Cat->getClassInterface(); if (!Interface) { @@ -395,13 +395,13 @@ StringRef CodeCompletionTUInfo::getParentName(const DeclContext *DC) { CachedParentName = StringRef((const char *)(uintptr_t)~0U, 0); return {}; } - + OS << Interface->getName() << '(' << Cat->getName() << ')'; } else { OS << cast<NamedDecl>(CurDC)->getName(); } } - + CachedParentName = AllocatorRef->CopyString(OS.str()); } @@ -413,7 +413,7 @@ CodeCompletionString *CodeCompletionBuilder::TakeString() { sizeof(CodeCompletionString) + sizeof(Chunk) * Chunks.size() + sizeof(const char *) * Annotations.size(), alignof(CodeCompletionString)); - CodeCompletionString *Result + CodeCompletionString *Result = new (Mem) CodeCompletionString(Chunks.data(), Chunks.size(), Priority, Availability, Annotations.data(), Annotations.size(), @@ -459,14 +459,14 @@ void CodeCompletionBuilder::AddChunk(CodeCompletionString::ChunkKind CK, void CodeCompletionBuilder::addParentContext(const DeclContext *DC) { if (DC->isTranslationUnit()) return; - + if (DC->isFunctionOrMethod()) return; - + const NamedDecl *ND = dyn_cast<NamedDecl>(DC); if (!ND) return; - + ParentName = getCodeCompletionTUInfo().getParentName(DC); } @@ -492,11 +492,11 @@ CodeCompleteConsumer::OverloadCandidate::getFunctionType() const { switch (Kind) { case CK_Function: return Function->getType()->getAs<FunctionType>(); - + case CK_FunctionTemplate: return FunctionTemplate->getTemplatedDecl()->getType() ->getAs<FunctionType>(); - + case CK_FunctionType: return Type; } @@ -526,13 +526,13 @@ bool PrintingCodeCompleteConsumer::isResultFilteredOut(StringRef Filter, llvm_unreachable("Unknown code completion result Kind."); } -void +void PrintingCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &SemaRef, CodeCompletionContext Context, CodeCompletionResult *Results, unsigned NumResults) { std::stable_sort(Results, Results + NumResults); - + StringRef Filter = SemaRef.getPreprocessor().getCodeCompletionFilter(); // Print the results. @@ -545,7 +545,7 @@ PrintingCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &SemaRef, OS << *Results[I].Declaration; if (Results[I].Hidden) OS << " (Hidden)"; - if (CodeCompletionString *CCS + if (CodeCompletionString *CCS = Results[I].CreateCodeCompletionString(SemaRef, Context, getAllocator(), CCTUInfo, @@ -574,14 +574,14 @@ PrintingCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &SemaRef, } OS << '\n'; break; - + case CodeCompletionResult::RK_Keyword: OS << Results[I].Keyword << '\n'; break; - + case CodeCompletionResult::RK_Macro: OS << Results[I].Macro->getName(); - if (CodeCompletionString *CCS + if (CodeCompletionString *CCS = Results[I].CreateCodeCompletionString(SemaRef, Context, getAllocator(), CCTUInfo, @@ -590,9 +590,9 @@ PrintingCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &SemaRef, } OS << '\n'; break; - + case CodeCompletionResult::RK_Pattern: - OS << "Pattern : " + OS << "Pattern : " << Results[I].Pattern->getAsString() << '\n'; break; } @@ -624,7 +624,7 @@ static std::string getOverloadAsString(const CodeCompletionString &CCS) { return OS.str(); } -void +void PrintingCodeCompleteConsumer::ProcessOverloadCandidates(Sema &SemaRef, unsigned CurrentArg, OverloadCandidate *Candidates, @@ -655,19 +655,19 @@ void CodeCompletionResult::computeCursorKindAndAvailability(bool Accessible) { break; } LLVM_FALLTHROUGH; - + case RK_Declaration: { // Set the availability based on attributes. switch (getDeclAvailability(Declaration)) { case AR_Available: case AR_NotYetIntroduced: - Availability = CXAvailability_Available; + Availability = CXAvailability_Available; break; - + case AR_Deprecated: Availability = CXAvailability_Deprecated; break; - + case AR_Unavailable: Availability = CXAvailability_NotAvailable; break; @@ -676,11 +676,11 @@ void CodeCompletionResult::computeCursorKindAndAvailability(bool Accessible) { if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Declaration)) if (Function->isDeleted()) Availability = CXAvailability_NotAvailable; - + CursorKind = getCursorKindForDecl(Declaration); if (CursorKind == CXCursor_UnexposedDecl) { - // FIXME: Forward declarations of Objective-C classes and protocols - // are not directly exposed, but we want code completion to treat them + // FIXME: Forward declarations of Objective-C classes and protocols + // are not directly exposed, but we want code completion to treat them // like a definition. if (isa<ObjCInterfaceDecl>(Declaration)) CursorKind = CXCursor_ObjCInterfaceDecl; @@ -717,9 +717,9 @@ StringRef CodeCompletionResult::getOrderedName(std::string &Saved) const { // Handle declarations below. break; } - + DeclarationName Name = Declaration->getDeclName(); - + // If the name is a simple identifier (by far the common case), or a // zero-argument selector, just return a reference to that identifier. if (IdentifierInfo *Id = Name.getAsIdentifierInfo()) @@ -728,12 +728,12 @@ StringRef CodeCompletionResult::getOrderedName(std::string &Saved) const { if (IdentifierInfo *Id = Name.getObjCSelector().getIdentifierInfoForSlot(0)) return Id->getName(); - + Saved = Name.getAsString(); return Saved; } - -bool clang::operator<(const CodeCompletionResult &X, + +bool clang::operator<(const CodeCompletionResult &X, const CodeCompletionResult &Y) { std::string XSaved, YSaved; StringRef XStr = X.getOrderedName(XSaved); @@ -741,11 +741,11 @@ bool clang::operator<(const CodeCompletionResult &X, int cmp = XStr.compare_lower(YStr); if (cmp) return cmp < 0; - + // If case-insensitive comparison fails, try case-sensitive comparison. cmp = XStr.compare(YStr); if (cmp) return cmp < 0; - + return false; } diff --git a/lib/Sema/DeclSpec.cpp b/lib/Sema/DeclSpec.cpp index ccca5d37ea39..b22eea2b3642 100644 --- a/lib/Sema/DeclSpec.cpp +++ b/lib/Sema/DeclSpec.cpp @@ -44,7 +44,7 @@ void UnqualifiedId::setConstructorTemplateId(TemplateIdAnnotation *TemplateId) { EndLocation = TemplateId->RAngleLoc; } -void CXXScopeSpec::Extend(ASTContext &Context, SourceLocation TemplateKWLoc, +void CXXScopeSpec::Extend(ASTContext &Context, SourceLocation TemplateKWLoc, TypeLoc TL, SourceLocation ColonColonLoc) { Builder.Extend(Context, TemplateKWLoc, TL, ColonColonLoc); if (Range.getBegin().isInvalid()) @@ -56,23 +56,23 @@ void CXXScopeSpec::Extend(ASTContext &Context, SourceLocation TemplateKWLoc, } void CXXScopeSpec::Extend(ASTContext &Context, IdentifierInfo *Identifier, - SourceLocation IdentifierLoc, + SourceLocation IdentifierLoc, SourceLocation ColonColonLoc) { Builder.Extend(Context, Identifier, IdentifierLoc, ColonColonLoc); - + if (Range.getBegin().isInvalid()) Range.setBegin(IdentifierLoc); Range.setEnd(ColonColonLoc); - + assert(Range == Builder.getSourceRange() && "NestedNameSpecifierLoc range computation incorrect"); } void CXXScopeSpec::Extend(ASTContext &Context, NamespaceDecl *Namespace, - SourceLocation NamespaceLoc, + SourceLocation NamespaceLoc, SourceLocation ColonColonLoc) { Builder.Extend(Context, Namespace, NamespaceLoc, ColonColonLoc); - + if (Range.getBegin().isInvalid()) Range.setBegin(NamespaceLoc); Range.setEnd(ColonColonLoc); @@ -82,10 +82,10 @@ void CXXScopeSpec::Extend(ASTContext &Context, NamespaceDecl *Namespace, } void CXXScopeSpec::Extend(ASTContext &Context, NamespaceAliasDecl *Alias, - SourceLocation AliasLoc, + SourceLocation AliasLoc, SourceLocation ColonColonLoc) { Builder.Extend(Context, Alias, AliasLoc, ColonColonLoc); - + if (Range.getBegin().isInvalid()) Range.setBegin(AliasLoc); Range.setEnd(ColonColonLoc); @@ -94,12 +94,12 @@ void CXXScopeSpec::Extend(ASTContext &Context, NamespaceAliasDecl *Alias, "NestedNameSpecifierLoc range computation incorrect"); } -void CXXScopeSpec::MakeGlobal(ASTContext &Context, +void CXXScopeSpec::MakeGlobal(ASTContext &Context, SourceLocation ColonColonLoc) { Builder.MakeGlobal(Context, ColonColonLoc); - + Range = SourceRange(ColonColonLoc); - + assert(Range == Builder.getSourceRange() && "NestedNameSpecifierLoc range computation incorrect"); } @@ -116,7 +116,7 @@ void CXXScopeSpec::MakeSuper(ASTContext &Context, CXXRecordDecl *RD, "NestedNameSpecifierLoc range computation incorrect"); } -void CXXScopeSpec::MakeTrivial(ASTContext &Context, +void CXXScopeSpec::MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R) { Builder.MakeTrivial(Context, Qualifier, R); Range = R; @@ -139,11 +139,11 @@ SourceLocation CXXScopeSpec::getLastQualifierNameLoc() const { return Builder.getTemporary().getLocalBeginLoc(); } -NestedNameSpecifierLoc +NestedNameSpecifierLoc CXXScopeSpec::getWithLocInContext(ASTContext &Context) const { if (!Builder.getRepresentation()) return NestedNameSpecifierLoc(); - + return Builder.getWithLocInContext(Context); } @@ -232,7 +232,7 @@ DeclaratorChunk DeclaratorChunk::getFunction(bool hasProto, I.Fun.DeleteParams = true; } for (unsigned i = 0; i < NumParams; i++) - I.Fun.Params[i] = std::move(Params[i]); + I.Fun.Params[i] = std::move(Params[i]); } // Check what exception specification information we should actually store. @@ -323,7 +323,7 @@ bool Declarator::isDeclarationOfFunction() const { } llvm_unreachable("Invalid type chunk"); } - + switch (DS.getTypeSpecType()) { case TST_atomic: case TST_auto: @@ -369,20 +369,20 @@ bool Declarator::isDeclarationOfFunction() const { if (Expr *E = DS.getRepAsExpr()) return E->getType()->isFunctionType(); return false; - + case TST_underlyingType: case TST_typename: case TST_typeofType: { QualType QT = DS.getRepAsType().get(); if (QT.isNull()) return false; - + if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) QT = LIT->getType(); if (QT.isNull()) return false; - + return QT->isFunctionType(); } } @@ -438,8 +438,8 @@ template <class T> static bool BadSpecifier(T TNew, T TPrev, if (TNew != TPrev) DiagID = diag::err_invalid_decl_spec_combination; else - DiagID = IsExtension ? diag::ext_duplicate_declspec : - diag::warn_duplicate_declspec; + DiagID = IsExtension ? diag::ext_duplicate_declspec : + diag::warn_duplicate_declspec; return true; } @@ -970,7 +970,7 @@ bool DeclSpec::setModulePrivateSpec(SourceLocation Loc, const char *&PrevSpec, DiagID = diag::ext_duplicate_declspec; return true; } - + ModulePrivateLoc = Loc; return false; } @@ -1300,7 +1300,7 @@ bool DeclSpec::isMissingDeclaratorOk() { StorageClassSpec != DeclSpec::SCS_typedef; } -void UnqualifiedId::setOperatorFunctionId(SourceLocation OperatorLoc, +void UnqualifiedId::setOperatorFunctionId(SourceLocation OperatorLoc, OverloadedOperatorKind Op, SourceLocation SymbolLocations[3]) { Kind = UnqualifiedIdKind::IK_OperatorFunctionId; @@ -1309,7 +1309,7 @@ void UnqualifiedId::setOperatorFunctionId(SourceLocation OperatorLoc, OperatorFunctionId.Operator = Op; for (unsigned I = 0; I != 3; ++I) { OperatorFunctionId.SymbolLocations[I] = SymbolLocations[I].getRawEncoding(); - + if (SymbolLocations[I].isValid()) EndLocation = SymbolLocations[I]; } @@ -1321,7 +1321,7 @@ bool VirtSpecifiers::SetSpecifier(Specifier VS, SourceLocation Loc, FirstLocation = Loc; LastLocation = Loc; LastSpecifier = VS; - + if (Specifiers & VS) { PrevSpec = getSpecifierName(VS); return true; diff --git a/lib/Sema/DelayedDiagnostic.cpp b/lib/Sema/DelayedDiagnostic.cpp index 122b477d5522..a064e492c098 100644 --- a/lib/Sema/DelayedDiagnostic.cpp +++ b/lib/Sema/DelayedDiagnostic.cpp @@ -59,8 +59,8 @@ DelayedDiagnostic::makeAvailability(AvailabilityResult AR, void DelayedDiagnostic::Destroy() { switch (Kind) { - case Access: - getAccessData().~AccessedEntity(); + case Access: + getAccessData().~AccessedEntity(); break; case Availability: diff --git a/lib/Sema/IdentifierResolver.cpp b/lib/Sema/IdentifierResolver.cpp index dbd52dee1eea..dba56931d49c 100644 --- a/lib/Sema/IdentifierResolver.cpp +++ b/lib/Sema/IdentifierResolver.cpp @@ -46,7 +46,7 @@ class IdentifierResolver::IdDeclInfoMap { IdDeclInfoPool(IdDeclInfoPool *Next) : Next(Next) {} }; - + IdDeclInfoPool *CurPool = nullptr; unsigned int CurIndex = POOL_SIZE; @@ -171,9 +171,9 @@ void IdentifierResolver::InsertDeclAfter(iterator Pos, NamedDecl *D) { DeclarationName Name = D->getDeclName(); if (IdentifierInfo *II = Name.getAsIdentifierInfo()) updatingIdentifier(*II); - + void *Ptr = Name.getFETokenInfo<void>(); - + if (!Ptr) { AddDecl(D); return; @@ -196,7 +196,7 @@ void IdentifierResolver::InsertDeclAfter(iterator Pos, NamedDecl *D) { return; } - // General case: insert the declaration at the appropriate point in the + // General case: insert the declaration at the appropriate point in the // list, which already has at least two elements. IdDeclInfo *IDI = toIdDeclInfo(Ptr); if (Pos.isIterator()) { @@ -231,7 +231,7 @@ IdentifierResolver::iterator IdentifierResolver::begin(DeclarationName Name) { if (IdentifierInfo *II = Name.getAsIdentifierInfo()) readingIdentifier(*II); - + void *Ptr = Name.getFETokenInfo<void>(); if (!Ptr) return end(); @@ -258,7 +258,7 @@ enum DeclMatchKind { } // namespace /// Compare two declarations to see whether they are different or, -/// if they are the same, whether the new declaration should replace the +/// if they are the same, whether the new declaration should replace the /// existing declaration. static DeclMatchKind compareDeclarations(NamedDecl *Existing, NamedDecl *New) { // If the declarations are identical, ignore the new one. @@ -289,40 +289,40 @@ static DeclMatchKind compareDeclarations(NamedDecl *Existing, NamedDecl *New) { for (auto RD : New->redecls()) { if (RD == Existing) return DMK_Replace; - + if (RD->isCanonicalDecl()) break; } - + return DMK_Ignore; } - + return DMK_Different; } bool IdentifierResolver::tryAddTopLevelDecl(NamedDecl *D, DeclarationName Name){ if (IdentifierInfo *II = Name.getAsIdentifierInfo()) readingIdentifier(*II); - + void *Ptr = Name.getFETokenInfo<void>(); - + if (!Ptr) { Name.setFETokenInfo(D); return true; } - + IdDeclInfo *IDI; - + if (isDeclPtr(Ptr)) { NamedDecl *PrevD = static_cast<NamedDecl*>(Ptr); - + switch (compareDeclarations(PrevD, D)) { case DMK_Different: break; - + case DMK_Ignore: return false; - + case DMK_Replace: Name.setFETokenInfo(D); return true; @@ -330,7 +330,7 @@ bool IdentifierResolver::tryAddTopLevelDecl(NamedDecl *D, DeclarationName Name){ Name.setFETokenInfo(nullptr); IDI = &(*IdDeclInfos)[Name]; - + // If the existing declaration is not visible in translation unit scope, // then add the new top-level declaration first. if (!PrevD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { @@ -341,28 +341,28 @@ bool IdentifierResolver::tryAddTopLevelDecl(NamedDecl *D, DeclarationName Name){ IDI->AddDecl(D); } return true; - } - + } + IDI = toIdDeclInfo(Ptr); // See whether this declaration is identical to any existing declarations. // If not, find the right place to insert it. - for (IdDeclInfo::DeclsTy::iterator I = IDI->decls_begin(), + for (IdDeclInfo::DeclsTy::iterator I = IDI->decls_begin(), IEnd = IDI->decls_end(); I != IEnd; ++I) { - + switch (compareDeclarations(*I, D)) { case DMK_Different: break; - + case DMK_Ignore: return false; - + case DMK_Replace: *I = D; return true; } - + if (!(*I)->getDeclContext()->getRedeclContext()->isTranslationUnit()) { // We've found a declaration that is not visible from the translation // unit (it's in an inner scope). Insert our declaration here. @@ -370,7 +370,7 @@ bool IdentifierResolver::tryAddTopLevelDecl(NamedDecl *D, DeclarationName Name){ return true; } } - + // Add the declaration to the end. IDI->AddDecl(D); return true; @@ -378,13 +378,13 @@ bool IdentifierResolver::tryAddTopLevelDecl(NamedDecl *D, DeclarationName Name){ void IdentifierResolver::readingIdentifier(IdentifierInfo &II) { if (II.isOutOfDate()) - PP.getExternalSource()->updateOutOfDateIdentifier(II); + PP.getExternalSource()->updateOutOfDateIdentifier(II); } void IdentifierResolver::updatingIdentifier(IdentifierInfo &II) { if (II.isOutOfDate()) PP.getExternalSource()->updateOutOfDateIdentifier(II); - + if (II.isFromAST()) II.setFETokenInfoChangedSinceDeserialization(); } diff --git a/lib/Sema/MultiplexExternalSemaSource.cpp b/lib/Sema/MultiplexExternalSemaSource.cpp index 7e61ccbb1068..50808effe007 100644 --- a/lib/Sema/MultiplexExternalSemaSource.cpp +++ b/lib/Sema/MultiplexExternalSemaSource.cpp @@ -121,7 +121,7 @@ void MultiplexExternalSemaSource::FindExternalLexicalDecls( Sources[i]->FindExternalLexicalDecls(DC, IsKindWeWant, Result); } -void MultiplexExternalSemaSource::FindFileRegionDecls(FileID File, +void MultiplexExternalSemaSource::FindFileRegionDecls(FileID File, unsigned Offset, unsigned Length, SmallVectorImpl<Decl *> &Decls){ @@ -179,13 +179,13 @@ bool MultiplexExternalSemaSource::DeclIsFromPCHWithObjectFile(const Decl *D) { } bool MultiplexExternalSemaSource::layoutRecordType(const RecordDecl *Record, - uint64_t &Size, + uint64_t &Size, uint64_t &Alignment, llvm::DenseMap<const FieldDecl *, uint64_t> &FieldOffsets, llvm::DenseMap<const CXXRecordDecl *, CharUnits> &BaseOffsets, llvm::DenseMap<const CXXRecordDecl *, CharUnits> &VirtualBaseOffsets){ for(size_t i = 0; i < Sources.size(); ++i) - if (Sources[i]->layoutRecordType(Record, Size, Alignment, FieldOffsets, + if (Sources[i]->layoutRecordType(Record, Size, Alignment, FieldOffsets, BaseOffsets, VirtualBaseOffsets)) return true; return false; @@ -243,10 +243,10 @@ void MultiplexExternalSemaSource::ReadMismatchingDeleteExpressions( Source->ReadMismatchingDeleteExpressions(Exprs); } -bool MultiplexExternalSemaSource::LookupUnqualified(LookupResult &R, Scope *S){ +bool MultiplexExternalSemaSource::LookupUnqualified(LookupResult &R, Scope *S){ for(size_t i = 0; i < Sources.size(); ++i) Sources[i]->LookupUnqualified(R, S); - + return !R.empty(); } @@ -255,13 +255,13 @@ void MultiplexExternalSemaSource::ReadTentativeDefinitions( for(size_t i = 0; i < Sources.size(); ++i) Sources[i]->ReadTentativeDefinitions(TentativeDefs); } - + void MultiplexExternalSemaSource::ReadUnusedFileScopedDecls( SmallVectorImpl<const DeclaratorDecl*> &Decls) { for(size_t i = 0; i < Sources.size(); ++i) Sources[i]->ReadUnusedFileScopedDecls(Decls); } - + void MultiplexExternalSemaSource::ReadDelegatingConstructors( SmallVectorImpl<CXXConstructorDecl*> &Decls) { for(size_t i = 0; i < Sources.size(); ++i) diff --git a/lib/Sema/Sema.cpp b/lib/Sema/Sema.cpp index d57473c5616f..49f3decc1151 100644 --- a/lib/Sema/Sema.cpp +++ b/lib/Sema/Sema.cpp @@ -1500,7 +1500,7 @@ LambdaScopeInfo *Sema::getCurLambda(bool IgnoreNonLambdaCapturingScope) { return CurLSI; } -// We have a generic lambda if we parsed auto parameters, or we have +// We have a generic lambda if we parsed auto parameters, or we have // an associated template parameter list. LambdaScopeInfo *Sema::getCurGenericLambda() { if (LambdaScopeInfo *LSI = getCurLambda()) { diff --git a/lib/Sema/SemaAccess.cpp b/lib/Sema/SemaAccess.cpp index 9fbae2ca297f..e06792cae78b 100644 --- a/lib/Sema/SemaAccess.cpp +++ b/lib/Sema/SemaAccess.cpp @@ -152,8 +152,8 @@ struct AccessTarget : public AccessedEntity { : AccessedEntity(Entity) { initialize(); } - - AccessTarget(ASTContext &Context, + + AccessTarget(ASTContext &Context, MemberNonce _, CXXRecordDecl *NamingClass, DeclAccessPair FoundDecl, @@ -163,7 +163,7 @@ struct AccessTarget : public AccessedEntity { initialize(); } - AccessTarget(ASTContext &Context, + AccessTarget(ASTContext &Context, BaseNonce _, CXXRecordDecl *BaseClass, CXXRecordDecl *DerivedClass, @@ -777,7 +777,7 @@ static AccessResult HasAccess(Sema &S, // We interpret this as a restriction on [M3]. // In this part of the code, 'C' is just our context class ECRecord. - + // These rules are different if we don't have an instance context. if (!Target.hasInstanceContext()) { // If it's not an instance member, these restrictions don't apply. @@ -1272,8 +1272,8 @@ static void DiagnoseBadAccess(Sema &S, SourceLocation Loc, DiagnoseAccessPath(S, EC, Entity); } -/// MSVC has a bug where if during an using declaration name lookup, -/// the declaration found is unaccessible (private) and that declaration +/// MSVC has a bug where if during an using declaration name lookup, +/// the declaration found is unaccessible (private) and that declaration /// was bring into scope via another using declaration whose target /// declaration is accessible (public) then no error is generated. /// Example: @@ -1290,15 +1290,15 @@ static void DiagnoseBadAccess(Sema &S, SourceLocation Loc, /// using B::f; /// }; /// -/// Here, B::f is private so this should fail in Standard C++, but +/// Here, B::f is private so this should fail in Standard C++, but /// because B::f refers to A::f which is public MSVC accepts it. -static bool IsMicrosoftUsingDeclarationAccessBug(Sema& S, +static bool IsMicrosoftUsingDeclarationAccessBug(Sema& S, SourceLocation AccessLoc, AccessTarget &Entity) { if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Entity.getTargetDecl())) { const NamedDecl *OrigDecl = Entity.getTargetDecl()->getUnderlyingDecl(); - if (Entity.getTargetDecl()->getAccess() == AS_private && + if (Entity.getTargetDecl()->getAccess() == AS_private && (OrigDecl->getAccess() == AS_public || OrigDecl->getAccess() == AS_protected)) { S.Diag(AccessLoc, diag::ext_ms_using_declaration_inaccessible) @@ -1536,7 +1536,7 @@ Sema::AccessResult Sema::CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E, Found.getAccess() == AS_public) return AR_accessible; - AccessTarget Entity(Context, AccessTarget::Member, E->getNamingClass(), + AccessTarget Entity(Context, AccessTarget::Member, E->getNamingClass(), Found, QualType()); Entity.setDiag(diag::err_access) << E->getSourceRange(); @@ -1691,7 +1691,7 @@ Sema::AccessResult Sema::CheckConstructorAccess(SourceLocation UseLoc, AccessEntity.setDiag(PD); return CheckAccess(*this, UseLoc, AccessEntity); -} +} /// Checks access to an overloaded operator new or delete. Sema::AccessResult Sema::CheckAllocationAccess(SourceLocation OpLoc, @@ -1823,7 +1823,7 @@ Sema::AccessResult Sema::CheckBaseClassAccess(SourceLocation AccessLoc, BaseD = cast<CXXRecordDecl>(Base->getAs<RecordType>()->getDecl()); DerivedD = cast<CXXRecordDecl>(Derived->getAs<RecordType>()->getDecl()); - AccessTarget Entity(Context, AccessTarget::Base, BaseD, DerivedD, + AccessTarget Entity(Context, AccessTarget::Base, BaseD, DerivedD, Path.Access); if (DiagID) Entity.setDiag(DiagID) << Derived << Base; @@ -1893,7 +1893,7 @@ bool Sema::IsSimplyAccessible(NamedDecl *Target, DeclContext *Ctx) { if (ObjCMethodDecl *MD = getCurMethodDecl()) ClassOfMethodDecl = MD->getClassInterface(); else if (FunctionDecl *FD = getCurFunctionDecl()) { - if (ObjCImplDecl *Impl + if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(FD->getLexicalDeclContext())) { if (ObjCImplementationDecl *IMPD = dyn_cast<ObjCImplementationDecl>(Impl)) @@ -1903,21 +1903,21 @@ bool Sema::IsSimplyAccessible(NamedDecl *Target, DeclContext *Ctx) { ClassOfMethodDecl = CatImplClass->getClassInterface(); } } - + // If we're not in an interface, this ivar is inaccessible. if (!ClassOfMethodDecl) return false; - + // If we're inside the same interface that owns the ivar, we're fine. if (declaresSameEntity(ClassOfMethodDecl, Ivar->getContainingInterface())) return true; - + // If the ivar is private, it's inaccessible. if (Ivar->getCanonicalAccessControl() == ObjCIvarDecl::Private) return false; - + return Ivar->getContainingInterface()->isSuperClassOf(ClassOfMethodDecl); } - + return true; } diff --git a/lib/Sema/SemaAttr.cpp b/lib/Sema/SemaAttr.cpp index 4f3cf4633c80..1a8a00075306 100644 --- a/lib/Sema/SemaAttr.cpp +++ b/lib/Sema/SemaAttr.cpp @@ -268,7 +268,7 @@ void Sema::DiagnoseUnterminatedPragmaPack() { } } -void Sema::ActOnPragmaMSStruct(PragmaMSStructKind Kind) { +void Sema::ActOnPragmaMSStruct(PragmaMSStructKind Kind) { MSStructPragmaOn = (Kind == PMSST_ON); } @@ -693,7 +693,7 @@ void Sema::AddRangeBasedOptnone(FunctionDecl *FD) { AddOptnoneAttributeIfNoConflicts(FD, OptimizeOffPragmaLocation); } -void Sema::AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, +void Sema::AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc) { // Don't add a conflicting attribute. No diagnostic is needed. if (FD->hasAttr<MinSizeAttr>() || FD->hasAttr<AlwaysInlineAttr>()) diff --git a/lib/Sema/SemaCXXScopeSpec.cpp b/lib/Sema/SemaCXXScopeSpec.cpp index f2fad825c3e7..4e39d0675471 100644 --- a/lib/Sema/SemaCXXScopeSpec.cpp +++ b/lib/Sema/SemaCXXScopeSpec.cpp @@ -401,18 +401,18 @@ bool Sema::isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, isDependent = isDependentScopeSpecifier(SS); Found.setContextRange(SS.getRange()); } - + if (LookupCtx) { // Perform "qualified" name lookup into the declaration context we // computed, which is either the type of the base of a member access // expression or the declaration context associated with a prior // nested-name-specifier. - + // The declaration context must be complete. if (!LookupCtx->isDependentContext() && RequireCompleteDeclContext(SS, LookupCtx)) return false; - + LookupQualifiedName(Found, LookupCtx); } else if (isDependent) { return false; @@ -420,7 +420,7 @@ bool Sema::isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, LookupName(Found, S); } Found.suppressDiagnostics(); - + return Found.getAsSingle<NamespaceDecl>(); } @@ -739,7 +739,7 @@ bool Sema::BuildCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo, = TLB.push<UnresolvedUsingTypeLoc>(T); UnresolvedTL.setNameLoc(IdInfo.IdentifierLoc); } else if (isa<SubstTemplateTypeParmType>(T)) { - SubstTemplateTypeParmTypeLoc TL + SubstTemplateTypeParmTypeLoc TL = TLB.push<SubstTemplateTypeParmTypeLoc>(T); TL.setNameLoc(IdInfo.IdentifierLoc); } else if (isa<SubstTemplateTypeParmPackType>(T)) { @@ -772,11 +772,11 @@ bool Sema::BuildCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo, } // In Microsoft mode, if we are within a templated function and we can't - // resolve Identifier, then extend the SS with Identifier. This will have - // the effect of resolving Identifier during template instantiation. + // resolve Identifier, then extend the SS with Identifier. This will have + // the effect of resolving Identifier during template instantiation. // The goal is to be able to resolve a function call whose // nested-name-specifier is located inside a dependent base class. - // Example: + // Example: // // class C { // public: @@ -850,7 +850,7 @@ bool Sema::ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS, return true; if (!T->isDependentType() && !T->getAs<TagType>()) { - Diag(DS.getTypeSpecTypeLoc(), diag::err_expected_class_or_namespace) + Diag(DS.getTypeSpecTypeLoc(), diag::err_expected_class_or_namespace) << T << getLangOpts().CPlusPlus; return true; } @@ -891,7 +891,7 @@ bool Sema::ActOnCXXNestedNameSpecifier(Scope *S, bool EnteringContext) { if (SS.isInvalid()) return true; - + // Translate the parser's template argument list in our AST format. TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc); translateTemplateArguments(TemplateArgsIn, TemplateArgs); @@ -905,7 +905,7 @@ bool Sema::ActOnCXXNestedNameSpecifier(Scope *S, DTN->getQualifier(), DTN->getIdentifier(), TemplateArgs); - + // Create source-location information for this type. TypeLocBuilder Builder; DependentTemplateSpecializationTypeLoc SpecTL @@ -918,7 +918,7 @@ bool Sema::ActOnCXXNestedNameSpecifier(Scope *S, SpecTL.setRAngleLoc(RAngleLoc); for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo()); - + SS.Extend(Context, TemplateKWLoc, Builder.getTypeLocInContext(Context, T), CCLoc); return false; @@ -937,7 +937,7 @@ bool Sema::ActOnCXXNestedNameSpecifier(Scope *S, return true; } - // We were able to resolve the template name to an actual template. + // We were able to resolve the template name to an actual template. // Build an appropriate nested-name-specifier. QualType T = CheckTemplateIdType(Template.get(), TemplateNameLoc, TemplateArgs); @@ -971,7 +971,7 @@ bool Sema::ActOnCXXNestedNameSpecifier(Scope *S, namespace { /// A structure that stores a nested-name-specifier annotation, - /// including both the nested-name-specifier + /// including both the nested-name-specifier struct NestedNameSpecifierAnnotation { NestedNameSpecifier *NNS; }; @@ -991,14 +991,14 @@ void *Sema::SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS) { return Annotation; } -void Sema::RestoreNestedNameSpecifierAnnotation(void *AnnotationPtr, +void Sema::RestoreNestedNameSpecifierAnnotation(void *AnnotationPtr, SourceRange AnnotationRange, CXXScopeSpec &SS) { if (!AnnotationPtr) { SS.SetInvalid(AnnotationRange); return; } - + NestedNameSpecifierAnnotation *Annotation = static_cast<NestedNameSpecifierAnnotation *>(AnnotationPtr); SS.Adopt(NestedNameSpecifierLoc(Annotation->NNS, Annotation + 1)); @@ -1065,7 +1065,7 @@ bool Sema::ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS) { // it is a complete declaration context. if (!DC->isDependentContext() && RequireCompleteDeclContext(SS, DC)) return true; - + EnterDeclaratorContext(S, DC); // Rebuild the nested name specifier for the new scope. diff --git a/lib/Sema/SemaCast.cpp b/lib/Sema/SemaCast.cpp index b7f4629fbab7..57aac80f5ad2 100644 --- a/lib/Sema/SemaCast.cpp +++ b/lib/Sema/SemaCast.cpp @@ -205,13 +205,13 @@ static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExp CXXCastPath &BasePath); static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, - QualType DestType, + QualType DestType, Sema::CheckedConversionKind CCK, SourceRange OpRange, unsigned &msg, CastKind &Kind, bool ListInitialization); static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr, - QualType DestType, + QualType DestType, Sema::CheckedConversionKind CCK, SourceRange OpRange, unsigned &msg, CastKind &Kind, @@ -319,7 +319,7 @@ Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, return ExprError(); DiscardMisalignedMemberAddress(DestType.getTypePtr(), E); } - + return Op.complete(CXXStaticCastExpr::Create(Context, Op.ResultType, Op.ValueKind, Op.Kind, Op.SrcExpr.get(), &Op.BasePath, DestTInfo, @@ -573,11 +573,11 @@ CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType, "Destination type is not pointer or pointer to member."); } - QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType), + QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType), UnwrappedDestType = Self.Context.getCanonicalType(DestType); - // Find the qualifiers. We only care about cvr-qualifiers for the - // purpose of this check, because other qualifiers (address spaces, + // Find the qualifiers. We only care about cvr-qualifiers for the + // purpose of this check, because other qualifiers (address spaces, // Objective-C GC, etc.) are part of the type's identity. QualType PrevUnwrappedSrcType = UnwrappedSrcType; QualType PrevUnwrappedDestType = UnwrappedDestType; @@ -719,7 +719,7 @@ void CastOperation::CheckDynamicCast() { // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to // complete class type, [...]. If T is an lvalue reference type, v shall be - // an lvalue of a complete class type, [...]. If T is an rvalue reference + // an lvalue of a complete class type, [...]. If T is an rvalue reference // type, v shall be an expression having a complete class type, [...] QualType SrcType = Self.Context.getCanonicalType(OrigSrcType); QualType SrcPointee; @@ -788,7 +788,7 @@ void CastOperation::CheckDynamicCast() { if (DestRecord && Self.IsDerivedFrom(OpRange.getBegin(), SrcPointee, DestPointee)) { if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee, - OpRange.getBegin(), OpRange, + OpRange.getBegin(), OpRange, &BasePath)) { SrcExpr = ExprError(); return; @@ -950,15 +950,15 @@ void CastOperation::CheckReinterpretCast() { return; unsigned msg = diag::err_bad_cxx_cast_generic; - TryCastResult tcr = - TryReinterpretCast(Self, SrcExpr, DestType, + TryCastResult tcr = + TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange, msg, Kind); if (tcr != TC_Success && msg != 0) { if (SrcExpr.isInvalid()) // if conversion failed, don't report another error return; if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { - //FIXME: &f<int>; is overloaded and resolvable - Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload) + //FIXME: &f<int>; is overloaded and resolvable + Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload) << OverloadExpr::find(SrcExpr.get()).Expression->getName() << DestType << OpRange; Self.NoteAllOverloadCandidates(SrcExpr.get()); @@ -996,8 +996,8 @@ void CastOperation::CheckStaticCast() { Kind = CK_ToVoid; if (claimPlaceholder(BuiltinType::Overload)) { - Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr, - false, // Decay Function to ptr + Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr, + false, // Decay Function to ptr true, // Complain OpRange, DestType, diag::err_bad_static_cast_overload); if (SrcExpr.isInvalid()) @@ -1025,7 +1025,7 @@ void CastOperation::CheckStaticCast() { if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression; Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload) - << oe->getName() << DestType << OpRange + << oe->getName() << DestType << OpRange << oe->getQualifierLoc().getSourceRange(); Self.NoteAllOverloadCandidates(SrcExpr.get()); } else { @@ -1048,15 +1048,15 @@ void CastOperation::CheckStaticCast() { /// possible. If @p CStyle, ignore access restrictions on hierarchy casting /// and casting away constness. static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr, - QualType DestType, + QualType DestType, Sema::CheckedConversionKind CCK, SourceRange OpRange, unsigned &msg, CastKind &Kind, CXXCastPath &BasePath, bool ListInitialization) { // Determine whether we have the semantics of a C-style cast. - bool CStyle + bool CStyle = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast); - + // The order the tests is not entirely arbitrary. There is one conversion // that can be handled in two different ways. Given: // struct A {}; @@ -1082,7 +1082,7 @@ static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr, if (tcr != TC_NotApplicable) return tcr; - // C++11 [expr.static.cast]p3: + // C++11 [expr.static.cast]p3: // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2 // T2" if "cv2 T2" is reference-compatible with "cv1 T1". tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind, @@ -1098,7 +1098,7 @@ static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr, return TC_Failed; if (tcr != TC_NotApplicable) return tcr; - + // C++ 5.2.9p6: May apply the reverse of any standard conversion, except // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean // conversions, subject to further restrictions. @@ -1126,7 +1126,7 @@ static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr, } } } - + // Reverse integral promotion/conversion. All such conversions are themselves // again integral promotions or conversions and are thus already handled by // p2 (TryDirectInitialization above). @@ -1199,7 +1199,7 @@ static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr, } } else if (DestType->isObjCObjectPointerType()) { - // allow both c-style cast and static_cast of objective-c pointers as + // allow both c-style cast and static_cast of objective-c pointers as // they are pervasive. Kind = CK_CPointerToObjCPointerCast; return TC_Success; @@ -1230,7 +1230,7 @@ static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr, if (SrcPointer->getPointeeType()->getAs<RecordType>() && DestPointer->getPointeeType()->getAs<RecordType>()) msg = diag::err_bad_cxx_cast_unrelated_class; - + // We tried everything. Everything! Nothing works! :-( return TC_NotApplicable; } @@ -1284,11 +1284,11 @@ TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, if (!Self.IsDerivedFrom(SrcExpr->getLocStart(), SrcExpr->getType(), R->getPointeeType(), Paths)) return TC_NotApplicable; - + Self.BuildBasePathArray(Paths, BasePath); } else Kind = CK_NoOp; - + return TC_Success; } @@ -1323,8 +1323,8 @@ TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType, // FIXME: If the source is a prvalue, we should issue a warning (because the // cast always has undefined behavior), and for AST consistency, we should // materialize a temporary. - return TryStaticDowncast(Self, - Self.Context.getCanonicalType(SrcExpr->getType()), + return TryStaticDowncast(Self, + Self.Context.getCanonicalType(SrcExpr->getType()), Self.Context.getCanonicalType(DestPointee), CStyle, OpRange, SrcExpr->getType(), DestType, msg, Kind, BasePath); @@ -1355,9 +1355,9 @@ TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType, return TC_NotApplicable; } - return TryStaticDowncast(Self, + return TryStaticDowncast(Self, Self.Context.getCanonicalType(SrcPointer->getPointeeType()), - Self.Context.getCanonicalType(DestPointer->getPointeeType()), + Self.Context.getCanonicalType(DestPointer->getPointeeType()), CStyle, OpRange, SrcType, DestType, msg, Kind, BasePath); } @@ -1368,7 +1368,7 @@ TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType, TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType, bool CStyle, SourceRange OpRange, QualType OrigSrcType, - QualType OrigDestType, unsigned &msg, + QualType OrigDestType, unsigned &msg, CastKind &Kind, CXXCastPath &BasePath) { // We can only work with complete types. But don't complain if it doesn't work if (!Self.isCompleteType(OpRange.getBegin(), SrcType) || @@ -1434,7 +1434,7 @@ TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType, } Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast) - << QualType(SrcType).getUnqualifiedType() + << QualType(SrcType).getUnqualifiedType() << QualType(DestType).getUnqualifiedType() << PathDisplayStr << OpRange; msg = 0; @@ -1478,8 +1478,8 @@ TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType, /// where B is a base class of D [...]. /// TryCastResult -TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType, - QualType DestType, bool CStyle, +TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType, + QualType DestType, bool CStyle, SourceRange OpRange, unsigned &msg, CastKind &Kind, CXXCastPath &BasePath) { @@ -1499,7 +1499,7 @@ TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType, WasOverloadedFunction = true; } } - + const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>(); if (!SrcMemPtr) { msg = diag::err_bad_static_cast_member_pointer_nonmp; @@ -1569,8 +1569,8 @@ TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType, if (WasOverloadedFunction) { // Resolve the address of the overloaded function again, this time // allowing complaints if something goes wrong. - FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), - DestType, + FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), + DestType, true, FoundOverload); if (!Fn) { @@ -1597,7 +1597,7 @@ TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType, /// @c static_cast if the declaration "T t(e);" is well-formed [...]. TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType, - Sema::CheckedConversionKind CCK, + Sema::CheckedConversionKind CCK, SourceRange OpRange, unsigned &msg, CastKind &Kind, bool ListInitialization) { if (DestType->isRecordType()) { @@ -1625,26 +1625,26 @@ TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType, InitializationSequence InitSeq(Self, Entity, InitKind, SrcExprRaw); // At this point of CheckStaticCast, if the destination is a reference, - // or the expression is an overload expression this has to work. + // or the expression is an overload expression this has to work. // There is no other way that works. // On the other hand, if we're checking a C-style cast, we've still got // the reinterpret_cast way. - bool CStyle + bool CStyle = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast); if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType())) return TC_NotApplicable; - + ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw); if (Result.isInvalid()) { msg = 0; return TC_Failed; } - + if (InitSeq.isConstructorInitialization()) Kind = CK_ConstructorConversion; else Kind = CK_NoOp; - + SrcExpr = Result; return TC_Success; } @@ -1976,7 +1976,7 @@ static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr, unsigned &msg, CastKind &Kind) { bool IsLValueCast = false; - + DestType = Self.Context.getCanonicalType(DestType); QualType SrcType = SrcExpr.get()->getType(); @@ -2019,7 +2019,7 @@ static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr, // FIXME: Use a specific diagnostic for the rest of these cases. case OK_VectorComponent: inappropriate = "vector element"; break; case OK_ObjCProperty: inappropriate = "property expression"; break; - case OK_ObjCSubscript: inappropriate = "container subscripting expression"; + case OK_ObjCSubscript: inappropriate = "container subscripting expression"; break; } if (inappropriate) { @@ -2033,7 +2033,7 @@ static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr, // This code does this transformation for the checked types. DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType()); SrcType = Self.Context.getPointerType(SrcType); - + IsLValueCast = true; } @@ -2121,18 +2121,18 @@ static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr, msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size; else msg = diag::err_bad_cxx_cast_vector_to_vector_different_size; - + return TC_Failed; } if (SrcType == DestType) { // C++ 5.2.10p2 has a note that mentions that, subject to all other // restrictions, a cast to the same type is allowed so long as it does not - // cast away constness. In C++98, the intent was not entirely clear here, + // cast away constness. In C++98, the intent was not entirely clear here, // since all other paragraphs explicitly forbid casts to the same type. // C++11 clarifies this case with p2. // - // The only allowed types are: integral, enumeration, pointer, or + // The only allowed types are: integral, enumeration, pointer, or // pointer-to-member types. We also won't restrict Obj-C pointers either. Kind = CK_NoOp; TryCastResult Result = TC_NotApplicable; @@ -2260,7 +2260,7 @@ static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr, << OpRange; return SuccessResult; } - + // C++ 5.2.10p7: A pointer to an object can be explicitly converted to // a pointer to an object of different type. // Void pointers are not specified, but supported by every compiler out there. @@ -2296,7 +2296,7 @@ void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle, if (claimPlaceholder(BuiltinType::Overload)) { Self.ResolveAndFixSingleFunctionTemplateSpecialization( - SrcExpr, /* Decay Function to ptr */ false, + SrcExpr, /* Decay Function to ptr */ false, /* Complain */ true, DestRange, DestType, diag::err_bad_cstyle_cast_overload); if (SrcExpr.isInvalid()) @@ -2404,7 +2404,7 @@ void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle, } } -/// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a +/// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a /// non-matching type. Such as enum function call to int, int call to /// pointer; etc. Cast to 'void' is an exception. static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr, @@ -2412,10 +2412,10 @@ static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr, if (Self.Diags.isIgnored(diag::warn_bad_function_cast, SrcExpr.get()->getExprLoc())) return; - + if (!isa<CallExpr>(SrcExpr.get())) return; - + QualType SrcType = SrcExpr.get()->getType(); if (DestType.getUnqualifiedType()->isVoidType()) return; @@ -2434,7 +2434,7 @@ static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr, return; if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType()) return; - + Self.Diag(SrcExpr.get()->getExprLoc(), diag::warn_bad_function_cast) << SrcType << DestType << SrcExpr.get()->getSourceRange(); @@ -2641,26 +2641,26 @@ void CastOperation::CheckCStyleCast() { if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) { Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers(); Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers(); - if (CastPtr->getPointeeType()->isObjCLifetimeType() && + if (CastPtr->getPointeeType()->isObjCLifetimeType() && ExprPtr->getPointeeType()->isObjCLifetimeType() && !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) { - Self.Diag(SrcExpr.get()->getLocStart(), + Self.Diag(SrcExpr.get()->getLocStart(), diag::err_typecheck_incompatible_ownership) << SrcType << DestType << Sema::AA_Casting << SrcExpr.get()->getSourceRange(); return; } } - } + } else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) { - Self.Diag(SrcExpr.get()->getLocStart(), + Self.Diag(SrcExpr.get()->getLocStart(), diag::err_arc_convesion_of_weak_unavailable) << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange(); SrcExpr = ExprError(); return; } } - + DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType); DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange); DiagnoseBadFunctionCast(Self, SrcExpr, DestType); @@ -2714,7 +2714,7 @@ ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc, TypeSourceInfo *CastTypeInfo, SourceLocation RPLoc, Expr *CastExpr) { - CastOperation Op(*this, CastTypeInfo->getType(), CastExpr); + CastOperation Op(*this, CastTypeInfo->getType(), CastExpr); Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange(); Op.OpRange = SourceRange(LPLoc, CastExpr->getLocEnd()); diff --git a/lib/Sema/SemaChecking.cpp b/lib/Sema/SemaChecking.cpp index 8d953b6ef341..93dbeab5b034 100644 --- a/lib/Sema/SemaChecking.cpp +++ b/lib/Sema/SemaChecking.cpp @@ -119,7 +119,7 @@ static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { // Highlight all the excess arguments. SourceRange range(call->getArg(desiredArgCount)->getLocStart(), call->getArg(argCount - 1)->getLocEnd()); - + return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) << 0 /*function call*/ << desiredArgCount << argCount << call->getArg(1)->getSourceRange(); @@ -888,18 +888,18 @@ Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); if (Error != ASTContext::GE_None) ICEArguments = 0; // Don't diagnose previously diagnosed errors. - + // If any arguments are required to be ICE's, check and diagnose. for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { // Skip arguments not required to be ICE's. if ((ICEArguments & (1 << ArgNo)) == 0) continue; - + llvm::APSInt Result; if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) return true; ICEArguments &= ~(1 << ArgNo); } - + switch (BuiltinID) { case Builtin::BI__builtin___CFStringMakeConstantString: assert(TheCall->getNumArgs() == 1 && @@ -3850,7 +3850,7 @@ DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, static bool isNonNullType(ASTContext &ctx, QualType type) { if (auto nullability = type->getNullability(ctx)) return *nullability == NullabilityKind::NonNull; - + return false; } @@ -3893,12 +3893,12 @@ static void CheckNonNullArguments(Sema &S, parms = FD->parameters(); else parms = cast<ObjCMethodDecl>(FDecl)->parameters(); - + unsigned ParamIndex = 0; for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); I != E; ++I, ++ParamIndex) { const ParmVarDecl *PVD = *I; - if (PVD->hasAttr<NonNullAttr>() || + if (PVD->hasAttr<NonNullAttr>() || isNonNullType(S.Context, PVD->getType())) { if (NonNullArgs.empty()) NonNullArgs.resize(Args.size()); @@ -3920,7 +3920,7 @@ static void CheckNonNullArguments(Sema &S, // Dig out the function prototype, if there is one. Proto = type->getAs<FunctionProtoType>(); - } + } } // Fill in non-null argument information from the nullability @@ -3931,17 +3931,17 @@ static void CheckNonNullArguments(Sema &S, if (isNonNullType(S.Context, paramType)) { if (NonNullArgs.empty()) NonNullArgs.resize(Args.size()); - + NonNullArgs.set(Index); } - + ++Index; } } } // Check for non-null arguments. - for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); + for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); ArgIndex != ArgIndexEnd; ++ArgIndex) { if (NonNullArgs[ArgIndex]) CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); @@ -4074,7 +4074,7 @@ bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, return false; } -bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, +bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, ArrayRef<const Expr *> Args) { VariadicCallType CallType = Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; @@ -4577,7 +4577,7 @@ ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(), SubExprs, ResultType, Op, TheCall->getRParenLoc()); - + if ((Op == AtomicExpr::AO__c11_atomic_load || Op == AtomicExpr::AO__c11_atomic_store || Op == AtomicExpr::AO__opencl_atomic_load || @@ -4744,52 +4744,52 @@ Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { bool WarnAboutSemanticsChange = false; switch (BuiltinID) { default: llvm_unreachable("Unknown overloaded atomic builtin!"); - case Builtin::BI__sync_fetch_and_add: + case Builtin::BI__sync_fetch_and_add: case Builtin::BI__sync_fetch_and_add_1: case Builtin::BI__sync_fetch_and_add_2: case Builtin::BI__sync_fetch_and_add_4: case Builtin::BI__sync_fetch_and_add_8: case Builtin::BI__sync_fetch_and_add_16: - BuiltinIndex = 0; + BuiltinIndex = 0; break; - - case Builtin::BI__sync_fetch_and_sub: + + case Builtin::BI__sync_fetch_and_sub: case Builtin::BI__sync_fetch_and_sub_1: case Builtin::BI__sync_fetch_and_sub_2: case Builtin::BI__sync_fetch_and_sub_4: case Builtin::BI__sync_fetch_and_sub_8: case Builtin::BI__sync_fetch_and_sub_16: - BuiltinIndex = 1; + BuiltinIndex = 1; break; - - case Builtin::BI__sync_fetch_and_or: + + case Builtin::BI__sync_fetch_and_or: case Builtin::BI__sync_fetch_and_or_1: case Builtin::BI__sync_fetch_and_or_2: case Builtin::BI__sync_fetch_and_or_4: case Builtin::BI__sync_fetch_and_or_8: case Builtin::BI__sync_fetch_and_or_16: - BuiltinIndex = 2; + BuiltinIndex = 2; break; - - case Builtin::BI__sync_fetch_and_and: + + case Builtin::BI__sync_fetch_and_and: case Builtin::BI__sync_fetch_and_and_1: case Builtin::BI__sync_fetch_and_and_2: case Builtin::BI__sync_fetch_and_and_4: case Builtin::BI__sync_fetch_and_and_8: case Builtin::BI__sync_fetch_and_and_16: - BuiltinIndex = 3; + BuiltinIndex = 3; break; - case Builtin::BI__sync_fetch_and_xor: + case Builtin::BI__sync_fetch_and_xor: case Builtin::BI__sync_fetch_and_xor_1: case Builtin::BI__sync_fetch_and_xor_2: case Builtin::BI__sync_fetch_and_xor_4: case Builtin::BI__sync_fetch_and_xor_8: case Builtin::BI__sync_fetch_and_xor_16: - BuiltinIndex = 4; + BuiltinIndex = 4; break; - case Builtin::BI__sync_fetch_and_nand: + case Builtin::BI__sync_fetch_and_nand: case Builtin::BI__sync_fetch_and_nand_1: case Builtin::BI__sync_fetch_and_nand_2: case Builtin::BI__sync_fetch_and_nand_4: @@ -4799,43 +4799,43 @@ Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { WarnAboutSemanticsChange = true; break; - case Builtin::BI__sync_add_and_fetch: + case Builtin::BI__sync_add_and_fetch: case Builtin::BI__sync_add_and_fetch_1: case Builtin::BI__sync_add_and_fetch_2: case Builtin::BI__sync_add_and_fetch_4: case Builtin::BI__sync_add_and_fetch_8: case Builtin::BI__sync_add_and_fetch_16: - BuiltinIndex = 6; + BuiltinIndex = 6; break; - - case Builtin::BI__sync_sub_and_fetch: + + case Builtin::BI__sync_sub_and_fetch: case Builtin::BI__sync_sub_and_fetch_1: case Builtin::BI__sync_sub_and_fetch_2: case Builtin::BI__sync_sub_and_fetch_4: case Builtin::BI__sync_sub_and_fetch_8: case Builtin::BI__sync_sub_and_fetch_16: - BuiltinIndex = 7; + BuiltinIndex = 7; break; - - case Builtin::BI__sync_and_and_fetch: + + case Builtin::BI__sync_and_and_fetch: case Builtin::BI__sync_and_and_fetch_1: case Builtin::BI__sync_and_and_fetch_2: case Builtin::BI__sync_and_and_fetch_4: case Builtin::BI__sync_and_and_fetch_8: case Builtin::BI__sync_and_and_fetch_16: - BuiltinIndex = 8; + BuiltinIndex = 8; break; - - case Builtin::BI__sync_or_and_fetch: + + case Builtin::BI__sync_or_and_fetch: case Builtin::BI__sync_or_and_fetch_1: case Builtin::BI__sync_or_and_fetch_2: case Builtin::BI__sync_or_and_fetch_4: case Builtin::BI__sync_or_and_fetch_8: case Builtin::BI__sync_or_and_fetch_16: - BuiltinIndex = 9; + BuiltinIndex = 9; break; - - case Builtin::BI__sync_xor_and_fetch: + + case Builtin::BI__sync_xor_and_fetch: case Builtin::BI__sync_xor_and_fetch_1: case Builtin::BI__sync_xor_and_fetch_2: case Builtin::BI__sync_xor_and_fetch_4: @@ -4844,7 +4844,7 @@ Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { BuiltinIndex = 10; break; - case Builtin::BI__sync_nand_and_fetch: + case Builtin::BI__sync_nand_and_fetch: case Builtin::BI__sync_nand_and_fetch_1: case Builtin::BI__sync_nand_and_fetch_2: case Builtin::BI__sync_nand_and_fetch_4: @@ -4863,7 +4863,7 @@ Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { BuiltinIndex = 12; NumFixed = 2; break; - + case Builtin::BI__sync_bool_compare_and_swap: case Builtin::BI__sync_bool_compare_and_swap_1: case Builtin::BI__sync_bool_compare_and_swap_2: @@ -4874,16 +4874,16 @@ Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { NumFixed = 2; ResultType = Context.BoolTy; break; - + case Builtin::BI__sync_lock_test_and_set: case Builtin::BI__sync_lock_test_and_set_1: case Builtin::BI__sync_lock_test_and_set_2: case Builtin::BI__sync_lock_test_and_set_4: case Builtin::BI__sync_lock_test_and_set_8: case Builtin::BI__sync_lock_test_and_set_16: - BuiltinIndex = 14; + BuiltinIndex = 14; break; - + case Builtin::BI__sync_lock_release: case Builtin::BI__sync_lock_release_1: case Builtin::BI__sync_lock_release_2: @@ -4894,14 +4894,14 @@ Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { NumFixed = 0; ResultType = Context.VoidTy; break; - - case Builtin::BI__sync_swap: + + case Builtin::BI__sync_swap: case Builtin::BI__sync_swap_1: case Builtin::BI__sync_swap_2: case Builtin::BI__sync_swap_4: case Builtin::BI__sync_swap_8: case Builtin::BI__sync_swap_16: - BuiltinIndex = 16; + BuiltinIndex = 16; break; } @@ -5410,7 +5410,7 @@ bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { } } } - + return false; } @@ -5787,13 +5787,13 @@ bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, Expr *Arg = TheCall->getArg(ArgNum); DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); - + if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; - + if (!Arg->isIntegerConstantExpr(Result, Context)) return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type) << FDecl->getDeclName() << Arg->getSourceRange(); - + return false; } @@ -5964,7 +5964,7 @@ bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { // TODO: This is less than ideal. Overload this to take a value. if (SemaBuiltinConstantArg(TheCall, 1, Result)) return true; - + if (Result != 1) return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val) << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); @@ -6231,7 +6231,7 @@ checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, // cannot contain format specifiers and thus are not a security // liability. return SLCT_UncheckedLiteral; - + case Stmt::DeclRefExprClass: { const DeclRefExpr *DR = cast<DeclRefExpr>(E); @@ -6626,14 +6626,14 @@ protected: void HandlePositionalNonpositionalArgs(SourceLocation Loc, const char *startSpec, unsigned specifierLen); - + SourceRange getFormatStringRange(); CharSourceRange getSpecifierRange(const char *startSpecifier, unsigned specifierLen); SourceLocation getLocationOfByte(const char *x); const Expr *getDataArg(unsigned i) const; - + bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, const analyze_format_string::ConversionSpecifier &CS, const char *startSpecifier, unsigned specifierLen, @@ -7052,7 +7052,7 @@ public: const char *startSpecifier, unsigned specifierLen); bool checkForCStrMembers(const analyze_printf::ArgType &AT, const Expr *E); - + void HandleEmptyObjCModifierFlag(const char *startFlag, unsigned flagLen) override; @@ -7061,7 +7061,7 @@ public: void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, const char *flagsEnd, - const char *conversionPosition) + const char *conversionPosition) override; }; @@ -7073,7 +7073,7 @@ bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( unsigned specifierLen) { const analyze_printf::PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); - + return HandleInvalidConversionSpecifier(FS.getArgIndex(), getLocationOfByte(CS.getStart()), startSpecifier, specifierLen, @@ -7736,7 +7736,7 @@ CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, CastFix << ")"; SmallVector<FixItHint,4> Hints; - if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) + if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { @@ -7777,7 +7777,7 @@ CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, SpecRange, Hints); } else { // In this case, the expression could be printed using a different - // specifier, but we've decided that the specifier is probably correct + // specifier, but we've decided that the specifier is probably correct // and we should cast instead. Just use the normal warning message. EmitFormatDiagnostic( S.PDiag(diag::warn_format_conversion_argument_type_mismatch) @@ -7852,7 +7852,7 @@ CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, //===--- CHECK: Scanf format string checking ------------------------------===// -namespace { +namespace { class CheckScanfHandler : public CheckFormatHandler { public: @@ -7872,7 +7872,7 @@ public: bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, const char *startSpecifier, unsigned specifierLen) override; - + bool HandleInvalidScanfConversionSpecifier( const analyze_scanf::ScanfSpecifier &FS, const char *startSpecifier, @@ -7908,7 +7908,7 @@ bool CheckScanfHandler::HandleScanfSpecifier( const char *startSpecifier, unsigned specifierLen) { using namespace analyze_scanf; - using namespace analyze_format_string; + using namespace analyze_format_string; const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); @@ -7925,7 +7925,7 @@ bool CheckScanfHandler::HandleScanfSpecifier( return false; } } - + // Check if the field with is non-zero. const OptionalAmount &Amt = FS.getFieldWidth(); if (Amt.getHowSpecified() == OptionalAmount::Constant) { @@ -8981,7 +8981,7 @@ void Sema::CheckMemaccessArguments(const CallExpr *Call, else if (BId == Builtin::BImemcmp) OperationType = 3; } - + DiagRuntimeBehavior( Dest->getExprLoc(), Dest, PDiag(diag::warn_dyn_class_memaccess) @@ -9035,7 +9035,7 @@ static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); - + if (isa<IntegerLiteral>(RHS)) Ex = LHS; else if (isa<IntegerLiteral>(LHS)) @@ -9077,7 +9077,7 @@ void Sema::CheckStrlcpycatArguments(const CallExpr *Call, if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, Call->getLocStart(), Call->getRParenLoc())) return; - + // Look for 'strlcpy(dst, x, sizeof(x))' if (const Expr *Ex = getSizeOfExprArg(SizeArg)) CompareWithSrc = Ex; @@ -9100,16 +9100,16 @@ void Sema::CheckStrlcpycatArguments(const CallExpr *Call, const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); if (!SrcArgDRE) return; - + const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); - if (!CompareWithSrcDRE || + if (!CompareWithSrcDRE || SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) return; - + const Expr *OriginalSizeArg = Call->getArg(2); Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size) << OriginalSizeArg->getSourceRange() << FnName; - + // Output a FIXIT hint if the destination is an array (rather than a // pointer to an array). This could be enhanced to handle some // pointers if we know the actual size, like if DstArg is 'array+2' @@ -9123,7 +9123,7 @@ void Sema::CheckStrlcpycatArguments(const CallExpr *Call, OS << "sizeof("; DstArg->printPretty(OS, nullptr, getPrintingPolicy()); OS << ")"; - + Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size) << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), OS.str()); @@ -10271,7 +10271,7 @@ static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { } /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. -static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, +static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, SourceLocation CContext, unsigned diag, bool pruneControlFlow = false) { if (pruneControlFlow) { @@ -10876,7 +10876,7 @@ CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC, // We also want to warn about it in -Wconversion. // So if -Wconversion is off, use a completely identical diagnostic // in the sign-compare group. - // The conditional-checking code will + // The conditional-checking code will if (ICContext) { DiagID = diag::warn_impcast_integer_sign_conditional; *ICContext = true; @@ -10897,7 +10897,7 @@ CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC, Source = S.Context.getCanonicalType(SourceType).getTypePtr(); } } - + if (const EnumType *SourceEnum = Source->getAs<EnumType>()) if (const EnumType *TargetEnum = Target->getAs<EnumType>()) if (SourceEnum->getDecl()->hasNameForLinkage() && @@ -10906,7 +10906,7 @@ CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC, if (S.SourceMgr.isInSystemMacro(CC)) return; - return DiagnoseImpCast(S, E, SourceType, T, CC, + return DiagnoseImpCast(S, E, SourceType, T, CC, diag::warn_impcast_different_enum_types); } } @@ -10945,7 +10945,7 @@ static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, // ...then check whether it would have warned about either of the // candidates for a signedness conversion to the condition type. if (E->getType() == T) return; - + Suspicious = false; CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), E->getType(), CC, &Suspicious); @@ -12426,11 +12426,11 @@ namespace { } void VisitBlockExpr(BlockExpr *block) { - // Look inside nested blocks + // Look inside nested blocks if (block->getBlockDecl()->capturesVariable(Variable)) Visit(block->getBlockDecl()->getBody()); } - + void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { if (Capturer) return; if (OVE->getSourceExpr()) @@ -12483,7 +12483,7 @@ static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { } } } - + BlockExpr *block = dyn_cast<BlockExpr>(e); if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) return nullptr; @@ -12736,12 +12736,12 @@ void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { RetainCycleOwner Owner; if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) return; - + // Because we don't have an expression for the variable, we have to set the // location explicitly here. Owner.Loc = Var->getLocation(); Owner.Range = Var->getSourceRange(); - + if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) diagnoseRetainCycle(*this, Capturer, Owner); } @@ -12814,7 +12814,7 @@ void Sema::checkUnsafeExprAssigns(SourceLocation Loc, if (PD) LHSType = PD->getType(); } - + if (LHSType.isNull()) LHSType = LHS->getType(); @@ -12831,14 +12831,14 @@ void Sema::checkUnsafeExprAssigns(SourceLocation Loc, // FIXME. Check for other life times. if (LT != Qualifiers::OCL_None) return; - + if (PRE) { if (PRE->isImplicitProperty()) return; const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); if (!PD) return; - + unsigned Attributes = PD->getPropertyAttributes(); if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { // when 'assign' attribute was not explicitly specified @@ -12848,7 +12848,7 @@ void Sema::checkUnsafeExprAssigns(SourceLocation Loc, if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && LHSType->isObjCRetainableType()) return; - + while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { if (cast->getCastKind() == CK_ARCConsumeObject) { Diag(Loc, diag::warn_arc_retained_property_assign) diff --git a/lib/Sema/SemaCodeComplete.cpp b/lib/Sema/SemaCodeComplete.cpp index 4e571eba17e9..30af826ef6cc 100644 --- a/lib/Sema/SemaCodeComplete.cpp +++ b/lib/Sema/SemaCodeComplete.cpp @@ -1303,34 +1303,8 @@ namespace { void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx, bool InBaseClass) override { bool Accessible = true; - if (Ctx) { - DeclContext *AccessingCtx = Ctx; - // If ND comes from a base class, set the naming class back to the - // derived class if the search starts from the derived class (i.e. - // InBaseClass is true). - // - // Example: - // class B { protected: int X; } - // class D : public B { void f(); } - // void D::f() { this->^; } - // The completion after "this->" will have `InBaseClass` set to true and - // `Ctx` set to "B", when looking up in `B`. We need to set the actual - // accessing context (i.e. naming class) to "D" so that access can be - // calculated correctly. - if (InBaseClass && isa<CXXRecordDecl>(Ctx)) { - CXXRecordDecl *RC = nullptr; - // Get the enclosing record. - for (DeclContext *DC = CurContext; !DC->isFileContext(); - DC = DC->getParent()) { - if ((RC = dyn_cast<CXXRecordDecl>(DC))) - break; - } - if (RC) - AccessingCtx = RC; - } - Accessible = Results.getSema().IsSimplyAccessible(ND, AccessingCtx); - } - + if (Ctx) + Accessible = Results.getSema().IsSimplyAccessible(ND, Ctx); ResultBuilder::Result Result(ND, Results.getBasePriority(ND), nullptr, false, Accessible, FixIts); Results.AddResult(Result, CurContext, Hiding, InBaseClass); diff --git a/lib/Sema/SemaDecl.cpp b/lib/Sema/SemaDecl.cpp index 55542828f783..b92d76ad4204 100644 --- a/lib/Sema/SemaDecl.cpp +++ b/lib/Sema/SemaDecl.cpp @@ -3182,7 +3182,7 @@ bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, if (OldTypeInfo.getNoCallerSavedRegs() != NewTypeInfo.getNoCallerSavedRegs()) { if (NewTypeInfo.getNoCallerSavedRegs()) { - AnyX86NoCallerSavedRegistersAttr *Attr = + AnyX86NoCallerSavedRegistersAttr *Attr = New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; Diag(OldLocation, diag::note_previous_declaration); @@ -6008,6 +6008,31 @@ static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { << Attr; ND.dropAttr<NotTailCalledAttr>(); } + + // Check the attributes on the function type, if any. + if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { + // Don't declare this variable in the second operand of the for-statement; + // GCC miscompiles that by ending its lifetime before evaluating the + // third operand. See gcc.gnu.org/PR86769. + AttributedTypeLoc ATL; + for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); + (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); + TL = ATL.getModifiedLoc()) { + // The [[lifetimebound]] attribute can be applied to the implicit object + // parameter of a non-static member function (other than a ctor or dtor) + // by applying it to the function type. + if (ATL.getAttrKind() == AttributedType::attr_lifetimebound) { + const auto *MD = dyn_cast<CXXMethodDecl>(FD); + if (!MD || MD->isStatic()) { + S.Diag(ATL.getAttrNameLoc(), diag::err_lifetimebound_no_object_param) + << !MD << ATL.getLocalSourceRange(); + } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { + S.Diag(ATL.getAttrNameLoc(), diag::err_lifetimebound_ctor_dtor) + << isa<CXXDestructorDecl>(MD) << ATL.getLocalSourceRange(); + } + } + } + } } static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, @@ -8049,6 +8074,29 @@ enum OpenCLParamType { RecordKernelParam }; +static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { + // Size dependent types are just typedefs to normal integer types + // (e.g. unsigned long), so we cannot distinguish them from other typedefs to + // integers other than by their names. + StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; + + // Remove typedefs one by one until we reach a typedef + // for a size dependent type. + QualType DesugaredTy = Ty; + do { + ArrayRef<StringRef> Names(SizeTypeNames); + auto Match = + std::find(Names.begin(), Names.end(), DesugaredTy.getAsString()); + if (Names.end() != Match) + return true; + + Ty = DesugaredTy; + DesugaredTy = Ty.getSingleStepDesugaredType(C); + } while (DesugaredTy != Ty); + + return false; +} + static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { if (PT->isPointerType()) { QualType PointeeType = PT->getPointeeType(); @@ -8061,8 +8109,13 @@ static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { return PtrKernelParam; } - // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can - // be used as builtin types. + // OpenCL v1.2 s6.9.k: + // Arguments to kernel functions in a program cannot be declared with the + // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and + // uintptr_t or a struct and/or union that contain fields declared to be one + // of these built-in scalar types. + if (isOpenCLSizeDependentType(S.getASTContext(), PT)) + return InvalidKernelParam; if (PT->isImageType()) return PtrKernelParam; @@ -8079,6 +8132,15 @@ static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { if (PT->isRecordType()) return RecordKernelParam; + // Look into an array argument to check if it has a forbidden type. + if (PT->isArrayType()) { + const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); + // Call ourself to check an underlying type of an array. Since the + // getPointeeOrArrayElementType returns an innermost type which is not an + // array, this recusive call only happens once. + return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); + } + return ValidKernelParam; } @@ -8124,8 +8186,20 @@ static void checkIsValidOpenCLKernelParameter( // of event_t type. // Do not diagnose half type since it is diagnosed as invalid argument // type for any function elsewhere. - if (!PT->isHalfType()) + if (!PT->isHalfType()) { S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; + + // Explain what typedefs are involved. + const TypedefType *Typedef = nullptr; + while ((Typedef = PT->getAs<TypedefType>())) { + SourceLocation Loc = Typedef->getDecl()->getLocation(); + // SourceLocation may be invalid for a built-in type. + if (Loc.isValid()) + S.Diag(Loc, diag::note_entity_declared_at) << PT; + PT = Typedef->desugar(); + } + } + D.setInvalidType(); return; @@ -8146,9 +8220,14 @@ static void checkIsValidOpenCLKernelParameter( SmallVector<const FieldDecl *, 4> HistoryStack; HistoryStack.push_back(nullptr); - const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); - VisitStack.push_back(PD); + // At this point we already handled everything except of a RecordType or + // an ArrayType of a RecordType. + assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."); + const RecordType *RecTy = + PT->getPointeeOrArrayElementType()->getAs<RecordType>(); + const RecordDecl *OrigRecDecl = RecTy->getDecl(); + VisitStack.push_back(RecTy->getDecl()); assert(VisitStack.back() && "First decl null?"); do { @@ -8167,7 +8246,15 @@ static void checkIsValidOpenCLKernelParameter( const RecordDecl *RD; if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { HistoryStack.push_back(Field); - RD = Field->getType()->castAs<RecordType>()->getDecl(); + + QualType FieldTy = Field->getType(); + // Other field types (known to be valid or invalid) are handled while we + // walk around RecordDecl::fields(). + assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && + "Unexpected type."); + const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); + + RD = FieldRecTy->castAs<RecordType>()->getDecl(); } else { RD = cast<RecordDecl>(Next); } @@ -8204,8 +8291,8 @@ static void checkIsValidOpenCLKernelParameter( S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; } - S.Diag(PD->getLocation(), diag::note_within_field_of_type) - << PD->getDeclName(); + S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) + << OrigRecDecl->getDeclName(); // We have an error, now let's go back up through history and show where // the offending field came from @@ -10720,7 +10807,7 @@ QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); InitializationKind Kind = InitializationKind::CreateForInit( VDecl->getLocation(), DirectInit, Init); - // FIXME: Initialization should not be taking a mutable list of inits. + // FIXME: Initialization should not be taking a mutable list of inits. SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, InitsCopy); @@ -11914,14 +12001,25 @@ void Sema::FinalizeDeclaration(Decl *ThisDecl) { NewAttr->setInherited(true); VD->addAttr(NewAttr); } - // CUDA E.2.9.4: Within the body of a __device__ or __global__ - // function, only __shared__ variables may be declared with - // static storage class. - if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() && - CUDADiagIfDeviceCode(VD->getLocation(), - diag::err_device_static_local_var) - << CurrentCUDATarget()) - VD->setInvalidDecl(); + // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__ + // function, only __shared__ variables or variables without any device + // memory qualifiers may be declared with static storage class. + // Note: It is unclear how a function-scope non-const static variable + // without device memory qualifier is implemented, therefore only static + // const variable without device memory qualifier is allowed. + [&]() { + if (!getLangOpts().CUDA) + return; + if (VD->hasAttr<CUDASharedAttr>()) + return; + if (VD->getType().isConstQualified() && + !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) + return; + if (CUDADiagIfDeviceCode(VD->getLocation(), + diag::err_device_static_local_var) + << CurrentCUDATarget()) + VD->setInvalidDecl(); + }(); } } @@ -13398,7 +13496,7 @@ void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { break; } } - + if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && !FD->hasAttr<ReturnsTwiceAttr>()) FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, diff --git a/lib/Sema/SemaDeclAttr.cpp b/lib/Sema/SemaDeclAttr.cpp index 320eabd5ec2f..77deed6047f4 100644 --- a/lib/Sema/SemaDeclAttr.cpp +++ b/lib/Sema/SemaDeclAttr.cpp @@ -1051,7 +1051,7 @@ static void handleConsumableAttr(Sema &S, Decl *D, const ParsedAttr &AL) { << AL.getName() << AANT_ArgumentIdentifier; return; } - + D->addAttr(::new (S.Context) ConsumableAttr(AL.getRange(), S.Context, DefaultState, AL.getAttributeSpellingListIndex())); @@ -1061,30 +1061,30 @@ static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD, const ParsedAttr &AL) { ASTContext &CurrContext = S.getASTContext(); QualType ThisType = MD->getThisType(CurrContext)->getPointeeType(); - + if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) { if (!RD->hasAttr<ConsumableAttr>()) { S.Diag(AL.getLoc(), diag::warn_attr_on_unconsumable_class) << RD->getNameAsString(); - + return false; } } - + return true; } static void handleCallableWhenAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (!checkAttributeAtLeastNumArgs(S, AL, 1)) return; - + if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL)) return; - + SmallVector<CallableWhenAttr::ConsumedState, 3> States; for (unsigned ArgIndex = 0; ArgIndex < AL.getNumArgs(); ++ArgIndex) { CallableWhenAttr::ConsumedState CallableState; - + StringRef StateString; SourceLocation Loc; if (AL.isArgIdent(ArgIndex)) { @@ -1102,10 +1102,10 @@ static void handleCallableWhenAttr(Sema &S, Decl *D, const ParsedAttr &AL) { << AL.getName() << StateString; return; } - + States.push_back(CallableState); } - + D->addAttr(::new (S.Context) CallableWhenAttr(AL.getRange(), S.Context, States.data(), States.size(), AL.getAttributeSpellingListIndex())); @@ -1113,7 +1113,7 @@ static void handleCallableWhenAttr(Sema &S, Decl *D, const ParsedAttr &AL) { static void handleParamTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) { ParamTypestateAttr::ConsumedState ParamState; - + if (AL.isArgIdent(0)) { IdentifierLoc *Ident = AL.getArgAsIdent(0); StringRef StateString = Ident->Ident->getName(); @@ -1129,7 +1129,7 @@ static void handleParamTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) { AL.getName() << AANT_ArgumentIdentifier; return; } - + // FIXME: This check is currently being done in the analysis. It can be // enabled here only after the parser propagates attributes at // template specialization definition, not declaration. @@ -1141,7 +1141,7 @@ static void handleParamTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) { // ReturnType.getAsString(); // return; //} - + D->addAttr(::new (S.Context) ParamTypestateAttr(AL.getRange(), S.Context, ParamState, AL.getAttributeSpellingListIndex())); @@ -1149,7 +1149,7 @@ static void handleParamTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) { static void handleReturnTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) { ReturnTypestateAttr::ConsumedState ReturnState; - + if (AL.isArgIdent(0)) { IdentifierLoc *IL = AL.getArgAsIdent(0); if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(), @@ -1163,7 +1163,7 @@ static void handleReturnTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) { AL.getName() << AANT_ArgumentIdentifier; return; } - + // FIXME: This check is currently being done in the analysis. It can be // enabled here only after the parser propagates attributes at // template specialization definition, not declaration. @@ -1175,9 +1175,9 @@ static void handleReturnTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) { //} else if (const CXXConstructorDecl *Constructor = // dyn_cast<CXXConstructorDecl>(D)) { // ReturnType = Constructor->getThisType(S.getASTContext())->getPointeeType(); - // + // //} else { - // + // // ReturnType = cast<FunctionDecl>(D)->getCallResultType(); //} // @@ -1197,7 +1197,7 @@ static void handleReturnTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) { static void handleSetTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL)) return; - + SetTypestateAttr::ConsumedState NewState; if (AL.isArgIdent(0)) { IdentifierLoc *Ident = AL.getArgAsIdent(0); @@ -1212,7 +1212,7 @@ static void handleSetTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) { AL.getName() << AANT_ArgumentIdentifier; return; } - + D->addAttr(::new (S.Context) SetTypestateAttr(AL.getRange(), S.Context, NewState, AL.getAttributeSpellingListIndex())); @@ -1221,8 +1221,8 @@ static void handleSetTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) { static void handleTestTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL)) return; - - TestTypestateAttr::ConsumedState TestState; + + TestTypestateAttr::ConsumedState TestState; if (AL.isArgIdent(0)) { IdentifierLoc *Ident = AL.getArgAsIdent(0); StringRef Param = Ident->Ident->getName(); @@ -1236,7 +1236,7 @@ static void handleTestTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) { AL.getName() << AANT_ArgumentIdentifier; return; } - + D->addAttr(::new (S.Context) TestTypestateAttr(AL.getRange(), S.Context, TestState, AL.getAttributeSpellingListIndex())); @@ -1980,7 +1980,7 @@ static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) { return; } } - + D->addAttr(::new (S.Context) AnalyzerNoReturnAttr(AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); @@ -2343,7 +2343,7 @@ static void handleAvailabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) { return; IdentifierLoc *Platform = AL.getArgAsIdent(0); unsigned Index = AL.getAttributeSpellingListIndex(); - + IdentifierInfo *II = Platform->Ident; if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty()) S.Diag(Platform->Loc, diag::warn_availability_unknown_platform) @@ -2533,7 +2533,7 @@ static void handleVisibilityAttr(Sema &S, Decl *D, const ParsedAttr &AL, << AL.getName() << TypeStr; return; } - + // Complain about attempts to use protected visibility on targets // (like Darwin) that don't support it. if (type == VisibilityAttr::Protected && @@ -2604,7 +2604,7 @@ static void handleObjCNSObject(Sema &S, Decl *D, const ParsedAttr &AL) { // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject)); // // In this case it follows tradition and suppresses an error in the above - // case. + // case. S.Diag(D->getLocation(), diag::warn_nsobject_attribute); } D->addAttr(::new (S.Context) @@ -2752,14 +2752,14 @@ static void handleWarnUnusedResult(Sema &S, Decl *D, const ParsedAttr &AL) { << AL.getName() << 1; return; } - + // If this is spelled as the standard C++17 attribute, but not in C++17, warn // about using it as an extension. if (!S.getLangOpts().CPlusPlus17 && AL.isCXX11Attribute() && !AL.getScopeName()) S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL.getName(); - D->addAttr(::new (S.Context) + D->addAttr(::new (S.Context) WarnUnusedResultAttr(AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); } @@ -2892,7 +2892,7 @@ bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) { std::string Error = Context.getTargetInfo().isValidSectionSpecifier(SecName); if (!Error.empty()) { Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error - << 1 /*'section'*/; + << 1 /*'section'*/; return false; } return true; @@ -3191,7 +3191,7 @@ static void handleInitPriorityAttr(Sema &S, Decl *D, const ParsedAttr &AL) { S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL.getName(); return; } - + if (S.getCurFunctionOrMethodDecl()) { S.Diag(AL.getLoc(), diag::err_init_priority_object_attr); AL.setInvalid(); @@ -3269,10 +3269,10 @@ static void handleFormatAttr(Sema &S, Decl *D, const ParsedAttr &AL) { // Check for supported formats. FormatAttrKind Kind = getFormatAttrKind(Format); - + if (Kind == IgnoredFormat) return; - + if (Kind == InvalidFormat) { S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL.getName() << II->getName(); @@ -3454,7 +3454,7 @@ static void handleAnnotateAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (I->getAnnotation() == Str) return; } - + D->addAttr(::new (S.Context) AnnotateAttr(AL.getRange(), S.Context, Str, AL.getAttributeSpellingListIndex())); @@ -4595,7 +4595,7 @@ static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D, << AL.getName() << 1 << AANT_ArgumentIdentifier; return; } - + if (!checkAttributeNumArgs(S, AL, 1)) return; @@ -4819,7 +4819,7 @@ static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) { const int EP_ObjCMethod = 1; const int EP_ObjCProperty = 2; - + SourceLocation loc = Attrs.getLoc(); QualType resultType; if (isa<ObjCMethodDecl>(D)) @@ -4887,7 +4887,7 @@ static void handleObjCBridgeAttr(Sema &S, Decl *D, const ParsedAttr &AL) { return; } } - + D->addAttr(::new (S.Context) ObjCBridgeAttr(AL.getRange(), S.Context, Parm->Ident, AL.getAttributeSpellingListIndex())); @@ -4901,7 +4901,7 @@ static void handleObjCBridgeMutableAttr(Sema &S, Decl *D, S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << AL.getName() << 0; return; } - + D->addAttr(::new (S.Context) ObjCBridgeMutableAttr(AL.getRange(), S.Context, Parm->Ident, AL.getAttributeSpellingListIndex())); @@ -5195,7 +5195,7 @@ static void handleMSP430InterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (!AL.isArgExpr(0)) { S.Diag(AL.getLoc(), diag::err_attribute_argument_type) << AL.getName() << AANT_ArgumentIntegerConstant; - return; + return; } // FIXME: Check for decl - it should be void ()(void). @@ -6150,6 +6150,9 @@ static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D, case ParsedAttr::AT_Restrict: handleRestrictAttr(S, D, AL); break; + case ParsedAttr::AT_LifetimeBound: + handleSimpleAttribute<LifetimeBoundAttr>(S, D, AL); + break; case ParsedAttr::AT_MayAlias: handleSimpleAttribute<MayAliasAttr>(S, D, AL); break; diff --git a/lib/Sema/SemaDeclObjC.cpp b/lib/Sema/SemaDeclObjC.cpp index e1b033ea8282..595cc76cd4a3 100644 --- a/lib/Sema/SemaDeclObjC.cpp +++ b/lib/Sema/SemaDeclObjC.cpp @@ -109,9 +109,33 @@ bool Sema::checkInitMethod(ObjCMethodDecl *method, return true; } -void Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, +/// Issue a warning if the parameter of the overridden method is non-escaping +/// but the parameter of the overriding method is not. +static bool diagnoseNoescape(const ParmVarDecl *NewD, const ParmVarDecl *OldD, + Sema &S) { + if (OldD->hasAttr<NoEscapeAttr>() && !NewD->hasAttr<NoEscapeAttr>()) { + S.Diag(NewD->getLocation(), diag::warn_overriding_method_missing_noescape); + S.Diag(OldD->getLocation(), diag::note_overridden_marked_noescape); + return false; + } + + return true; +} + +/// Produce additional diagnostics if a category conforms to a protocol that +/// defines a method taking a non-escaping parameter. +static void diagnoseNoescape(const ParmVarDecl *NewD, const ParmVarDecl *OldD, + const ObjCCategoryDecl *CD, + const ObjCProtocolDecl *PD, Sema &S) { + if (!diagnoseNoescape(NewD, OldD, S)) + S.Diag(CD->getLocation(), diag::note_cat_conform_to_noescape_prot) + << CD->IsClassExtension() << PD + << cast<ObjCMethodDecl>(NewD->getDeclContext()); +} + +void Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, const ObjCMethodDecl *Overridden) { - if (Overridden->hasRelatedResultType() && + if (Overridden->hasRelatedResultType() && !NewMethod->hasRelatedResultType()) { // This can only happen when the method follows a naming convention that // implies a related result type, and the original (overridden) method has @@ -119,9 +143,9 @@ void Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, // a suitable return type. QualType ResultType = NewMethod->getReturnType(); SourceRange ResultTypeRange = NewMethod->getReturnTypeSourceRange(); - + // Figure out which class this method is part of, if any. - ObjCInterfaceDecl *CurrentClass + ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(NewMethod->getDeclContext()); if (!CurrentClass) { DeclContext *DC = NewMethod->getDeclContext(); @@ -133,27 +157,27 @@ void Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, = dyn_cast<ObjCCategoryImplDecl>(DC)) CurrentClass = CatImpl->getClassInterface(); } - + if (CurrentClass) { - Diag(NewMethod->getLocation(), + Diag(NewMethod->getLocation(), diag::warn_related_result_type_compatibility_class) << Context.getObjCInterfaceType(CurrentClass) << ResultType << ResultTypeRange; } else { - Diag(NewMethod->getLocation(), + Diag(NewMethod->getLocation(), diag::warn_related_result_type_compatibility_protocol) << ResultType << ResultTypeRange; } - + if (ObjCMethodFamily Family = Overridden->getMethodFamily()) - Diag(Overridden->getLocation(), + Diag(Overridden->getLocation(), diag::note_related_result_type_family) << /*overridden method*/ 0 << Family; else - Diag(Overridden->getLocation(), + Diag(Overridden->getLocation(), diag::note_related_result_type_overridden); } @@ -192,13 +216,7 @@ void Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, Diag(oldDecl->getLocation(), diag::note_previous_decl) << "parameter"; } - // A parameter of the overriding method should be annotated with noescape - // if the corresponding parameter of the overridden method is annotated. - if (oldDecl->hasAttr<NoEscapeAttr>() && !newDecl->hasAttr<NoEscapeAttr>()) { - Diag(newDecl->getLocation(), - diag::warn_overriding_method_missing_noescape); - Diag(oldDecl->getLocation(), diag::note_overridden_marked_noescape); - } + diagnoseNoescape(newDecl, oldDecl, *this); } } @@ -232,7 +250,7 @@ bool Sema::CheckARCMethodDecl(ObjCMethodDecl *method) { return true; } return false; - + case OMF_init: // If the method doesn't obey the init rules, don't bother annotating it. if (checkInitMethod(method, QualType())) @@ -310,7 +328,7 @@ static void DiagnoseObjCImplementedDeprecations(Sema &S, const NamedDecl *ND, /// pool. void Sema::AddAnyMethodToGlobalPool(Decl *D) { ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D); - + // If we don't have a valid method decl, simply return. if (!MDecl) return; @@ -325,7 +343,7 @@ void Sema::AddAnyMethodToGlobalPool(Decl *D) { static bool HasExplicitOwnershipAttr(Sema &S, ParmVarDecl *Param) { QualType T = Param->getType(); - + if (const PointerType *PT = T->getAs<PointerType>()) { T = PT->getPointeeType(); } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) { @@ -333,8 +351,8 @@ HasExplicitOwnershipAttr(Sema &S, ParmVarDecl *Param) { } else { return true; } - - // If we have a lifetime qualifier, but it's local, we must have + + // If we have a lifetime qualifier, but it's local, we must have // inferred it. So, it is implicit. return !T.getLocalQualifiers().hasObjCLifetime(); } @@ -344,7 +362,7 @@ HasExplicitOwnershipAttr(Sema &S, ParmVarDecl *Param) { void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) { assert((getCurMethodDecl() == nullptr) && "Methodparsing confused"); ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D); - + // If we don't have a valid method decl, simply return. if (!MDecl) return; @@ -359,7 +377,7 @@ void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) { // Allow all of Sema to see that we are entering a method definition. PushDeclContext(FnBodyScope, MDecl); PushFunctionScope(); - + // Create Decl objects for each parameter, entrring them in the scope for // binding to their use. @@ -380,7 +398,7 @@ void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) { !HasExplicitOwnershipAttr(*this, Param)) Diag(Param->getLocation(), diag::warn_arc_strong_pointer_objc_pointer) << Param->getType(); - + if (Param->getIdentifier()) PushOnScopeChains(Param, FnBodyScope); } @@ -414,13 +432,13 @@ void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) { // Warn on deprecated methods under -Wdeprecated-implementations, // and prepare for warning on missing super calls. if (ObjCInterfaceDecl *IC = MDecl->getClassInterface()) { - ObjCMethodDecl *IMD = + ObjCMethodDecl *IMD = IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod()); - + if (IMD) { - ObjCImplDecl *ImplDeclOfMethodDef = + ObjCImplDecl *ImplDeclOfMethodDef = dyn_cast<ObjCImplDecl>(MDecl->getDeclContext()); - ObjCContainerDecl *ContDeclOfMethodDecl = + ObjCContainerDecl *ContDeclOfMethodDecl = dyn_cast<ObjCContainerDecl>(IMD->getDeclContext()); ObjCImplDecl *ImplDeclOfMethodDecl = nullptr; if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ContDeclOfMethodDecl)) @@ -463,12 +481,12 @@ void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) { } else if (Family == OMF_finalize) { if (Context.getLangOpts().getGC() != LangOptions::NonGC) getCurFunction()->ObjCShouldCallSuper = true; - + } else { const ObjCMethodDecl *SuperMethod = SuperClass->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod()); - getCurFunction()->ObjCShouldCallSuper = + getCurFunction()->ObjCShouldCallSuper = (SuperMethod && SuperMethod->hasAttr<ObjCRequiresSuperAttr>()); } } @@ -609,11 +627,11 @@ ActOnSuperClassOfClassInterface(Scope *S, // Handle type arguments on the superclass. TypeSourceInfo *SuperClassTInfo = nullptr; - if (!SuperTypeArgs.empty()) { + if (!SuperTypeArgs.empty()) { TypeResult fullSuperClassType = actOnObjCTypeArgsAndProtocolQualifiers( S, SuperLoc, - CreateParsedType(SuperClassType, + CreateParsedType(SuperClassType, nullptr), SuperTypeArgsRange.getBegin(), SuperTypeArgs, @@ -625,12 +643,12 @@ ActOnSuperClassOfClassInterface(Scope *S, if (!fullSuperClassType.isUsable()) return; - SuperClassType = GetTypeFromParser(fullSuperClassType.get(), + SuperClassType = GetTypeFromParser(fullSuperClassType.get(), &SuperClassTInfo); } if (!SuperClassTInfo) { - SuperClassTInfo = Context.getTrivialTypeSourceInfo(SuperClassType, + SuperClassTInfo = Context.getTrivialTypeSourceInfo(SuperClassType, SuperLoc); } @@ -834,7 +852,7 @@ static bool checkTypeParamListConsistency(Sema &S, // When the new type parameter is invariant and is not part // of the definition, just propagate the variance. newTypeParam->setVariance(prevTypeParam->getVariance()); - } else if (prevTypeParam->getVariance() + } else if (prevTypeParam->getVariance() == ObjCTypeParamVariance::Invariant && !(isa<ObjCInterfaceDecl>(prevTypeParam->getDeclContext()) && cast<ObjCInterfaceDecl>(prevTypeParam->getDeclContext()) @@ -993,7 +1011,7 @@ Decl *Sema::ActOnStartClassInterface( if (ObjCTypeParamList *prevTypeParamList = PrevIDecl->getTypeParamList()) { if (typeParamList) { // Both have type parameter lists; check for consistency. - if (checkTypeParamListConsistency(*this, prevTypeParamList, + if (checkTypeParamListConsistency(*this, prevTypeParamList, typeParamList, TypeParamListContext::Definition)) { typeParamList = nullptr; @@ -1020,7 +1038,7 @@ Decl *Sema::ActOnStartClassInterface( Context.getTrivialTypeSourceInfo(typeParam->getUnderlyingType()))); } - typeParamList = ObjCTypeParamList::create(Context, + typeParamList = ObjCTypeParamList::create(Context, SourceLocation(), clonedTypeParams, SourceLocation()); @@ -1045,18 +1063,18 @@ Decl *Sema::ActOnStartClassInterface( AddPragmaAttributes(TUScope, IDecl); PushOnScopeChains(IDecl, TUScope); - // Start the definition of this class. If we're in a redefinition case, there + // Start the definition of this class. If we're in a redefinition case, there // may already be a definition, so we'll end up adding to it. if (!IDecl->hasDefinition()) IDecl->startDefinition(); - + if (SuperName) { // Diagnose availability in the context of the @interface. ContextRAII SavedContext(*this, IDecl); - ActOnSuperClassOfClassInterface(S, AtInterfaceLoc, IDecl, - ClassName, ClassLoc, - SuperName, SuperLoc, SuperTypeArgs, + ActOnSuperClassOfClassInterface(S, AtInterfaceLoc, IDecl, + ClassName, ClassLoc, + SuperName, SuperLoc, SuperTypeArgs, SuperTypeArgsRange); } else { // we have a root class. IDecl->setEndOfDefinitionLoc(ClassLoc); @@ -1088,7 +1106,7 @@ void Sema::ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs, LookupOrdinaryName); if (!IDecl) return; - + if (const TypedefNameDecl *TDecl = dyn_cast_or_null<TypedefNameDecl>(IDecl)) { QualType T = TDecl->getUnderlyingType(); if (T->isObjCObjectType()) @@ -1157,7 +1175,7 @@ bool Sema::CheckForwardProtocolDeclarationForCircularDependency( IdentifierInfo *PName, SourceLocation &Ploc, SourceLocation PrevLoc, const ObjCList<ObjCProtocolDecl> &PList) { - + bool res = false; for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(), E = PList.end(); I != E; ++I) { @@ -1168,10 +1186,10 @@ bool Sema::CheckForwardProtocolDeclarationForCircularDependency( Diag(PrevLoc, diag::note_previous_definition); res = true; } - + if (!PDecl->hasDefinition()) continue; - + if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc, PDecl->getLocation(), PDecl->getReferencedProtocols())) res = true; @@ -1223,7 +1241,7 @@ Decl *Sema::ActOnStartProtocolInterface( PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName, ProtocolLoc, AtProtoInterfaceLoc, /*PrevDecl=*/PrevDecl); - + PushOnScopeChains(PDecl, TUScope); PDecl->startDefinition(); } @@ -1253,7 +1271,7 @@ static bool NestedProtocolHasNoDefinition(ObjCProtocolDecl *PDecl, UndefinedProtocol = PDecl; return true; } - + for (auto *PI : PDecl->protocols()) if (NestedProtocolHasNoDefinition(PI, UndefinedProtocol)) { UndefinedProtocol = PI; @@ -1300,7 +1318,7 @@ Sema::FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer, // case, do it. // FIXME: Recover nicely in the hidden case. ObjCProtocolDecl *UndefinedProtocol; - + if (WarnOnDeclarations && NestedProtocolHasNoDefinition(PDecl, UndefinedProtocol)) { Diag(Pair.second, diag::warn_undef_protocolref) << Pair.first; @@ -1393,7 +1411,7 @@ void Sema::actOnObjCTypeArgsOrProtocolQualifiers( unsigned numProtocolsResolved = 0; auto resolvedAsProtocols = [&] { assert(numProtocolsResolved == identifiers.size() && "Unresolved protocols"); - + // Determine whether the base type is a parameterized class, in // which case we want to warn about typos such as // "NSArray<NSObject>" (that should be NSArray<NSObject *>). @@ -1416,7 +1434,7 @@ void Sema::actOnObjCTypeArgsOrProtocolQualifiers( } for (unsigned i = 0, n = protocols.size(); i != n; ++i) { - ObjCProtocolDecl *&proto + ObjCProtocolDecl *&proto = reinterpret_cast<ObjCProtocolDecl *&>(protocols[i]); // For an objc container, delay protocol reference checking until after we // can set the objc decl as the availability context, otherwise check now. @@ -1458,7 +1476,7 @@ void Sema::actOnObjCTypeArgsOrProtocolQualifiers( } } } - + // All of the protocols listed also have type names, and at least // one is an Objective-C class name. Check whether all of the // protocol conformances are declared by the base class itself, in @@ -1533,7 +1551,7 @@ void Sema::actOnObjCTypeArgsOrProtocolQualifiers( // Local function that forms a reference to the given type or // Objective-C class declaration. - auto resolveTypeReference = [&](TypeOrClassDecl typeDecl, SourceLocation loc) + auto resolveTypeReference = [&](TypeOrClassDecl typeDecl, SourceLocation loc) -> TypeResult { // Form declaration specifiers. They simply refer to the type. DeclSpec DS(attrFactory); @@ -1749,10 +1767,10 @@ Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc, ObjCProtocolDecl *PrevDecl = LookupProtocol(Ident, IdentPair.second, forRedeclarationInCurContext()); ObjCProtocolDecl *PDecl - = ObjCProtocolDecl::Create(Context, CurContext, Ident, + = ObjCProtocolDecl::Create(Context, CurContext, Ident, IdentPair.second, AtProtocolLoc, PrevDecl); - + PushOnScopeChains(PDecl, TUScope); CheckObjCDeclScope(PDecl); @@ -1780,7 +1798,7 @@ Decl *Sema::ActOnStartCategoryInterface( /// Check that class of this category is already completely declared. - if (!IDecl + if (!IDecl || RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl), diag::err_category_forward_interface, CategoryName == nullptr)) { @@ -1792,7 +1810,7 @@ Decl *Sema::ActOnStartCategoryInterface( IDecl, typeParamList); CDecl->setInvalidDecl(); CurContext->addDecl(CDecl); - + if (!IDecl) Diag(ClassLoc, diag::err_undef_interface) << ClassName; return ActOnObjCContainerStartDefinition(CDecl); @@ -1800,7 +1818,7 @@ Decl *Sema::ActOnStartCategoryInterface( if (!CategoryName && IDecl->getImplementation()) { Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName; - Diag(IDecl->getImplementation()->getLocation(), + Diag(IDecl->getImplementation()->getLocation(), diag::note_implementation_declared); } @@ -1853,8 +1871,8 @@ Decl *Sema::ActOnStartCategoryInterface( ProtoLocs, Context); // Protocols in the class extension belong to the class. if (CDecl->IsClassExtension()) - IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl*const*)ProtoRefs, - NumProtoRefs, Context); + IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl*const*)ProtoRefs, + NumProtoRefs, Context); } CheckObjCDeclScope(CDecl); @@ -1915,7 +1933,7 @@ Decl *Sema::ActOnStartCategoryImplementation( CDecl->setInvalidDecl(); } else { CatIDecl->setImplementation(CDecl); - // Warn on implementating category of deprecated class under + // Warn on implementating category of deprecated class under // -Wdeprecated-implementations flag. DiagnoseObjCImplementedDeprecations(*this, CatIDecl, CDecl->getLocation()); @@ -2009,7 +2027,7 @@ Decl *Sema::ActOnStartClassImplementation( } else { IDecl->setEndOfDefinitionLoc(ClassLoc); } - + PushOnScopeChains(IDecl, TUScope); } else { // Mark the interface as being completed, even if it was just as @@ -2036,7 +2054,7 @@ Decl *Sema::ActOnStartClassImplementation( } else { // add it to the list. IDecl->setImplementation(IMPDecl); PushOnScopeChains(IMPDecl, TUScope); - // Warn on implementating deprecated class under + // Warn on implementating deprecated class under // -Wdeprecated-implementations flag. DiagnoseObjCImplementedDeprecations(*this, IDecl, IMPDecl->getLocation()); } @@ -2090,7 +2108,7 @@ void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, IDecl->makeDeclVisibleInContext(ivars[i]); ImpDecl->addDecl(ivars[i]); } - + return; } // If implementation has empty ivar list, just return. @@ -2103,17 +2121,17 @@ void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use); for (unsigned i = 0; i < numIvars; i++) { ObjCIvarDecl* ImplIvar = ivars[i]; - if (const ObjCIvarDecl *ClsIvar = + if (const ObjCIvarDecl *ClsIvar = IDecl->getIvarDecl(ImplIvar->getIdentifier())) { - Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration); + Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration); Diag(ClsIvar->getLocation(), diag::note_previous_definition); continue; } // Check class extensions (unnamed categories) for duplicate ivars. for (const auto *CDecl : IDecl->visible_extensions()) { - if (const ObjCIvarDecl *ClsExtIvar = + if (const ObjCIvarDecl *ClsExtIvar = CDecl->getIvarDecl(ImplIvar->getIdentifier())) { - Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration); + Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration); Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); continue; } @@ -2194,8 +2212,8 @@ static void WarnUndefinedMethod(Sema &S, SourceLocation ImpLoc, } /// Determines if type B can be substituted for type A. Returns true if we can -/// guarantee that anything that the user will do to an object of type A can -/// also be done to an object of type B. This is trivially true if the two +/// guarantee that anything that the user will do to an object of type A can +/// also be done to an object of type B. This is trivially true if the two /// types are the same, or if B is a subclass of A. It becomes more complex /// in cases where protocols are involved. /// @@ -2204,12 +2222,12 @@ static void WarnUndefinedMethod(Sema &S, SourceLocation ImpLoc, /// example, if A is a subclass of B, then B* may refer to an instance of A. /// The principle of substitutability means that we may use an instance of A /// anywhere that we may use an instance of B - it will implement all of the -/// ivars of B and all of the methods of B. +/// ivars of B and all of the methods of B. /// -/// This substitutability is important when type checking methods, because +/// This substitutability is important when type checking methods, because /// the implementation may have stricter type definitions than the interface. /// The interface specifies minimum requirements, but the implementation may -/// have more accurate ones. For example, a method may privately accept +/// have more accurate ones. For example, a method may privately accept /// instances of B, but only publish that it accepts instances of A. Any /// object passed to it will be type checked against B, and so will implicitly /// by a valid A*. Similarly, a method may return a subclass of the class that @@ -2225,7 +2243,7 @@ static void WarnUndefinedMethod(Sema &S, SourceLocation ImpLoc, /// advertises, but it may be specified more accurately. This avoids the need /// for explicit down-casting by callers. /// -/// Note: This is a stricter requirement than for assignment. +/// Note: This is a stricter requirement than for assignment. static bool isObjCTypeSubstitutable(ASTContext &Context, const ObjCObjectPointerType *A, const ObjCObjectPointerType *B, @@ -2314,15 +2332,15 @@ static bool CheckMethodOverrideReturn(Sema &S, != 0)); S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration); } - + if (S.Context.hasSameUnqualifiedType(MethodImpl->getReturnType(), MethodDecl->getReturnType())) return true; if (!Warn) return false; - unsigned DiagID = - IsOverridingMode ? diag::warn_conflicting_overriding_ret_types + unsigned DiagID = + IsOverridingMode ? diag::warn_conflicting_overriding_ret_types : diag::warn_conflicting_ret_types; // Mismatches between ObjC pointers go into a different warning @@ -2338,8 +2356,8 @@ static bool CheckMethodOverrideReturn(Sema &S, if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false)) return false; - DiagID = - IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types + DiagID = + IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types : diag::warn_non_covariant_ret_types; } } @@ -2368,21 +2386,21 @@ static bool CheckMethodOverrideParam(Sema &S, IfaceVar->getObjCDeclQualifier())) { if (Warn) { if (IsOverridingMode) - S.Diag(ImplVar->getLocation(), + S.Diag(ImplVar->getLocation(), diag::warn_conflicting_overriding_param_modifiers) << getTypeRange(ImplVar->getTypeSourceInfo()) << MethodImpl->getDeclName(); - else S.Diag(ImplVar->getLocation(), + else S.Diag(ImplVar->getLocation(), diag::warn_conflicting_param_modifiers) << getTypeRange(ImplVar->getTypeSourceInfo()) << MethodImpl->getDeclName(); S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration) - << getTypeRange(IfaceVar->getTypeSourceInfo()); + << getTypeRange(IfaceVar->getTypeSourceInfo()); } else return false; } - + QualType ImplTy = ImplVar->getType(); QualType IfaceTy = IfaceVar->getType(); if (Warn && IsOverridingMode && @@ -2405,8 +2423,8 @@ static bool CheckMethodOverrideParam(Sema &S, if (!Warn) return false; - unsigned DiagID = - IsOverridingMode ? diag::warn_conflicting_overriding_param_types + unsigned DiagID = + IsOverridingMode ? diag::warn_conflicting_overriding_param_types : diag::warn_conflicting_param_types; // Mismatches between ObjC pointers go into a different warning @@ -2422,8 +2440,8 @@ static bool CheckMethodOverrideParam(Sema &S, if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true)) return false; - DiagID = - IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types + DiagID = + IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types : diag::warn_non_contravariant_param_types; } } @@ -2431,8 +2449,8 @@ static bool CheckMethodOverrideParam(Sema &S, S.Diag(ImplVar->getLocation(), DiagID) << getTypeRange(ImplVar->getTypeSourceInfo()) << MethodImpl->getDeclName() << IfaceTy << ImplTy; - S.Diag(IfaceVar->getLocation(), - (IsOverridingMode ? diag::note_previous_declaration + S.Diag(IfaceVar->getLocation(), + (IsOverridingMode ? diag::note_previous_declaration : diag::note_previous_definition)) << getTypeRange(IfaceVar->getTypeSourceInfo()); return false; @@ -2517,8 +2535,8 @@ void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl, checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl)) return; - CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl, - IsProtocolMethodDecl, false, + CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl, + IsProtocolMethodDecl, false, true); for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(), @@ -2530,7 +2548,7 @@ void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl, } if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) { - Diag(ImpMethodDecl->getLocation(), + Diag(ImpMethodDecl->getLocation(), diag::warn_conflicting_variadic); Diag(MethodDecl->getLocation(), diag::note_previous_declaration); } @@ -2539,11 +2557,11 @@ void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl, void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method, ObjCMethodDecl *Overridden, bool IsProtocolMethodDecl) { - - CheckMethodOverrideReturn(*this, Method, Overridden, - IsProtocolMethodDecl, true, + + CheckMethodOverrideReturn(*this, Method, Overridden, + IsProtocolMethodDecl, true, true); - + for (ObjCMethodDecl::param_iterator IM = Method->param_begin(), IF = Overridden->param_begin(), EM = Method->param_end(), EF = Overridden->param_end(); @@ -2551,9 +2569,9 @@ void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method, CheckMethodOverrideParam(*this, Method, Overridden, *IM, *IF, IsProtocolMethodDecl, true, true); } - + if (Method->isVariadic() != Overridden->isVariadic()) { - Diag(Method->getLocation(), + Diag(Method->getLocation(), diag::warn_conflicting_overriding_variadic); Diag(Overridden->getLocation(), diag::note_previous_declaration); } @@ -2569,20 +2587,20 @@ void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl, // to implement it. if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional) return; - // don't issue warning when primary class's method is + // don't issue warning when primary class's method is // depecated/unavailable. if (MethodDecl->hasAttr<UnavailableAttr>() || MethodDecl->hasAttr<DeprecatedAttr>()) return; - - bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl, + + bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl, IsProtocolMethodDecl, false, false); if (match) for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(), IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(), EF = MethodDecl->param_end(); IM != EM && IF != EF; ++IM, ++IF) { - match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, + match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF, IsProtocolMethodDecl, false, false); if (!match) @@ -2593,9 +2611,9 @@ void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl, if (match) match = !(MethodDecl->isClassMethod() && MethodDecl->getSelector() == GetNullarySelector("load", Context)); - + if (match) { - Diag(ImpMethodDecl->getLocation(), + Diag(ImpMethodDecl->getLocation(), diag::warn_category_method_impl_match); Diag(MethodDecl->getLocation(), diag::note_method_declared_at) << MethodDecl->getDeclName(); @@ -2644,10 +2662,10 @@ static void CheckProtocolMethodDefs(Sema &S, ObjCContainerDecl *CDecl, LazyProtocolNameSet &ProtocolsExplictImpl) { ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl); - ObjCInterfaceDecl *IDecl = C ? C->getClassInterface() + ObjCInterfaceDecl *IDecl = C ? C->getClassInterface() : dyn_cast<ObjCInterfaceDecl>(CDecl); assert (IDecl && "CheckProtocolMethodDefs - IDecl is null"); - + ObjCInterfaceDecl *Super = IDecl->getSuperClass(); ObjCInterfaceDecl *NSIDecl = nullptr; @@ -2696,7 +2714,7 @@ static void CheckProtocolMethodDefs(Sema &S, if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition()) PDecl = PDecl->getDefinition(); - + // If a method lookup fails locally we still need to look and see if // the method was implemented by a base class or an inherited // protocol. This lookup is slow, but occurs rarely in correct code @@ -2715,10 +2733,10 @@ static void CheckProtocolMethodDefs(Sema &S, nullptr /* category */))) { // If a method is not implemented in the category implementation but // has been declared in its primary class, superclass, - // or in one of their protocols, no need to issue the warning. - // This is because method will be implemented in the primary class + // or in one of their protocols, no need to issue the warning. + // This is because method will be implemented in the primary class // or one of its super class implementation. - + // Ugly, but necessary. Method declared in protocol might have // have been synthesized due to a property declared in the class which // uses the protocol. @@ -2828,7 +2846,7 @@ void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap, } } } - + if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl> (CDecl)) { // Also, check for methods declared in protocols inherited by // this protocol. @@ -2837,7 +2855,7 @@ void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap, IMPDecl, PI, IncompleteImpl, false, WarnCategoryMethodImpl); } - + if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) { // when checking that methods in implementation match their declaration, // i.e. when WarnCategoryMethodImpl is false, check declarations in class @@ -2862,8 +2880,8 @@ void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap, IMPDecl, PI, IncompleteImpl, false, WarnCategoryMethodImpl); - // FIXME. For now, we are not checking for extact match of methods - // in category implementation and its primary class's super class. + // FIXME. For now, we are not checking for extact match of methods + // in category implementation and its primary class's super class. if (!WarnCategoryMethodImpl && I->getSuperClass()) MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, IMPDecl, @@ -2873,7 +2891,7 @@ void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap, /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in /// category matches with those implemented in its primary class and -/// warns each time an exact match is found. +/// warns each time an exact match is found. void Sema::CheckCategoryVsClassMethodMatches( ObjCCategoryImplDecl *CatIMPDecl) { // Get category's primary class. @@ -2885,7 +2903,7 @@ void Sema::CheckCategoryVsClassMethodMatches( return; ObjCInterfaceDecl *SuperIDecl = IDecl->getSuperClass(); SelectorSet InsMap, ClsMap; - + for (const auto *I : CatIMPDecl->instance_methods()) { Selector Sel = I->getSelector(); // When checking for methods implemented in the category, skip over @@ -2895,7 +2913,7 @@ void Sema::CheckCategoryVsClassMethodMatches( continue; InsMap.insert(Sel); } - + for (const auto *I : CatIMPDecl->class_methods()) { Selector Sel = I->getSelector(); if (SuperIDecl && SuperIDecl->lookupMethod(Sel, false)) @@ -2904,12 +2922,12 @@ void Sema::CheckCategoryVsClassMethodMatches( } if (InsMap.empty() && ClsMap.empty()) return; - + SelectorSet InsMapSeen, ClsMapSeen; bool IncompleteImpl = false; MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, CatIMPDecl, IDecl, - IncompleteImpl, false, + IncompleteImpl, false, true /*WarnCategoryMethodImpl*/); } @@ -2959,10 +2977,10 @@ void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl, MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, IMPDecl, CDecl, IncompleteImpl, true); - + // check all methods implemented in category against those declared // in its primary class. - if (ObjCCategoryImplDecl *CatDecl = + if (ObjCCategoryImplDecl *CatDecl = dyn_cast<ObjCCategoryImplDecl>(IMPDecl)) CheckCategoryVsClassMethodMatches(CatDecl); @@ -2987,7 +3005,7 @@ void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl, ExplicitImplProtocols); DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, /*SynthesizeProperties=*/false); - } + } } else llvm_unreachable("invalid ObjCContainerDecl type."); } @@ -3002,7 +3020,7 @@ Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc, for (unsigned i = 0; i != NumElts; ++i) { // Check for another declaration kind with the same name. NamedDecl *PrevDecl - = LookupSingleName(TUScope, IdentList[i], IdentLocs[i], + = LookupSingleName(TUScope, IdentList[i], IdentLocs[i], LookupOrdinaryName, forRedeclarationInCurContext()); if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) { // GCC apparently allows the following idiom: @@ -3029,7 +3047,7 @@ Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc, } } } - + // Create a declaration to describe this forward declaration. ObjCInterfaceDecl *PrevIDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl); @@ -3120,7 +3138,7 @@ static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy, // Consider all the kinds of non-dependent canonical types: // - functions and arrays aren't possible as return and parameter types - + // - vector types of equal size can be arbitrarily mixed if (isa<VectorType>(left)) return isa<VectorType>(right); if (isa<VectorType>(right)) return false; @@ -3368,14 +3386,14 @@ void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, if (ExternalSource) ReadMethodPool(Method->getSelector()); - + GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector()); if (Pos == MethodPool.end()) Pos = MethodPool.insert(std::make_pair(Method->getSelector(), GlobalMethods())).first; Method->setDefined(impl); - + ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second; addMethodToGlobalList(&Entry, Method); } @@ -3503,7 +3521,7 @@ ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R, bool instance) { if (ExternalSource) ReadMethodPool(Sel); - + GlobalMethodPool::iterator Pos = MethodPool.find(Sel); if (Pos == MethodPool.end()) return nullptr; @@ -3553,7 +3571,7 @@ void Sema::DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> & break; } } - + if (issueDiagnostic) { if (issueError) Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R; @@ -3561,7 +3579,7 @@ void Sema::DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> & Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R; else Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R; - + Diag(Methods[0]->getLocStart(), issueError ? diag::note_possibility : diag::note_using) << Methods[0]->getSourceRange(); @@ -3584,7 +3602,7 @@ ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) { (Method->getMethod()->isDefined() || Method->getMethod()->isPropertyAccessor())) return Method->getMethod(); - + for (const ObjCMethodList *Method = &Methods.second; Method; Method = Method->getNext()) if (Method->getMethod() && @@ -3601,7 +3619,7 @@ HelperSelectorsForTypoCorrection( const unsigned MaxEditDistance = 1; unsigned BestEditDistance = MaxEditDistance + 1; std::string MethodName = Method->getSelector().getAsString(); - + unsigned MinPossibleEditDistance = abs((int)MethodName.size() - (int)Typo.size()); if (MinPossibleEditDistance > 0 && Typo.size() / MinPossibleEditDistance < 1) @@ -3676,7 +3694,7 @@ Sema::SelectorsForTypoCorrection(Selector Sel, Methods.push_back(M->getMethod()); } } - + SmallVector<const ObjCMethodDecl *, 8> SelectedMethods; for (unsigned i = 0, e = Methods.size(); i < e; i++) { HelperSelectorsForTypoCorrection(SelectedMethods, @@ -3686,11 +3704,11 @@ Sema::SelectorsForTypoCorrection(Selector Sel, } /// DiagnoseDuplicateIvars - -/// Check for duplicate ivars in the entire class at the start of +/// Check for duplicate ivars in the entire class at the start of /// \@implementation. This becomes necesssary because class extension can /// add ivars to a class in random order which will not be known until /// class's \@implementation is seen. -void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, +void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID) { for (auto *Ivar : ID->ivars()) { if (Ivar->isInvalidDecl()) @@ -3962,7 +3980,7 @@ Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods, if (const ObjCPropertyImplDecl *PIDecl = IC->FindPropertyImplDecl(Property->getIdentifier(), Property->getQueryKind())) - if (PIDecl->getPropertyImplementation() + if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic) continue; @@ -4089,12 +4107,12 @@ CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) { /// Check whether the declared result type of the given Objective-C /// method declaration is compatible with the method's class. /// -static Sema::ResultTypeCompatibilityKind +static Sema::ResultTypeCompatibilityKind CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method, ObjCInterfaceDecl *CurrentClass) { QualType ResultType = Method->getReturnType(); - // If an Objective-C method inherits its related result type, then its + // If an Objective-C method inherits its related result type, then its // declared result type must be compatible with its own class type. The // declared result type is compatible if: if (const ObjCObjectPointerType *ResultObjectType @@ -4103,25 +4121,25 @@ CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method, if (ResultObjectType->isObjCIdType() || ResultObjectType->isObjCQualifiedIdType()) return Sema::RTC_Compatible; - + if (CurrentClass) { - if (ObjCInterfaceDecl *ResultClass + if (ObjCInterfaceDecl *ResultClass = ResultObjectType->getInterfaceDecl()) { // - it is the same as the method's class type, or if (declaresSameEntity(CurrentClass, ResultClass)) return Sema::RTC_Compatible; - + // - it is a superclass of the method's class type if (ResultClass->isSuperClassOf(CurrentClass)) return Sema::RTC_Compatible; - } + } } else { // Any Objective-C pointer type might be acceptable for a protocol // method; we just don't know. return Sema::RTC_Unknown; } } - + return Sema::RTC_Incompatible; } @@ -4145,7 +4163,7 @@ public: if (it == S.MethodPool.end()) { if (!S.getExternalSource()) return; S.ReadMethodPool(selector); - + it = S.MethodPool.find(selector); if (it == S.MethodPool.end()) return; @@ -4193,7 +4211,7 @@ private: void searchFrom(ObjCProtocolDecl *protocol) { if (!protocol->hasDefinition()) return; - + // A method in a protocol declaration overrides declarations from // referenced ("parent") protocols. search(protocol->getReferencedProtocols()); @@ -4225,7 +4243,7 @@ private: // A method in a class declaration overrides declarations from if (!iface->hasDefinition()) return; - + // - categories, for (auto *Cat : iface->known_categories()) search(Cat); @@ -4342,11 +4360,11 @@ void Sema::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod, continue; // Conflicting properties are detected elsewhere. // Check for overriding methods - if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) || + if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) || isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext())) CheckConflictingOverridingMethod(ObjCMethod, overridden, isa<ObjCProtocolDecl>(overridden->getDeclContext())); - + if (CurrentClass && overridden->getDeclContext() != CurrentClass && isa<ObjCInterfaceDecl>(overridden->getDeclContext()) && !overridden->isImplicit() /* not meant for properties */) { @@ -4556,17 +4574,17 @@ Decl *Sema::ActOnMethodDeclaration( ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI); } - LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc, + LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc, LookupOrdinaryName, forRedeclarationInCurContext()); LookupName(R, S); if (R.isSingleResult()) { NamedDecl *PrevDecl = R.getFoundDecl(); if (S->isDeclScope(PrevDecl)) { - Diag(ArgInfo[i].NameLoc, - (MethodDefinition ? diag::warn_method_param_redefinition - : diag::warn_method_param_declaration)) + Diag(ArgInfo[i].NameLoc, + (MethodDefinition ? diag::warn_method_param_redefinition + : diag::warn_method_param_declaration)) << ArgInfo[i].Name; - Diag(PrevDecl->getLocation(), + Diag(PrevDecl->getLocation(), diag::note_previous_declaration); } } @@ -4597,7 +4615,7 @@ Decl *Sema::ActOnMethodDeclaration( Params.push_back(Param); } - + for (unsigned i = 0, e = CNumArgs; i != e; ++i) { ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param); QualType ArgType = Param->getType(); @@ -4610,7 +4628,7 @@ Decl *Sema::ActOnMethodDeclaration( Param->setDeclContext(ObjCMethod); Params.push_back(Param); } - + ObjCMethod->setMethodParams(Context, Params, SelectorLocs); ObjCMethod->setObjCDeclQualifier( CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier())); @@ -4643,6 +4661,22 @@ Decl *Sema::ActOnMethodDeclaration( << ObjCMethod->getDeclName(); } } + + // Warn if a method declared in a protocol to which a category or + // extension conforms is non-escaping and the implementation's method is + // escaping. + for (auto *C : IDecl->visible_categories()) + for (auto &P : C->protocols()) + if (auto *IMD = P->lookupMethod(ObjCMethod->getSelector(), + ObjCMethod->isInstanceMethod())) { + assert(ObjCMethod->parameters().size() == + IMD->parameters().size() && + "Methods have different number of parameters"); + auto OI = IMD->param_begin(), OE = IMD->param_end(); + auto NI = ObjCMethod->param_begin(); + for (; OI != OE; ++OI, ++NI) + diagnoseNoescape(*NI, *OI, C, P, *this); + } } } else { cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod); @@ -4696,12 +4730,12 @@ Decl *Sema::ActOnMethodDeclaration( case OMF_initialize: case OMF_performSelector: break; - + case OMF_alloc: case OMF_new: InferRelatedResultType = ObjCMethod->isClassMethod(); break; - + case OMF_init: case OMF_autorelease: case OMF_retain: @@ -4709,7 +4743,7 @@ Decl *Sema::ActOnMethodDeclaration( InferRelatedResultType = ObjCMethod->isInstanceMethod(); break; } - + if (InferRelatedResultType && !ObjCMethod->getReturnType()->isObjCIndependentClassType()) ObjCMethod->SetRelatedResultType(); @@ -4745,7 +4779,7 @@ bool Sema::CheckObjCDeclScope(Decl *D) { // an objc container, it means the parser missed emitting an error. if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext())) return false; - + Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope); D->setInvalidDecl(); @@ -4800,7 +4834,7 @@ VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T, SourceLocation IdLoc, IdentifierInfo *Id, bool Invalid) { - // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage + // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage // duration shall not be qualified by an address-space qualifier." // Since all parameters have automatic store duration, they can not have // an address space. @@ -4808,7 +4842,7 @@ VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T, Diag(IdLoc, diag::err_arg_with_address_space); Invalid = true; } - + // An @catch parameter must be an unqualified object pointer type; // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"? if (Invalid) { @@ -4827,11 +4861,11 @@ VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T, Invalid = true; Diag(IdLoc, diag::err_catch_param_not_objc_type); } - + VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id, T, TInfo, SC_None); New->setExceptionVariable(true); - + // In ARC, infer 'retaining' for variables of retainable type. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New)) Invalid = true; @@ -4843,7 +4877,7 @@ VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T, Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) { const DeclSpec &DS = D.getDeclSpec(); - + // We allow the "register" storage class on exception variables because // GCC did, but we drop it completely. Any other storage class is an error. if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { @@ -4863,12 +4897,12 @@ Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) { D.getMutableDeclSpec().ClearStorageClassSpecs(); DiagnoseFunctionSpecifiers(D.getDeclSpec()); - + // Check that there are no default arguments inside the type of this // exception object (C++ only). if (getLangOpts().CPlusPlus) CheckExtraCXXDefaultArguments(D); - + TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); QualType ExceptionType = TInfo->getType(); @@ -4877,21 +4911,21 @@ Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) { D.getIdentifierLoc(), D.getIdentifier(), D.isInvalidType()); - + // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). if (D.getCXXScopeSpec().isSet()) { Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm) << D.getCXXScopeSpec().getRange(); New->setInvalidDecl(); } - + // Add the parameter declaration into this scope. S->AddDecl(New); if (D.getIdentifier()) IdResolver.AddDecl(New); - + ProcessDeclAttributes(S, New, D); - + if (New->hasAttr<BlocksAttr>()) Diag(New->getLocation(), diag::err_block_on_nonlocal); return New; @@ -4901,7 +4935,7 @@ Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) { /// initialization. void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, SmallVectorImpl<ObjCIvarDecl*> &Ivars) { - for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv; + for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv; Iv= Iv->getNextIvar()) { QualType QT = Context.getBaseElementType(Iv->getType()); if (QT->isRecordType()) @@ -4917,11 +4951,11 @@ void Sema::DiagnoseUseOfUnimplementedSelectors() { for (unsigned I = 0, N = Sels.size(); I != N; ++I) ReferencedSelectors[Sels[I].first] = Sels[I].second; } - + // Warning will be issued only when selector table is // generated (which means there is at lease one implementation // in the TU). This is to match gcc's behavior. - if (ReferencedSelectors.empty() || + if (ReferencedSelectors.empty() || !Context.AnyObjCImplementation()) return; for (auto &SelectorAndLocation : ReferencedSelectors) { diff --git a/lib/Sema/SemaExceptionSpec.cpp b/lib/Sema/SemaExceptionSpec.cpp index df5bc9b82b96..134c76ef28c6 100644 --- a/lib/Sema/SemaExceptionSpec.cpp +++ b/lib/Sema/SemaExceptionSpec.cpp @@ -385,7 +385,7 @@ bool Sema::CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New) { OnFirstException = false; else OS << ", "; - + OS << E.getAsString(getPrintingPolicy()); } OS << ")"; diff --git a/lib/Sema/SemaExpr.cpp b/lib/Sema/SemaExpr.cpp index 60abd718e228..3dc6fb151cb7 100644 --- a/lib/Sema/SemaExpr.cpp +++ b/lib/Sema/SemaExpr.cpp @@ -248,7 +248,7 @@ bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, Diag(Loc, diag::err_deleted_inherited_ctor_use) << Ctor->getParent() << Ctor->getInheritedConstructor().getConstructor()->getParent(); - else + else Diag(Loc, diag::err_deleted_function_use); NoteDeletedFunction(FD); return true; @@ -401,7 +401,7 @@ void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, if (MissingNilLoc.isInvalid()) Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); else - Diag(MissingNilLoc, diag::warn_missing_sentinel) + Diag(MissingNilLoc, diag::warn_missing_sentinel) << int(calleeType) << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); @@ -423,7 +423,7 @@ ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { if (result.isInvalid()) return ExprError(); E = result.get(); } - + QualType Ty = E->getType(); assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); @@ -479,12 +479,12 @@ static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, const ObjCIvarDecl *IV = OIRE->getDecl(); if (!IV) return; - + DeclarationName MemberName = IV->getDeclName(); IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); if (!Member || !Member->isStr("isa")) return; - + const Expr *Base = OIRE->getBase(); QualType BaseType = Base->getType(); if (OIRE->isArrow()) @@ -536,7 +536,7 @@ ExprResult Sema::DefaultLvalueConversion(Expr *E) { if (result.isInvalid()) return ExprError(); E = result.get(); } - + // C++ [conv.lval]p1: // A glvalue of a non-function, non-array type T can be // converted to a prvalue. @@ -604,8 +604,8 @@ ExprResult Sema::DefaultLvalueConversion(Expr *E) { (void)isCompleteType(E->getExprLoc(), T); UpdateMarkingForLValueToRValue(E); - - // Loading a __weak object implicitly retains the value, so we need a cleanup to + + // Loading a __weak object implicitly retains the value, so we need a cleanup to // balance that. if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) Cleanup.setExprNeedsCleanups(true); @@ -614,14 +614,14 @@ ExprResult Sema::DefaultLvalueConversion(Expr *E) { nullptr, VK_RValue); // C11 6.3.2.1p2: - // ... if the lvalue has atomic type, the value has the non-atomic version + // ... if the lvalue has atomic type, the value has the non-atomic version // of the type of the lvalue ... if (const AtomicType *Atomic = T->getAs<AtomicType>()) { T = Atomic->getValueType().getUnqualifiedType(); Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), nullptr, VK_RValue); } - + return Res; } @@ -876,7 +876,7 @@ ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, E = ExprRes.get(); } } - + ExprResult ExprRes = DefaultArgumentPromotion(E); if (ExprRes.isInvalid()) return ExprError(); @@ -1011,7 +1011,7 @@ static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, CK_IntegralToFloating); return FloatTy; } - + // Convert both sides to the appropriate complex float. assert(IntTy->isComplexIntegerType()); QualType result = S.Context.getComplexType(FloatTy); @@ -1201,7 +1201,7 @@ static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, QualType ComplexType = S.Context.getComplexType(ScalarType); RHS = S.ImpCastExprToType(RHS.get(), ComplexType, CK_IntegralRealToComplex); - + return ComplexType; } @@ -1212,7 +1212,7 @@ static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, handleIntegerConversion<doIntegralCast, doComplexIntegralCast> (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); QualType ComplexType = S.Context.getComplexType(ScalarType); - + if (!IsCompAssign) LHS = S.ImpCastExprToType(LHS.get(), ComplexType, CK_IntegralRealToComplex); @@ -2099,7 +2099,7 @@ Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); LookupParsedName(R, S, &SS, !IvarLookupFollowUp); - // If the result might be in a dependent base class, this is a dependent + // If the result might be in a dependent base class, this is a dependent // id-expression. if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, @@ -2357,7 +2357,7 @@ Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, IdentifierInfo *II, bool AllowBuiltinCreation) { SourceLocation Loc = Lookup.getNameLoc(); ObjCMethodDecl *CurMethod = getCurMethodDecl(); - + // Check for error condition which is already reported. if (!CurMethod) return ExprError(); @@ -2445,7 +2445,7 @@ Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, Diag(Loc, diag::warn_implicitly_retains_self) << FixItHint::CreateInsertion(Loc, "self->"); } - + return Result; } } else if (CurMethod->isInstanceMethod()) { @@ -2918,7 +2918,7 @@ ExprResult Sema::BuildDeclarationNameExpr( if (!CapturedType.isNull()) type = CapturedType; } - + break; } @@ -2934,7 +2934,7 @@ ExprResult Sema::BuildDeclarationNameExpr( diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); break; } - + case Decl::Function: { if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { @@ -2959,7 +2959,7 @@ ExprResult Sema::BuildDeclarationNameExpr( valueKind = VK_LValue; break; } - + // C99 DR 316 says that, if a function type comes from a // function definition (without a prototype), that type is only // used for checking compatibility. Therefore, when referencing @@ -4029,11 +4029,11 @@ ExprResult Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind) { ExprResult PE = CheckPlaceholderExpr(E); - if (PE.isInvalid()) + if (PE.isInvalid()) return ExprError(); E = PE.get(); - + // Verify that the operand is valid. bool isInvalid = false; if (E->isTypeDependent()) { @@ -4562,7 +4562,7 @@ bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, diag::note_default_argument_declared_here); return true; } - + if (Param->hasUninstantiatedDefaultArg()) { Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); @@ -4664,7 +4664,7 @@ bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, "default argument expression has capturing blocks?"); } - // We already type-checked the argument, so we know it works. + // We already type-checked the argument, so we know it works. // Just mark all of the declarations in this potentially-evaluated expression // as being "referenced". MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), @@ -4861,7 +4861,7 @@ Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) Diag(FDecl->getLocStart(), diag::note_callee_decl) << FDecl; - + // This deletes the extra arguments. Call->setNumArgs(Context, NumParams); return true; @@ -4869,7 +4869,7 @@ Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, } SmallVector<Expr *, 8> AllArgs; VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); - + Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, Proto, 0, Args, AllArgs, CallType); if (Invalid) @@ -5275,11 +5275,11 @@ tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( // Check if the naming class in which the unresolved members were found is // related (same as or is a base of) to the enclosing class. - + if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) return; - - + + DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); // If the enclosing function is not dependent, then this lambda is // capture ready, so if we can capture this, do so. @@ -5625,7 +5625,7 @@ Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); } - + // If the function we're calling isn't a function prototype, but we have // a function prototype from a prior declaratiom, use that prototype. if (!FDecl->hasPrototype()) @@ -5643,7 +5643,7 @@ Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, PerformCopyInitialization(Entity, SourceLocation(), Arg); if (ArgE.isInvalid()) return true; - + Arg = ArgE.getAs<Expr>(); } else { @@ -5654,7 +5654,7 @@ Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, Arg = ArgE.getAs<Expr>(); } - + if (RequireCompleteType(Arg->getLocStart(), Arg->getType(), diag::err_call_incomplete_argument, Arg)) @@ -5728,7 +5728,7 @@ Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, InitializedEntity Entity = InitializedEntity::InitializeCompoundLiteralInit(TInfo); InitializationKind Kind - = InitializationKind::CreateCStyleCast(LParenLoc, + = InitializationKind::CreateCStyleCast(LParenLoc, SourceRange(LParenLoc, RParenLoc), /*InitList=*/true); InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); @@ -6007,11 +6007,11 @@ static bool breakDownVectorType(QualType type, uint64_t &len, assert(eltType->isScalarType()); return true; } - + // We allow lax conversion to and from non-vector types, but only if // they're real types (i.e. non-complex, non-pointer scalar types). if (!type->isRealType()) return false; - + len = 1; eltType = type; return true; @@ -6026,7 +6026,7 @@ static bool breakDownVectorType(QualType type, uint64_t &len, /// vector nor a real type. bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { assert(destTy->isVectorType() || srcTy->isVectorType()); - + // Disallow lax conversions between scalars and ExtVectors (these // conversions are allowed for other vector types because common headers // depend on them). Most scalar OP ExtVector cases are handled by the @@ -6039,13 +6039,13 @@ bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { QualType srcEltTy, destEltTy; if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; - + // ASTContext::getTypeSize will return the size rounded up to a // power of 2, so instead of using that, we need to use the raw // element size multiplied by the element count. uint64_t srcEltSize = Context.getTypeSize(srcEltTy); uint64_t destEltSize = Context.getTypeSize(destEltTy); - + return (srcLen * srcEltSize == destLen * destEltSize); } @@ -6053,7 +6053,7 @@ bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { /// known to be a vector type? bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { assert(destTy->isVectorType() || srcTy->isVectorType()); - + if (!Context.getLangOpts().LaxVectorConversions) return false; return areLaxCompatibleVectorTypes(srcTy, destTy); @@ -6211,9 +6211,9 @@ Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, if (getLangOpts().CPlusPlus && !castType->isVoidType() && !getSourceManager().isInSystemMacro(LParenLoc)) Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); - + CheckTollFreeBridgeCast(castType, CastExpr); - + CheckObjCBridgeRelatedCast(castType, CastExpr); DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); @@ -6250,7 +6250,7 @@ ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, SmallVector<Expr *, 8> initExprs; const VectorType *VTy = Ty->getAs<VectorType>(); unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); - + // '(...)' form of vector initialization in AltiVec: the number of // initializers must be one or must match the size of the vector. // If a single value is specified in the initializer then it will be @@ -6290,7 +6290,7 @@ ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, PrepareScalarCast(Literal, ElemTy)); return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); } - + initExprs.append(exprs, exprs + numExprs); } // FIXME: This means that pretty-printing the final AST will produce curly @@ -6787,7 +6787,7 @@ static QualType OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc) { - Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); + Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); if (Cond.isInvalid()) return QualType(); QualType CondTy = Cond.get()->getType(); @@ -7359,7 +7359,7 @@ ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, ExprValueKind VK = VK_RValue; ExprObjectKind OK = OK_Ordinary; ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; - QualType result = CheckConditionalOperands(Cond, LHS, RHS, + QualType result = CheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || RHS.isInvalid()) @@ -7431,7 +7431,7 @@ checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { // Treat lifetime mismatches as fatal. else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; - + // For GCC/MS compatibility, other qualifier mismatches are treated // as still compatible in C. else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; @@ -7778,7 +7778,7 @@ Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, // - conversions from 'Class' to the redefinition type if (RHSType->isObjCClassType() && - Context.hasSameType(LHSType, + Context.hasSameType(LHSType, Context.getObjCClassRedefinitionType())) { Kind = CK_BitCast; return Compatible; @@ -7845,10 +7845,10 @@ Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, // A* -> B* if (RHSType->isObjCObjectPointerType()) { Kind = CK_BitCast; - Sema::AssignConvertType result = + Sema::AssignConvertType result = checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && - result == Compatible && + result == Compatible && !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) result = IncompatibleObjCWeakRef; return result; @@ -7872,7 +7872,7 @@ Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, // - conversions to 'Class' from its redefinition type if (LHSType->isObjCClassType() && - Context.hasSameType(RHSType, + Context.hasSameType(RHSType, Context.getObjCClassRedefinitionType())) { return Compatible; } @@ -7881,7 +7881,7 @@ Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, } // Only under strict condition T^ is compatible with an Objective-C pointer. - if (RHSType->isBlockPointerType() && + if (RHSType->isBlockPointerType() && LHSType->isBlockCompatibleObjCPointerType(Context)) { if (ConvertRHS) maybeExtendBlockObject(RHS); @@ -8113,7 +8113,7 @@ Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl; } } - + CastKind Kind; Sema::AssignConvertType result = CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); @@ -8249,7 +8249,7 @@ static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, // The conversion to apply to the scalar before splatting it, // if necessary. CastKind scalarCast = CK_NoOp; - + if (vectorEltTy->isIntegralType(S.Context)) { if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || (scalarTy->isIntegerType() && @@ -8709,7 +8709,7 @@ QualType Sema::CheckRemainderOperands( if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) { - if (LHS.get()->getType()->hasIntegerRepresentation() && + if (LHS.get()->getType()->hasIntegerRepresentation() && RHS.get()->getType()->hasIntegerRepresentation()) return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, /*AllowBothBool*/getLangOpts().AltiVec, @@ -9061,7 +9061,7 @@ QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, // In C++ adding zero to a null pointer is defined. llvm::APSInt KnownVal; if (!getLangOpts().CPlusPlus || - (!IExp->isValueDependent() && + (!IExp->isValueDependent() && (!IExp->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) { // Check the conditions to see if this is the 'p = nullptr + n' idiom. bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( @@ -9138,7 +9138,7 @@ QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, Expr::NPC_ValueDependentIsNotNull)) { // In C++ adding zero to a null pointer is defined. llvm::APSInt KnownVal; - if (!getLangOpts().CPlusPlus || + if (!getLangOpts().CPlusPlus || (!RHS.get()->isValueDependent() && (!RHS.get()->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) { diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); @@ -10416,7 +10416,7 @@ QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, if (isError) return QualType(); } - + if (LHSType->isIntegerType()) LHS = ImpCastExprToType(LHS.get(), RHSType, LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); @@ -10425,7 +10425,7 @@ QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); return computeResultTy(); } - + // Handle block pointers. if (!IsRelational && RHSIsNull && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { @@ -10596,7 +10596,7 @@ inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, // Check vector operands differently. if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) return CheckVectorLogicalOperands(LHS, RHS, Loc); - + // Diagnose cases where the user write a logical and/or but probably meant a // bitwise one. We do this when the LHS is a non-bool integer and the RHS // is a constant. @@ -11120,7 +11120,7 @@ QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, << LHSType.getUnqualifiedType(); return QualType(); } - + AssignConvertType ConvTy; if (CompoundType.isNull()) { Expr *RHSCheck = RHS.get(); @@ -11357,7 +11357,7 @@ static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, // Otherwise, we just need a complete type. if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || checkArithmeticOnObjCPointer(S, OpLoc, Op)) - return QualType(); + return QualType(); } else if (ResType->isAnyComplexType()) { // C99 does not support ++/-- on complex types, we allow as an extension. S.Diag(OpLoc, diag::ext_integer_increment_complex) @@ -11397,7 +11397,7 @@ static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, return ResType.getUnqualifiedType(); } } - + /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). /// This routine allows us to typecheck complex/recursive expressions @@ -11557,7 +11557,7 @@ QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { Expr::LValueClassification lval = op->ClassifyLValue(Context); unsigned AddressOfError = AO_No_Error; - if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { + if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { bool sfinae = (bool)isSFINAEContext(); Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary : diag::ext_typecheck_addrof_temporary) @@ -11772,7 +11772,7 @@ static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, // ...except that certain expressions are never l-values in C. if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) VK = VK_RValue; - + return Result; } @@ -11910,7 +11910,7 @@ static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, if (SelArg0.startswith("performSelector")) Diag = diag::warn_objc_pointer_masking_performSelector; } - + S.Diag(OpLoc, Diag) << ObjCPointerExpr->getSourceRange(); } @@ -12209,7 +12209,7 @@ ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, else if (const ObjCIvarRefExpr *OIRE = dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); - + // Opc is not a compound assignment if CompResultTy is null. if (CompResultTy.isNull()) { if (ConvertHalfVec) @@ -12549,7 +12549,7 @@ ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, return ExprError(); } } - + ExprResult LHS = CheckPlaceholderExpr(LHSExpr); if (LHS.isInvalid()) return ExprError(); LHSExpr = LHS.get(); @@ -12762,7 +12762,7 @@ ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) << resultType << Input.get()->getSourceRange()); } - + // LNot always has type int. C99 6.5.3.3p5. // In C++, it's bool. C++ 5.3.1p8 resultType = Context.getLogicalOperationType(); @@ -12820,23 +12820,23 @@ bool Sema::isQualifiedMemberAccess(Expr *E) { if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { if (!DRE->getQualifier()) return false; - + ValueDecl *VD = DRE->getDecl(); if (!VD->isCXXClassMember()) return false; - + if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) return true; if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) return Method->isInstance(); - + return false; } - + if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { if (!ULE->getQualifier()) return false; - + for (NamedDecl *D : ULE->decls()) { if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { if (Method->isInstance()) @@ -12846,10 +12846,10 @@ bool Sema::isQualifiedMemberAccess(Expr *E) { break; } } - + return false; } - + return false; } @@ -13031,17 +13031,17 @@ ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, QualType ArgTy = TInfo->getType(); bool Dependent = ArgTy->isDependentType(); SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); - + // We must have at least one component that refers to the type, and the first // one is known to be a field designator. Verify that the ArgTy represents // a struct/union/class. if (!Dependent && !ArgTy->isRecordType()) - return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) + return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) << ArgTy << TypeRange); - + // Type must be complete per C99 7.17p3 because a declaring a variable // with an incomplete type would be ill-formed. - if (!Dependent + if (!Dependent && RequireCompleteType(BuiltinLoc, ArgTy, diag::err_offsetof_incomplete_type, TypeRange)) return ExprError(); @@ -13061,7 +13061,7 @@ ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, CurrentType = AT->getElementType(); } else CurrentType = Context.DependentTy; - + ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); if (IdxRval.isInvalid()) return ExprError(); @@ -13080,7 +13080,7 @@ ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, Exprs.push_back(Idx); continue; } - + // Offset of a field. if (CurrentType->isDependentType()) { // We have the offset of a field, but we can't look into the dependent @@ -13089,19 +13089,19 @@ ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, CurrentType = Context.DependentTy; continue; } - + // We need to have a complete type to look into. if (RequireCompleteType(OC.LocStart, CurrentType, diag::err_offsetof_incomplete_type)) return ExprError(); - + // Look for the designated field. const RecordType *RC = CurrentType->getAs<RecordType>(); - if (!RC) + if (!RC) return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) << CurrentType); RecordDecl *RD = RC->getDecl(); - + // C++ [lib.support.types]p5: // The macro offsetof accepts a restricted set of type arguments in this // International Standard. type shall be a POD structure or a POD union @@ -13122,7 +13122,7 @@ ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, << CurrentType)) DidWarnAboutNonPOD = true; } - + // Look for the field. LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); LookupQualifiedName(R, RD); @@ -13135,9 +13135,9 @@ ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, if (!MemberDecl) return ExprError(Diag(BuiltinLoc, diag::err_no_member) - << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, + << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd)); - + // C99 7.17p3: // (If the specified member is a bit-field, the behavior is undefined.) // @@ -13180,9 +13180,9 @@ ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, } else Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); - CurrentType = MemberDecl->getType().getNonReferenceType(); + CurrentType = MemberDecl->getType().getNonReferenceType(); } - + return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, Comps, Exprs, RParenLoc); } @@ -13193,7 +13193,7 @@ ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, ParsedType ParsedArgTy, ArrayRef<OffsetOfComponent> Components, SourceLocation RParenLoc) { - + TypeSourceInfo *ArgTInfo; QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); if (ArgTy.isNull()) @@ -13298,7 +13298,7 @@ void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, T = Context.getFunctionType(Context.DependentTy, None, EPI); Sig = Context.getTrivialTypeSourceInfo(T); } - + // GetTypeForDeclarator always produces a function type for a block // literal signature. Furthermore, it is always a FunctionProtoType // unless the function was written with a typedef. @@ -13376,7 +13376,7 @@ void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), /*CheckParameterNames=*/false); } - + // Finally we can process decl attributes. ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); @@ -13452,7 +13452,7 @@ ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, FunctionType::ExtInfo Ext = FTy->getExtInfo(); if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); - + // Turn protoless block types into nullary block types. if (isa<FunctionNoProtoType>(FTy)) { FunctionProtoType::ExtProtoInfo EPI; @@ -13500,7 +13500,7 @@ ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, if (getLangOpts().CPlusPlus && RetTy->isRecordType() && !BSI->TheDecl->isDependentContext()) computeNRVO(Body, BSI); - + BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); @@ -13674,7 +13674,7 @@ bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, if (!ID || !ID->getIdentifier()->isStr("NSString")) return false; } - + // Ignore any parens, implicit casts (should only be // array-to-pointer decays), and not-so-opaque values. The last is // important for making this trigger for property assignments. @@ -13907,7 +13907,7 @@ bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, PDecl && IFace && !IFace->hasDefinition()) Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) << IFace << PDecl; - + if (SecondType == Context.OverloadTy) NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, FirstType, /*TakingAddress=*/true); @@ -13917,7 +13917,7 @@ bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, if (Action == AA_Returning && ConvTy == IncompatiblePointer) EmitRelatedResultTypeNoteForReturn(DstType); - + if (Complained) *Complained = true; return isInvalid; @@ -13931,7 +13931,7 @@ ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; } } Diagnoser; - + return VerifyIntegerConstantExpression(E, Result, Diagnoser); } @@ -13941,16 +13941,16 @@ ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, bool AllowFold) { class IDDiagnoser : public VerifyICEDiagnoser { unsigned DiagID; - + public: IDDiagnoser(unsigned DiagID) : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } - + void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { S.Diag(Loc, DiagID) << SR; } } Diagnoser(DiagID); - + return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); } @@ -14516,19 +14516,19 @@ diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, // capture. } - -static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, + +static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, bool &SubCapturesAreNested, - QualType &CaptureType, + QualType &CaptureType, QualType &DeclRefType) { // Check whether we've already captured it. if (CSI->CaptureMap.count(Var)) { // If we found a capture, any subcaptures are nested. SubCapturesAreNested = true; - + // Retrieve the capture type for this variable. CaptureType = CSI->getCapture(Var).getCaptureType(); - + // Compute the type of an expression that refers to this variable. DeclRefType = CaptureType.getNonReferenceType(); @@ -14548,8 +14548,8 @@ static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDec // Only block literals, captured statements, and lambda expressions can // capture; other scopes don't work. -static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, - SourceLocation Loc, +static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, + SourceLocation Loc, const bool Diagnose, Sema &S) { if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) return getLambdaAwareParentOfDeclContext(DC); @@ -14560,11 +14560,11 @@ static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl * return nullptr; } -// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture +// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture // certain types of variables (unnamed, variably modified types etc.) // so check for eligibility. -static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, - SourceLocation Loc, +static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, + SourceLocation Loc, const bool Diagnose, Sema &S) { bool IsBlock = isa<BlockScopeInfo>(CSI); @@ -14586,7 +14586,7 @@ static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, if (Var->getType()->isVariablyModifiedType() && IsBlock) { if (Diagnose) { S.Diag(Loc, diag::err_ref_vm_type); - S.Diag(Var->getLocation(), diag::note_previous_decl) + S.Diag(Var->getLocation(), diag::note_previous_decl) << Var->getDeclName(); } return false; @@ -14631,21 +14631,21 @@ static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, } // Returns true if the capture by block was successful. -static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, - SourceLocation Loc, - const bool BuildAndDiagnose, +static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, + SourceLocation Loc, + const bool BuildAndDiagnose, QualType &CaptureType, - QualType &DeclRefType, + QualType &DeclRefType, const bool Nested, Sema &S) { Expr *CopyExpr = nullptr; bool ByRef = false; - + // Blocks are not allowed to capture arrays. if (CaptureType->isArrayType()) { if (BuildAndDiagnose) { S.Diag(Loc, diag::err_ref_array_type); - S.Diag(Var->getLocation(), diag::note_previous_decl) + S.Diag(Var->getLocation(), diag::note_previous_decl) << Var->getDeclName(); } return false; @@ -14703,7 +14703,7 @@ static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, // Block capture by copy introduces 'const'. CaptureType = CaptureType.getNonReferenceType().withConst(); DeclRefType = CaptureType; - + if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { // The capture logic needs the destructor, so make sure we mark it. @@ -14723,15 +14723,15 @@ static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, // the stack requires a const copy constructor. This is not true // of the copy/move done to move a __block variable to the heap. Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, - DeclRefType.withConst(), + DeclRefType.withConst(), VK_LValue, Loc); - + ExprResult Result = S.PerformCopyInitialization( InitializedEntity::InitializeBlock(Var->getLocation(), CaptureType, false), Loc, DeclRef); - + // Build a full-expression copy expression if initialization // succeeded and used a non-trivial constructor. Recover from // errors by pretending that the copy isn't necessary. @@ -14747,7 +14747,7 @@ static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, // Actually capture the variable. if (BuildAndDiagnose) - BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, + BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), CaptureType, CopyExpr); return true; @@ -14757,11 +14757,11 @@ static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, /// Capture the given variable in the captured region. static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, - VarDecl *Var, - SourceLocation Loc, - const bool BuildAndDiagnose, + VarDecl *Var, + SourceLocation Loc, + const bool BuildAndDiagnose, QualType &CaptureType, - QualType &DeclRefType, + QualType &DeclRefType, const bool RefersToCapturedVariable, Sema &S) { // By default, capture variables by reference. @@ -14799,7 +14799,7 @@ static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, RD->addDecl(Field); if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel); - + CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, DeclRefType, VK_LValue, Loc); Var->setReferenced(true); @@ -14810,14 +14810,14 @@ static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, if (BuildAndDiagnose) RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, SourceLocation(), CaptureType, CopyExpr); - - + + return true; } /// Create a field within the lambda class for the variable /// being captured. -static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, +static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, QualType FieldType, QualType DeclRefType, SourceLocation Loc, bool RefersToCapturedVariable) { @@ -14835,13 +14835,13 @@ static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, /// Capture the given variable in the lambda. static bool captureInLambda(LambdaScopeInfo *LSI, - VarDecl *Var, - SourceLocation Loc, - const bool BuildAndDiagnose, + VarDecl *Var, + SourceLocation Loc, + const bool BuildAndDiagnose, QualType &CaptureType, - QualType &DeclRefType, + QualType &DeclRefType, const bool RefersToCapturedVariable, - const Sema::TryCaptureKind Kind, + const Sema::TryCaptureKind Kind, SourceLocation EllipsisLoc, const bool IsTopScope, Sema &S) { @@ -14853,7 +14853,7 @@ static bool captureInLambda(LambdaScopeInfo *LSI, } else { ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); } - + // Compute the type of the field that will capture this variable. if (ByRef) { // C++11 [expr.prim.lambda]p15: @@ -14865,7 +14865,7 @@ static bool captureInLambda(LambdaScopeInfo *LSI, // // FIXME: It is not clear whether we want to build an lvalue reference // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears - // to do the former, while EDG does the latter. Core issue 1249 will + // to do the former, while EDG does the latter. Core issue 1249 will // clarify, but for now we follow GCC because it's a more permissive and // easily defensible position. CaptureType = S.Context.getLValueReferenceType(DeclRefType); @@ -14913,26 +14913,26 @@ static bool captureInLambda(LambdaScopeInfo *LSI, if (BuildAndDiagnose) addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc, RefersToCapturedVariable); - + // Compute the type of a reference to this captured variable. if (ByRef) DeclRefType = CaptureType.getNonReferenceType(); else { // C++ [expr.prim.lambda]p5: - // The closure type for a lambda-expression has a public inline - // function call operator [...]. This function call operator is - // declared const (9.3.1) if and only if the lambda-expression's + // The closure type for a lambda-expression has a public inline + // function call operator [...]. This function call operator is + // declared const (9.3.1) if and only if the lambda-expression's // parameter-declaration-clause is not followed by mutable. DeclRefType = CaptureType.getNonReferenceType(); if (!LSI->Mutable && !CaptureType->isReferenceType()) - DeclRefType.addConst(); + DeclRefType.addConst(); } - + // Add the capture. if (BuildAndDiagnose) - LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, + LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); - + return true; } @@ -14945,10 +14945,10 @@ bool Sema::tryCaptureVariable( DeclContext *VarDC = Var->getDeclContext(); if (Var->isInitCapture()) VarDC = VarDC->getParent(); - + DeclContext *DC = CurContext; - const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt - ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; + const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt + ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; // We need to sync up the Declaration Context with the // FunctionScopeIndexToStopAt if (FunctionScopeIndexToStopAt) { @@ -14959,7 +14959,7 @@ bool Sema::tryCaptureVariable( } } - + // If the variable is declared in the current context, there is no need to // capture it. if (VarDC == DC) return true; @@ -14975,7 +14975,7 @@ bool Sema::tryCaptureVariable( // performing the "simple" checks that don't depend on type. We stop when // we've either hit the declared scope of the variable or find an existing // capture of that variable. We start from the innermost capturing-entity - // (the DC) and ensure that all intervening capturing-entities + // (the DC) and ensure that all intervening capturing-entities // (blocks/lambdas etc.) between the innermost capturer and the variable`s // declcontext can either capture the variable or have already captured // the variable. @@ -14987,8 +14987,8 @@ bool Sema::tryCaptureVariable( do { // Only block literals, captured statements, and lambda expressions can // capture; other scopes don't work. - DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, - ExprLoc, + DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, + ExprLoc, BuildAndDiagnose, *this); // We need to check for the parent *first* because, if we *have* @@ -15007,29 +15007,29 @@ bool Sema::tryCaptureVariable( // Check whether we've already captured it. - if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, + if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, DeclRefType)) { CSI->getCapture(Var).markUsed(BuildAndDiagnose); break; } - // If we are instantiating a generic lambda call operator body, + // If we are instantiating a generic lambda call operator body, // we do not want to capture new variables. What was captured // during either a lambdas transformation or initial parsing - // should be used. + // should be used. if (isGenericLambdaCallOperatorSpecialization(DC)) { if (BuildAndDiagnose) { - LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); + LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); - Diag(Var->getLocation(), diag::note_previous_decl) + Diag(Var->getLocation(), diag::note_previous_decl) << Var->getDeclName(); - Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); + Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); } else diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); } return true; } - // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture + // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture // certain types of variables (unnamed, variably modified types etc.) // so check for eligibility. if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) @@ -15070,11 +15070,11 @@ bool Sema::tryCaptureVariable( } } if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { - // No capture-default, and this is not an explicit capture - // so cannot capture this variable. + // No capture-default, and this is not an explicit capture + // so cannot capture this variable. if (BuildAndDiagnose) { Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); - Diag(Var->getLocation(), diag::note_previous_decl) + Diag(Var->getLocation(), diag::note_previous_decl) << Var->getDeclName(); if (cast<LambdaScopeInfo>(CSI)->Lambda) Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), @@ -15083,12 +15083,12 @@ bool Sema::tryCaptureVariable( // capture a variable that an inner lambda explicitly captures, we // should have the inner lambda do the explicit capture - because // it makes for cleaner diagnostics later. This would purely be done - // so that the diagnostic does not misleadingly claim that a variable - // can not be captured by a lambda implicitly even though it is captured + // so that the diagnostic does not misleadingly claim that a variable + // can not be captured by a lambda implicitly even though it is captured // explicitly. Suggestion: - // - create const bool VariableCaptureWasInitiallyExplicit = Explicit + // - create const bool VariableCaptureWasInitiallyExplicit = Explicit // at the function head - // - cache the StartingDeclContext - this must be a lambda + // - cache the StartingDeclContext - this must be a lambda // - captureInLambda in the innermost lambda the variable. } return true; @@ -15100,31 +15100,31 @@ bool Sema::tryCaptureVariable( } while (!VarDC->Equals(DC)); // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) - // computing the type of the capture at each step, checking type-specific - // requirements, and adding captures if requested. - // If the variable had already been captured previously, we start capturing - // at the lambda nested within that one. - for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; + // computing the type of the capture at each step, checking type-specific + // requirements, and adding captures if requested. + // If the variable had already been captured previously, we start capturing + // at the lambda nested within that one. + for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; ++I) { CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); - + if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { - if (!captureInBlock(BSI, Var, ExprLoc, - BuildAndDiagnose, CaptureType, + if (!captureInBlock(BSI, Var, ExprLoc, + BuildAndDiagnose, CaptureType, DeclRefType, Nested, *this)) return true; Nested = true; } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { - if (!captureInCapturedRegion(RSI, Var, ExprLoc, - BuildAndDiagnose, CaptureType, + if (!captureInCapturedRegion(RSI, Var, ExprLoc, + BuildAndDiagnose, CaptureType, DeclRefType, Nested, *this)) return true; Nested = true; } else { LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); - if (!captureInLambda(LSI, Var, ExprLoc, - BuildAndDiagnose, CaptureType, - DeclRefType, Nested, Kind, EllipsisLoc, + if (!captureInLambda(LSI, Var, ExprLoc, + BuildAndDiagnose, CaptureType, + DeclRefType, Nested, Kind, EllipsisLoc, /*IsTopScope*/I == N - 1, *this)) return true; Nested = true; @@ -15134,7 +15134,7 @@ bool Sema::tryCaptureVariable( } bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, - TryCaptureKind Kind, SourceLocation EllipsisLoc) { + TryCaptureKind Kind, SourceLocation EllipsisLoc) { QualType CaptureType; QualType DeclRefType; return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, @@ -15153,10 +15153,10 @@ bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { QualType CaptureType; QualType DeclRefType; - + // Determine whether we can capture this variable. if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), - /*BuildAndDiagnose=*/false, CaptureType, + /*BuildAndDiagnose=*/false, CaptureType, DeclRefType, nullptr)) return QualType(); @@ -15165,49 +15165,49 @@ QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { -// If either the type of the variable or the initializer is dependent, +// If either the type of the variable or the initializer is dependent, // return false. Otherwise, determine whether the variable is a constant // expression. Use this if you need to know if a variable that might or // might not be dependent is truly a constant expression. -static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, +static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, ASTContext &Context) { - - if (Var->getType()->isDependentType()) + + if (Var->getType()->isDependentType()) return false; const VarDecl *DefVD = nullptr; Var->getAnyInitializer(DefVD); - if (!DefVD) + if (!DefVD) return false; EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); Expr *Init = cast<Expr>(Eval->Value); - if (Init->isValueDependent()) + if (Init->isValueDependent()) return false; - return IsVariableAConstantExpression(Var, Context); + return IsVariableAConstantExpression(Var, Context); } void Sema::UpdateMarkingForLValueToRValue(Expr *E) { - // Per C++11 [basic.def.odr], a variable is odr-used "unless it is + // Per C++11 [basic.def.odr], a variable is odr-used "unless it is // an object that satisfies the requirements for appearing in a // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) // is immediately applied." This function handles the lvalue-to-rvalue // conversion part. MaybeODRUseExprs.erase(E->IgnoreParens()); - + // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers // to a variable that is a constant expression, and if so, identify it as - // a reference to a variable that does not involve an odr-use of that - // variable. + // a reference to a variable that does not involve an odr-use of that + // variable. if (LambdaScopeInfo *LSI = getCurLambda()) { Expr *SansParensExpr = E->IgnoreParens(); VarDecl *Var = nullptr; - if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) + if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) Var = dyn_cast<VarDecl>(ME->getMemberDecl()); - - if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) - LSI->markVariableExprAsNonODRUsed(SansParensExpr); + + if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) + LSI->markVariableExprAsNonODRUsed(SansParensExpr); } } @@ -15508,13 +15508,13 @@ namespace { class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { Sema &S; bool SkipLocalVariables; - + public: typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; - - EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) + + EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } - + void VisitDeclRefExpr(DeclRefExpr *E) { // If we were asked not to visit local variables, don't. if (SkipLocalVariables) { @@ -15522,7 +15522,7 @@ namespace { if (VD->hasLocalStorage()) return; } - + S.MarkDeclRefReferenced(E); } @@ -15530,13 +15530,13 @@ namespace { S.MarkMemberReferenced(E); Inherited::VisitMemberExpr(E); } - + void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { S.MarkFunctionReferenced(E->getLocStart(), const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); Visit(E->getSubExpr()); } - + void VisitCXXNewExpr(CXXNewExpr *E) { if (E->getOperatorNew()) S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); @@ -15551,18 +15551,18 @@ namespace { QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); - S.MarkFunctionReferenced(E->getLocStart(), + S.MarkFunctionReferenced(E->getLocStart(), S.LookupDestructor(Record)); } - + Inherited::VisitCXXDeleteExpr(E); } - + void VisitCXXConstructExpr(CXXConstructExpr *E) { S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); Inherited::VisitCXXConstructExpr(E); } - + void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { Visit(E->getExpr()); } @@ -15579,9 +15579,9 @@ namespace { /// Mark any declarations that appear within this expression or any /// potentially-evaluated subexpressions as "referenced". /// -/// \param SkipLocalVariables If true, don't mark local variables as +/// \param SkipLocalVariables If true, don't mark local variables as /// 'referenced'. -void Sema::MarkDeclarationsReferencedInExpr(Expr *E, +void Sema::MarkDeclarationsReferencedInExpr(Expr *E, bool SkipLocalVariables) { EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); } @@ -15661,7 +15661,7 @@ bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, class CallReturnIncompleteDiagnoser : public TypeDiagnoser { FunctionDecl *FD; CallExpr *CE; - + public: CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) : FD(FD), CE(CE) { } @@ -15672,14 +15672,14 @@ bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, << T << CE->getSourceRange(); return; } - + S.Diag(Loc, diag::err_call_function_incomplete_return) << CE->getSourceRange() << FD->getDeclName() << T; S.Diag(FD->getLocation(), diag::note_entity_declared_at) << FD->getDeclName(); } } Diagnoser(FD, CE); - + if (RequireCompleteType(Loc, ReturnType, Diagnoser)) return true; @@ -15762,7 +15762,7 @@ void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) == Expr::MLV_Valid) { SourceLocation Loc = opE->getOperatorLoc(); - + Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); SourceRange ParenERange = ParenE->getSourceRange(); Diag(Loc, diag::note_equality_comparison_silence) @@ -16099,7 +16099,7 @@ ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { } // Rebuild the appropriate pointer-to-function type. - switch (Kind) { + switch (Kind) { case FK_MemberFunction: // Nothing to do. break; @@ -16148,15 +16148,15 @@ ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { if (E->getCastKind() == CK_FunctionToPointerDecay) { assert(E->getValueKind() == VK_RValue); assert(E->getObjectKind() == OK_Ordinary); - + E->setType(DestType); - + // Rebuild the sub-expression as the pointee (function) type. DestType = DestType->castAs<PointerType>()->getPointeeType(); - + ExprResult Result = Visit(E->getSubExpr()); if (!Result.isUsable()) return ExprError(); - + E->setSubExpr(Result.get()); return E; } else if (E->getCastKind() == CK_LValueToRValue) { @@ -16218,7 +16218,7 @@ ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { SC_None, false/*isInlineSpecified*/, FD->hasPrototype(), false/*isConstexprSpecified*/); - + if (FD->getQualifier()) NewFD->setQualifierInfo(FD->getQualifierLoc()); @@ -16486,7 +16486,7 @@ Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { Sema::LookupOrdinaryName); if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { NamedDecl *ND = Result.getFoundDecl(); - if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) + if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) Context.setBOOLDecl(TD); } } diff --git a/lib/Sema/SemaExprMember.cpp b/lib/Sema/SemaExprMember.cpp index 3a8fee862c91..e6d2b5068fd5 100644 --- a/lib/Sema/SemaExprMember.cpp +++ b/lib/Sema/SemaExprMember.cpp @@ -120,7 +120,7 @@ static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef, // member reference. if (Classes.empty()) return IMA_Static; - + // C++11 [expr.prim.general]p12: // An id-expression that denotes a non-static data member or non-static // member function of a class can only be used: @@ -166,7 +166,7 @@ static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef, else contextClass = cast<CXXRecordDecl>(DC); - // [class.mfct.non-static]p3: + // [class.mfct.non-static]p3: // ...is used in the body of a non-static member function of class X, // if name lookup (3.4.1) resolves the name in the id-expression to a // non-static non-type member of some class C [...] @@ -417,14 +417,14 @@ CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK, QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize); // Now look up the TypeDefDecl from the vector type. Without this, // diagostics look bad. We want extended vector types to appear built-in. - for (Sema::ExtVectorDeclsType::iterator + for (Sema::ExtVectorDeclsType::iterator I = S.ExtVectorDecls.begin(S.getExternalSource()), - E = S.ExtVectorDecls.end(); + E = S.ExtVectorDecls.end(); I != E; ++I) { if ((*I)->getUnderlyingType() == VT) return S.Context.getTypedefType(*I); } - + return VT; // should never get here (a typedef type should always be found). } @@ -817,10 +817,10 @@ Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS, // static data members cannot be anonymous structs or unions. // Supporting this is as easy as building a MemberExpr here. assert(!baseObjectExpr && "anonymous struct/union is static data member?"); - + DeclarationNameInfo baseNameInfo(DeclarationName(), loc); - - ExprResult result + + ExprResult result = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable); if (result.isInvalid()) return ExprError(); @@ -855,10 +855,10 @@ Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS, if (!result) return ExprError(); } - + // In all cases, we should now skip the first declaration in the chain. ++FI; - + while (FI != FEnd) { FieldDecl *field = cast<FieldDecl>(*FI++); @@ -873,7 +873,7 @@ Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS, fakeFoundDecl, memberNameInfo) .get(); } - + return result; } @@ -965,8 +965,8 @@ Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType, return ExprError(); BaseExpr = Converted.get(); } - - + + const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo(); DeclarationName MemberName = MemberNameInfo.getName(); SourceLocation MemberLoc = MemberNameInfo.getLoc(); @@ -1035,7 +1035,7 @@ Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType, !SuppressQualifierCheck && CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R)) return ExprError(); - + // Construct an unresolved result if we in fact got an unresolved // result. if (R.isOverloadedResult() || R.isUnresolvableResult()) { @@ -1421,7 +1421,7 @@ static ExprResult LookupMemberExpr(Sema &S, LookupResult &R, if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp)) if (UO->getOpcode() == UO_Deref) BaseExp = UO->getSubExpr()->IgnoreParenCasts(); - + if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp)) if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { S.Diag(DE->getLocation(), diag::err_arc_weak_ivar_access); @@ -1431,7 +1431,7 @@ static ExprResult LookupMemberExpr(Sema &S, LookupResult &R, if (warn) { if (ObjCMethodDecl *MD = S.getCurMethodDecl()) { ObjCMethodFamily MF = MD->getMethodFamily(); - warn = (MF != OMF_init && MF != OMF_dealloc && + warn = (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && !S.IvarBacksCurrentMethodAccessor(IDecl, MD, IV)); } @@ -1732,7 +1732,7 @@ Sema::BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, } if (VK != VK_RValue && Field->isBitField()) OK = OK_BitField; - + // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref] QualType MemberType = Field->getType(); if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) { @@ -1797,7 +1797,7 @@ Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS, const TemplateArgumentListInfo *TemplateArgs, bool IsKnownInstance, const Scope *S) { assert(!R.empty() && !R.isAmbiguous()); - + SourceLocation loc = R.getNameLoc(); // If this is known to be an instance access, go ahead and build an diff --git a/lib/Sema/SemaExprObjC.cpp b/lib/Sema/SemaExprObjC.cpp index bf0ffeba06b2..b291fc8691d5 100644 --- a/lib/Sema/SemaExprObjC.cpp +++ b/lib/Sema/SemaExprObjC.cpp @@ -73,7 +73,7 @@ ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs, /*Pascal=*/false, StrTy, &StrLocs[0], StrLocs.size()); } - + return BuildObjCStringLiteral(AtLocs[0], S); } @@ -92,12 +92,12 @@ ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S){ } else if (getLangOpts().NoConstantCFStrings) { IdentifierInfo *NSIdent=nullptr; std::string StringClass(getLangOpts().ObjCConstantStringClass); - + if (StringClass.empty()) NSIdent = &Context.Idents.get("NSConstantString"); else NSIdent = &Context.Idents.get(StringClass); - + NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc, LookupOrdinaryName); if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) { @@ -126,10 +126,10 @@ ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S){ // being an 'id' type. Ty = Context.getObjCNSStringType(); if (Ty.isNull()) { - ObjCInterfaceDecl *NSStringIDecl = - ObjCInterfaceDecl::Create (Context, - Context.getTranslationUnitDecl(), - SourceLocation(), NSIdent, + ObjCInterfaceDecl *NSStringIDecl = + ObjCInterfaceDecl::Create (Context, + Context.getTranslationUnitDecl(), + SourceLocation(), NSIdent, nullptr, nullptr, SourceLocation()); Ty = Context.getObjCInterfaceType(NSStringIDecl); Context.setObjCNSStringType(Ty); @@ -252,16 +252,16 @@ static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc, } return nullptr; } - + // If we already looked up this method, we're done. if (S.NSNumberLiteralMethods[*Kind]) return S.NSNumberLiteralMethods[*Kind]; - + Selector Sel = S.NSAPIObj->getNSNumberLiteralSelector(*Kind, /*Instance=*/false); - + ASTContext &CX = S.Context; - + // Look up the NSNumber class, if we haven't done so already. It's cached // in the Sema instance. if (!S.NSNumberDecl) { @@ -277,7 +277,7 @@ static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc, QualType NSNumberObject = CX.getObjCInterfaceType(S.NSNumberDecl); S.NSNumberPointer = CX.getObjCObjectPointerType(NSNumberObject); } - + // Look for the appropriate method within NSNumber. ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel); if (!Method && S.getLangOpts().DebuggerObjCLiteral) { @@ -304,7 +304,7 @@ static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc, // Note: if the parameter type is out-of-line, we'll catch it later in the // implicit conversion. - + S.NSNumberLiteralMethods[*Kind] = Method; return Method; } @@ -322,21 +322,21 @@ ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) { case CharacterLiteral::UTF8: NumberType = Context.CharTy; break; - + case CharacterLiteral::Wide: NumberType = Context.getWideCharType(); break; - + case CharacterLiteral::UTF16: NumberType = Context.Char16Ty; break; - + case CharacterLiteral::UTF32: NumberType = Context.Char32Ty; break; } } - + // Look for the appropriate method within NSNumber. // Construct the literal. SourceRange NR(Number->getSourceRange()); @@ -355,33 +355,33 @@ ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) { if (ConvertedNumber.isInvalid()) return ExprError(); Number = ConvertedNumber.get(); - + // Use the effective source range of the literal, including the leading '@'. return MaybeBindToTemporary( new (Context) ObjCBoxedExpr(Number, NSNumberPointer, Method, SourceRange(AtLoc, NR.getEnd()))); } -ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc, +ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc, bool Value) { ExprResult Inner; if (getLangOpts().CPlusPlus) { Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false); } else { - // C doesn't actually have a way to represent literal values of type + // C doesn't actually have a way to represent literal values of type // _Bool. So, we'll use 0/1 and implicit cast to _Bool. Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0); - Inner = ImpCastExprToType(Inner.get(), Context.BoolTy, + Inner = ImpCastExprToType(Inner.get(), Context.BoolTy, CK_IntegralToBoolean); } - + return BuildObjCNumericLiteral(AtLoc, Inner.get()); } /// Check that the given expression is a valid element of an Objective-C /// collection literal. -static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element, +static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element, QualType T, bool ArrayLiteral = false) { // If the expression is type-dependent, there's nothing for us to do. @@ -393,7 +393,7 @@ static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element, return ExprError(); Element = Result.get(); - // In C++, check for an implicit conversion to an Objective-C object pointer + // In C++, check for an implicit conversion to an Objective-C object pointer // type. if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) { InitializedEntity Entity @@ -413,15 +413,15 @@ static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element, Result = S.DefaultLvalueConversion(Element); if (Result.isInvalid()) return ExprError(); - Element = Result.get(); + Element = Result.get(); // Make sure that we have an Objective-C pointer type or block. if (!Element->getType()->isObjCObjectPointerType() && !Element->getType()->isBlockPointerType()) { bool Recovered = false; - + // If this is potentially an Objective-C numeric literal, add the '@'. - if (isa<IntegerLiteral>(OrigElement) || + if (isa<IntegerLiteral>(OrigElement) || isa<CharacterLiteral>(OrigElement) || isa<FloatingLiteral>(OrigElement) || isa<ObjCBoolLiteralExpr>(OrigElement) || @@ -431,16 +431,16 @@ static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element, : (isa<CXXBoolLiteralExpr>(OrigElement) || isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2 : 3; - + S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection) << Which << OrigElement->getSourceRange() << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@"); - + Result = S.BuildObjCNumericLiteral(OrigElement->getLocStart(), OrigElement); if (Result.isInvalid()) return ExprError(); - + Element = Result.get(); Recovered = true; } @@ -455,12 +455,12 @@ static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element, Result = S.BuildObjCStringLiteral(OrigElement->getLocStart(), String); if (Result.isInvalid()) return ExprError(); - + Element = Result.get(); Recovered = true; } } - + if (!Recovered) { S.Diag(Element->getLocStart(), diag::err_invalid_collection_element) << Element->getType(); @@ -488,17 +488,17 @@ static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element, } } - // Make sure that the element has the type that the container factory - // function expects. + // Make sure that the element has the type that the container factory + // function expects. return S.PerformCopyInitialization( - InitializedEntity::InitializeParameter(S.Context, T, + InitializedEntity::InitializeParameter(S.Context, T, /*Consumed=*/false), Element->getLocStart(), Element); } ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) { if (ValueExpr->isTypeDependent()) { - ObjCBoxedExpr *BoxedExpr = + ObjCBoxedExpr *BoxedExpr = new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, nullptr, SR); return BoxedExpr; } @@ -525,7 +525,7 @@ ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) { QualType NSStringObject = Context.getObjCInterfaceType(NSStringDecl); NSStringPointer = Context.getObjCObjectPointerType(NSStringObject); } - + if (!StringWithUTF8StringMethod) { IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String"); Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II); @@ -561,7 +561,7 @@ ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) { StringWithUTF8StringMethod = BoxingMethod; } - + BoxingMethod = StringWithUTF8StringMethod; BoxedType = NSStringPointer; // Transfer the nullability from method's return type. @@ -588,22 +588,22 @@ ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) { case CharacterLiteral::UTF8: ValueType = Context.CharTy; break; - + case CharacterLiteral::Wide: ValueType = Context.getWideCharType(); break; - + case CharacterLiteral::UTF16: ValueType = Context.Char16Ty; break; - + case CharacterLiteral::UTF32: ValueType = Context.Char32Ty; break; } } // FIXME: Do I need to do anything special with BoolTy expressions? - + // Look for the appropriate method within NSNumber. BoxingMethod = getNSNumberFactoryMethod(*this, Loc, ValueType); BoxedType = NSNumberPointer; @@ -620,7 +620,7 @@ ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) { } else if (ValueType->isObjCBoxableRecordType()) { // Support for structure types, that marked as objc_boxable // struct __attribute__((objc_boxable)) s { ... }; - + // Look up the NSValue class, if we haven't done so already. It's cached // in the Sema instance. if (!NSValueDecl) { @@ -634,14 +634,14 @@ ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) { QualType NSValueObject = Context.getObjCInterfaceType(NSValueDecl); NSValuePointer = Context.getObjCObjectPointerType(NSValueObject); } - + if (!ValueWithBytesObjCTypeMethod) { IdentifierInfo *II[] = { &Context.Idents.get("valueWithBytes"), &Context.Idents.get("objCType") }; Selector ValueWithBytesObjCType = Context.Selectors.getSelector(2, II); - + // Look for the appropriate method within NSValue. BoxingMethod = NSValueDecl->lookupClassMethod(ValueWithBytesObjCType); if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) { @@ -662,9 +662,9 @@ ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) { /*isDefined=*/false, ObjCMethodDecl::Required, /*HasRelatedResultType=*/false); - + SmallVector<ParmVarDecl *, 2> Params; - + ParmVarDecl *bytes = ParmVarDecl::Create(Context, M, SourceLocation(), SourceLocation(), @@ -673,7 +673,7 @@ ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) { /*TInfo=*/nullptr, SC_None, nullptr); Params.push_back(bytes); - + QualType ConstCharType = Context.CharTy.withConst(); ParmVarDecl *type = ParmVarDecl::Create(Context, M, @@ -683,18 +683,18 @@ ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) { /*TInfo=*/nullptr, SC_None, nullptr); Params.push_back(type); - + M->setMethodParams(Context, Params, None); BoxingMethod = M; } - + if (!validateBoxingMethod(*this, Loc, NSValueDecl, ValueWithBytesObjCType, BoxingMethod)) return ExprError(); - + ValueWithBytesObjCTypeMethod = BoxingMethod; } - + if (!ValueType.isTriviallyCopyableType(Context)) { Diag(Loc, diag::err_objc_non_trivially_copyable_boxed_expression_type) << ValueType << ValueExpr->getSourceRange(); @@ -710,13 +710,13 @@ ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) { << ValueType << ValueExpr->getSourceRange(); return ExprError(); } - + DiagnoseUseOfDecl(BoxingMethod, Loc); ExprResult ConvertedValueExpr; if (ValueType->isObjCBoxableRecordType()) { InitializedEntity IE = InitializedEntity::InitializeTemporary(ValueType); - ConvertedValueExpr = PerformCopyInitialization(IE, ValueExpr->getExprLoc(), + ConvertedValueExpr = PerformCopyInitialization(IE, ValueExpr->getExprLoc(), ValueExpr); } else { // Convert the expression to the type that the parameter requires. @@ -726,12 +726,12 @@ ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) { ConvertedValueExpr = PerformCopyInitialization(IE, SourceLocation(), ValueExpr); } - + if (ConvertedValueExpr.isInvalid()) return ExprError(); ValueExpr = ConvertedValueExpr.get(); - - ObjCBoxedExpr *BoxedExpr = + + ObjCBoxedExpr *BoxedExpr = new (Context) ObjCBoxedExpr(ValueExpr, BoxedType, BoxingMethod, SR); return MaybeBindToTemporary(BoxedExpr); @@ -756,7 +756,7 @@ ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr, if (Result.isInvalid()) return ExprError(); IndexExpr = Result.get(); - + // Perform lvalue-to-rvalue conversion on the base. Result = DefaultLvalueConversion(BaseExpr); if (Result.isInvalid()) @@ -821,24 +821,24 @@ ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) { // Dig out the type that all elements should be converted to. QualType T = Method->parameters()[0]->getType(); const PointerType *PtrT = T->getAs<PointerType>(); - if (!PtrT || + if (!PtrT || !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) { Diag(SR.getBegin(), diag::err_objc_literal_method_sig) << Sel; Diag(Method->parameters()[0]->getLocation(), diag::note_objc_literal_method_param) - << 0 << T + << 0 << T << Context.getPointerType(IdT.withConst()); return ExprError(); } - + // Check that the 'count' parameter is integral. if (!Method->parameters()[1]->getType()->isIntegerType()) { Diag(SR.getBegin(), diag::err_objc_literal_method_sig) << Sel; Diag(Method->parameters()[1]->getLocation(), diag::note_objc_literal_method_param) - << 1 + << 1 << Method->parameters()[1]->getType() << "integral"; return ExprError(); @@ -860,11 +860,11 @@ ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) { RequiredType, true); if (Converted.isInvalid()) return ExprError(); - + ElementsBuffer[I] = Converted.get(); } - - QualType Ty + + QualType Ty = Context.getObjCObjectPointerType( Context.getObjCInterfaceType(NSArrayDecl)); @@ -893,7 +893,7 @@ ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR, NSAPI::NSDict_dictionaryWithObjectsForKeysCount); ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel); if (!Method && getLangOpts().DebuggerObjCLiteral) { - Method = ObjCMethodDecl::Create(Context, + Method = ObjCMethodDecl::Create(Context, SourceLocation(), SourceLocation(), Sel, IdT, nullptr /*TypeSourceInfo */, @@ -938,7 +938,7 @@ ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR, // Dig out the type that all values should be converted to. QualType ValueT = Method->parameters()[0]->getType(); const PointerType *PtrValue = ValueT->getAs<PointerType>(); - if (!PtrValue || + if (!PtrValue || !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) { Diag(SR.getBegin(), diag::err_objc_literal_method_sig) << Sel; @@ -952,7 +952,7 @@ ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR, // Dig out the type that all keys should be converted to. QualType KeyT = Method->parameters()[1]->getType(); const PointerType *PtrKey = KeyT->getAs<PointerType>(); - if (!PtrKey || + if (!PtrKey || !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(), IdT)) { bool err = true; @@ -962,7 +962,7 @@ ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR, if (ObjCProtocolDecl *NSCopyingPDecl = LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) { ObjCProtocolDecl *PQ[] = {NSCopyingPDecl}; - QIDNSCopying = + QIDNSCopying = Context.getObjCObjectType(Context.ObjCBuiltinIdTy, { }, llvm::makeArrayRef( (ObjCProtocolDecl**) PQ, @@ -975,7 +975,7 @@ ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR, err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(), QIDNSCopying); } - + if (err) { Diag(SR.getBegin(), diag::err_objc_literal_method_sig) << Sel; @@ -1008,7 +1008,7 @@ ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR, QualType KeysT = DictionaryWithObjectsMethod->parameters()[1]->getType(); QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType(); - // Check that each of the keys and values provided is valid in a collection + // Check that each of the keys and values provided is valid in a collection // literal, performing conversions as necessary. bool HasPackExpansions = false; for (ObjCDictionaryElement &Element : Elements) { @@ -1017,19 +1017,19 @@ ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR, KeyT); if (Key.isInvalid()) return ExprError(); - + // Check the value. ExprResult Value = CheckObjCCollectionLiteralElement(*this, Element.Value, ValueT); if (Value.isInvalid()) return ExprError(); - + Element.Key = Key.get(); Element.Value = Value.get(); - + if (Element.EllipsisLoc.isInvalid()) continue; - + if (!Element.Key->containsUnexpandedParameterPack() && !Element.Value->containsUnexpandedParameterPack()) { Diag(Element.EllipsisLoc, @@ -1038,10 +1038,10 @@ ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR, Element.Value->getLocEnd()); return ExprError(); } - + HasPackExpansions = true; } - + QualType Ty = Context.getObjCObjectPointerType( Context.getObjCInterfaceType(NSDictionaryDecl)); @@ -1147,7 +1147,7 @@ static void DiagnoseMismatchedSelectors(Sema &S, SourceLocation AtLoc, if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc, Method, InstMethList)) Warned = true; - + // second, class methods ObjCMethodList &ClsMethList = b->second.second; if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc, @@ -1175,7 +1175,7 @@ ExprResult Sema::ParseObjCSelectorExpression(Selector Sel, Diag(SelLoc, diag::warn_undeclared_selector_with_typo) << Sel << MatchedSel << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString()); - + } else Diag(SelLoc, diag::warn_undeclared_selector) << Sel; } else @@ -1187,7 +1187,7 @@ ExprResult Sema::ParseObjCSelectorExpression(Selector Sel, !getSourceManager().isInSystemHeader(Method->getLocation())) ReferencedSelectors.insert(std::make_pair(Sel, AtLoc)); - // In ARC, forbid the user from using @selector for + // In ARC, forbid the user from using @selector for // retain/release/autorelease/dealloc/retainCount. if (getLangOpts().ObjCAutoRefCount) { switch (Sel.getMethodFamily()) { @@ -1196,7 +1196,7 @@ ExprResult Sema::ParseObjCSelectorExpression(Selector Sel, case OMF_autorelease: case OMF_retainCount: case OMF_dealloc: - Diag(AtLoc, diag::err_arc_illegal_selector) << + Diag(AtLoc, diag::err_arc_illegal_selector) << Sel << SourceRange(LParenLoc, RParenLoc); break; @@ -1269,7 +1269,7 @@ static QualType stripObjCInstanceType(ASTContext &Context, QualType T) { if (T == Context.getObjCInstanceType()) return Context.getObjCIdType(); - + return origType; } @@ -1313,7 +1313,7 @@ static QualType getBaseMessageSendResultType(Sema &S, // was a class message send, T is the declared return type of the method // found if (Method->isInstanceMethod() && isClassMessage) - return stripObjCInstanceType(Context, + return stripObjCInstanceType(Context, Method->getSendResultType(ReceiverType)); // - if the receiver is super, T is a pointer to the class of the @@ -1334,7 +1334,7 @@ static QualType getBaseMessageSendResultType(Sema &S, // T is the declared return type of the method. if (ReceiverType->isObjCClassType() || ReceiverType->isObjCQualifiedClassType()) - return stripObjCInstanceType(Context, + return stripObjCInstanceType(Context, Method->getSendResultType(ReceiverType)); // - if the receiver is id, qualified id, Class, or qualified Class, T @@ -1424,14 +1424,14 @@ findExplicitInstancetypeDeclarer(const ObjCMethodDecl *MD, if (const ObjCImplDecl *impl = dyn_cast<ObjCImplDecl>(MD->getDeclContext())) { const ObjCContainerDecl *iface; - if (const ObjCCategoryImplDecl *catImpl = + if (const ObjCCategoryImplDecl *catImpl = dyn_cast<ObjCCategoryImplDecl>(impl)) { iface = catImpl->getCategoryDecl(); } else { iface = impl->getClassInterface(); } - const ObjCMethodDecl *ifaceMD = + const ObjCMethodDecl *ifaceMD = iface->getMethod(MD->getSelector(), MD->isInstanceMethod()); if (ifaceMD) return findExplicitInstancetypeDeclarer(ifaceMD, instancetype); } @@ -1481,11 +1481,11 @@ void Sema::EmitRelatedResultTypeNote(const Expr *E) { const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E); if (!MsgSend) return; - + const ObjCMethodDecl *Method = MsgSend->getMethodDecl(); if (!Method) return; - + if (!Method->hasRelatedResultType()) return; @@ -1496,7 +1496,7 @@ void Sema::EmitRelatedResultTypeNote(const Expr *E) { if (!Context.hasSameUnqualifiedType(Method->getReturnType(), Context.getObjCInstanceType())) return; - + Diag(Method->getLocation(), diag::note_related_result_type_inferred) << Method->isInstanceMethod() << Method->getSelector() << MsgSend->getType(); @@ -1560,7 +1560,7 @@ bool Sema::CheckMessageArgumentTypes(QualType ReceiverType, } else Diag(SelLoc, DiagID) - << Sel << isClassMessage << SourceRange(SelectorLocs.front(), + << Sel << isClassMessage << SourceRange(SelectorLocs.front(), SelectorLocs.back()); // Find the class to which we are sending this message. if (ReceiverType->isObjCObjectPointerType()) { @@ -1587,7 +1587,7 @@ bool Sema::CheckMessageArgumentTypes(QualType ReceiverType, return false; } - ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage, + ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage, isSuperMessage); VK = Expr::getValueKindForType(Method->getReturnType()); @@ -1751,7 +1751,7 @@ ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type, return nullptr; } -/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier +/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier /// list of a qualified objective pointer type. ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel, const ObjCObjectPointerType *OPT, @@ -1785,14 +1785,14 @@ HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT, } IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); - + SourceRange BaseRange = Super? SourceRange(SuperLoc) : BaseExpr->getSourceRange(); - if (RequireCompleteType(MemberLoc, OPT->getPointeeType(), + if (RequireCompleteType(MemberLoc, OPT->getPointeeType(), diag::err_property_not_found_forward_class, MemberName, BaseRange)) return ExprError(); - + if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration( Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) { // Check whether we can reference this property. @@ -1832,7 +1832,7 @@ HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT, Selector Sel = PP.getSelectorTable().getNullarySelector(Member); ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel); - + // May be found in property's qualified list. if (!Getter) Getter = LookupMethodInQualifiedType(Sel, OPT, true); @@ -1852,17 +1852,17 @@ HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT, SelectorTable::constructSetterSelector(PP.getIdentifierTable(), PP.getSelectorTable(), Member); ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel); - + // May be found in property's qualified list. if (!Setter) Setter = LookupMethodInQualifiedType(SetterSel, OPT, true); - + if (!Setter) { // If this reference is in an @implementation, also check for 'private' // methods. Setter = IFace->lookupPrivateMethod(SetterSel); } - + if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc)) return ExprError(); @@ -1926,23 +1926,23 @@ HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT, } } ObjCInterfaceDecl *ClassDeclared; - if (ObjCIvarDecl *Ivar = + if (ObjCIvarDecl *Ivar = IFace->lookupInstanceVariable(Member, ClassDeclared)) { QualType T = Ivar->getType(); - if (const ObjCObjectPointerType * OBJPT = + if (const ObjCObjectPointerType * OBJPT = T->getAsObjCInterfacePointerType()) { - if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(), + if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(), diag::err_property_not_as_forward_class, MemberName, BaseExpr)) return ExprError(); } - Diag(MemberLoc, + Diag(MemberLoc, diag::err_ivar_access_using_property_syntax_suggest) << MemberName << QualType(OPT, 0) << Ivar->getDeclName() << FixItHint::CreateReplacement(OpLoc, "->"); return ExprError(); } - + Diag(MemberLoc, diag::err_property_not_found) << MemberName << QualType(OPT, 0); if (Setter) @@ -2086,10 +2086,10 @@ Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S, // trailing dot, it's an instance message. if (IsSuper && S->isInObjcMethodScope()) return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage; - + LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); LookupName(Result, S); - + switch (Result.getResultKind()) { case LookupResult::NotFound: // Normal name lookup didn't find anything. If we're in an @@ -2103,11 +2103,11 @@ Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S, } ObjCInterfaceDecl *ClassDeclared; - if (Method->getClassInterface()->lookupInstanceVariable(Name, + if (Method->getClassInterface()->lookupInstanceVariable(Name, ClassDeclared)) return ObjCInstanceMessage; } - + // Break out; we'll perform typo correction below. break; @@ -2171,7 +2171,7 @@ Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S, return ObjCInstanceMessage; } -ExprResult Sema::ActOnSuperMessage(Scope *S, +ExprResult Sema::ActOnSuperMessage(Scope *S, SourceLocation SuperLoc, Selector Sel, SourceLocation LBracLoc, @@ -2213,7 +2213,7 @@ ExprResult Sema::ActOnSuperMessage(Scope *S, Sel, /*Method=*/nullptr, LBracLoc, SelectorLocs, RBracLoc, Args); } - + // Since we are in a class method, this is a class message to // the superclass. return BuildClassMessage(/*ReceiverTypeInfo=*/nullptr, @@ -2353,7 +2353,7 @@ DiagnoseCStringFormatDirectiveInObjCAPI(Sema &S, } if (!Format || NumArgs <= Idx) return; - + Expr *FormatExpr = Args[Idx]; if (ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) { @@ -2401,7 +2401,7 @@ ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, SourceLocation SuperLoc, Selector Sel, ObjCMethodDecl *Method, - SourceLocation LBracLoc, + SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg ArgsIn, @@ -2431,7 +2431,7 @@ ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs), RBracLoc, isImplicit); } - + // Find the class to which we are sending this message. ObjCInterfaceDecl *Class = nullptr; const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>(); @@ -2446,7 +2446,7 @@ ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, (void)DiagnoseUseOfDecl(Class, SelectorSlotLocs); // Find the method we are messaging. if (!Method) { - SourceRange TypeRange + SourceRange TypeRange = SuperLoc.isValid()? SourceRange(SuperLoc) : ReceiverTypeInfo->getTypeLoc().getSourceRange(); if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class), @@ -2455,7 +2455,7 @@ ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, : diag::warn_receiver_forward_class), TypeRange)) { // A forward class used in messaging is treated as a 'Class' - Method = LookupFactoryMethodInGlobalPool(Sel, + Method = LookupFactoryMethodInGlobalPool(Sel, SourceRange(LBracLoc, RBracLoc)); if (Method && !getLangOpts().ObjCAutoRefCount) Diag(Method->getLocation(), diag::note_method_sent_forward_class) @@ -2490,7 +2490,7 @@ ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, RequireCompleteType(LBracLoc, Method->getReturnType(), diag::err_illegal_message_expr_incomplete_type)) return ExprError(); - + // Warn about explicit call of +initialize on its own class. But not on 'super'. if (Method && Method->getMethodFamily() == OMF_initialize) { if (!SuperLoc.isValid()) { @@ -2513,19 +2513,19 @@ ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, } } } - + DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs); - + // Construct the appropriate ObjCMessageExpr. ObjCMessageExpr *Result; if (SuperLoc.isValid()) - Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc, - SuperLoc, /*IsInstanceSuper=*/false, + Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc, + SuperLoc, /*IsInstanceSuper=*/false, ReceiverType, Sel, SelectorLocs, Method, makeArrayRef(Args, NumArgs), RBracLoc, isImplicit); else { - Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc, + Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc, ReceiverTypeInfo, Sel, SelectorLocs, Method, makeArrayRef(Args, NumArgs), RBracLoc, isImplicit); @@ -2541,7 +2541,7 @@ ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, // ActOnClassMessage - used for both unary and keyword messages. // ArgExprs is optional - if it is present, the number of expressions // is obtained from Sel.getNumArgs(). -ExprResult Sema::ActOnClassMessage(Scope *S, +ExprResult Sema::ActOnClassMessage(Scope *S, ParsedType Receiver, Selector Sel, SourceLocation LBracLoc, @@ -2556,7 +2556,7 @@ ExprResult Sema::ActOnClassMessage(Scope *S, if (!ReceiverTypeInfo) ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc); - return BuildClassMessage(ReceiverTypeInfo, ReceiverType, + return BuildClassMessage(ReceiverTypeInfo, ReceiverType, /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/nullptr, LBracLoc, SelectorLocs, RBracLoc, Args); @@ -2625,7 +2625,7 @@ ExprResult Sema::BuildInstanceMessage(Expr *Receiver, SourceLocation SuperLoc, Selector Sel, ObjCMethodDecl *Method, - SourceLocation LBracLoc, + SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg ArgsIn, @@ -2691,15 +2691,15 @@ ExprResult Sema::BuildInstanceMessage(Expr *Receiver, // do nothing } else if (!getLangOpts().ObjCAutoRefCount && !Context.getObjCIdType().isNull() && - (ReceiverType->isPointerType() || + (ReceiverType->isPointerType() || ReceiverType->isIntegerType())) { // Implicitly convert integers and pointers to 'id' but emit a warning. // But not in ARC. Diag(Loc, diag::warn_bad_receiver_type) - << ReceiverType + << ReceiverType << Receiver->getSourceRange(); if (ReceiverType->isPointerType()) { - Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(), + Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(), CK_CPointerToObjCPointerCast).get(); } else { // TODO: specialized warning on null receivers? @@ -2828,7 +2828,7 @@ ExprResult Sema::BuildInstanceMessage(Expr *Receiver, // We allow sending a message to a qualified ID ("id<foo>"), which is ok as // long as one of the protocols implements the selector (if not, warn). // And as long as message is not deprecated/unavailable (warn if it is). - if (const ObjCObjectPointerType *QIdTy + if (const ObjCObjectPointerType *QIdTy = ReceiverType->getAsObjCQualifiedIdType()) { // Search protocols for instance methods. Method = LookupMethodInQualifiedType(Sel, QIdTy, true); @@ -2854,9 +2854,9 @@ ExprResult Sema::BuildInstanceMessage(Expr *Receiver, : SourceRange(SuperLoc))) { if (getLangOpts().ObjCAutoRefCount) return ExprError(); - + forwardClass = OCIType->getInterfaceDecl(); - Diag(Receiver ? Receiver->getLocStart() + Diag(Receiver ? Receiver->getLocStart() : SuperLoc, diag::note_receiver_is_id); Method = nullptr; } else { @@ -2866,7 +2866,7 @@ ExprResult Sema::BuildInstanceMessage(Expr *Receiver, if (!Method) // Search protocol qualifiers. Method = LookupMethodInQualifiedType(Sel, OCIType, true); - + if (!Method) { // If we have implementations in scope, check "private" methods. Method = ClassDecl->lookupPrivateMethod(Sel); @@ -2975,7 +2975,7 @@ ExprResult Sema::BuildInstanceMessage(Expr *Receiver, ReceiverType->isObjCQualifiedClassType()); if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs), Sel, SelectorLocs, Method, - ClassMessage, SuperLoc.isValid(), + ClassMessage, SuperLoc.isValid(), LBracLoc, RBracLoc, RecRange, ReturnType, VK)) return ExprError(); @@ -2984,7 +2984,7 @@ ExprResult Sema::BuildInstanceMessage(Expr *Receiver, diag::err_illegal_message_expr_incomplete_type)) return ExprError(); - // In ARC, forbid the user from sending messages to + // In ARC, forbid the user from sending messages to // retain/release/autorelease/dealloc/retainCount explicitly. if (getLangOpts().ObjCAutoRefCount) { ObjCMethodFamily family = @@ -3013,13 +3013,13 @@ ExprResult Sema::BuildInstanceMessage(Expr *Receiver, Diag(SelLoc, diag::err_arc_illegal_explicit_message) << Sel << RecRange; break; - + case OMF_performSelector: if (Method && NumArgs >= 1) { if (const auto *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0]->IgnoreParens())) { Selector ArgSel = SelExp->getSelector(); - ObjCMethodDecl *SelMethod = + ObjCMethodDecl *SelMethod = LookupInstanceMethodInGlobalPool(ArgSel, SelExp->getSourceRange()); if (!SelMethod) @@ -3036,8 +3036,8 @@ ExprResult Sema::BuildInstanceMessage(Expr *Receiver, case OMF_init: // Issue error, unless ns_returns_not_retained. if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) { - // selector names a +1 method - Diag(SelLoc, + // selector names a +1 method + Diag(SelLoc, diag::err_arc_perform_selector_retains); Diag(SelMethod->getLocation(), diag::note_method_declared_at) << SelMethod->getDeclName(); @@ -3047,7 +3047,7 @@ ExprResult Sema::BuildInstanceMessage(Expr *Receiver, // +0 call. OK. unless ns_returns_retained. if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) { // selector names a +1 method - Diag(SelLoc, + Diag(SelLoc, diag::err_arc_perform_selector_retains); Diag(SelMethod->getLocation(), diag::note_method_declared_at) << SelMethod->getDeclName(); @@ -3066,13 +3066,13 @@ ExprResult Sema::BuildInstanceMessage(Expr *Receiver, } DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs); - + // Construct the appropriate ObjCMessageExpr instance. ObjCMessageExpr *Result; if (SuperLoc.isValid()) Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc, SuperLoc, /*IsInstanceSuper=*/true, - ReceiverType, Sel, SelectorLocs, Method, + ReceiverType, Sel, SelectorLocs, Method, makeArrayRef(Args, NumArgs), RBracLoc, isImplicit); else { @@ -3158,7 +3158,7 @@ static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) { // ArgExprs is optional - if it is present, the number of expressions // is obtained from Sel.getNumArgs(). ExprResult Sema::ActOnInstanceMessage(Scope *S, - Expr *Receiver, + Expr *Receiver, Selector Sel, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, @@ -3173,7 +3173,7 @@ ExprResult Sema::ActOnInstanceMessage(Scope *S, if (Result.isInvalid()) return ExprError(); Receiver = Result.get(); } - + if (RespondsToSelectorSel.isNull()) { IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector"); RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId); @@ -3218,13 +3218,13 @@ static bool isAnyCLike(ARCConversionTypeClass ACTC) { static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) { bool isIndirect = false; - + // Ignore an outermost reference type. if (const ReferenceType *ref = type->getAs<ReferenceType>()) { type = ref->getPointeeType(); isIndirect = true; } - + // Drill through pointers and arrays recursively. while (true) { if (const PointerType *ptr = type->getAs<PointerType>()) { @@ -3242,7 +3242,7 @@ static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) { } isIndirect = true; } - + if (isIndirect) { if (type->isObjCARCBridgableType()) return ACTC_indirectRetainable; @@ -3322,7 +3322,7 @@ namespace { return ACC_invalid; } - + /// Look through certain implicit and explicit casts. ACCResult VisitCastExpr(CastExpr *e) { switch (e->getCastKind()) { @@ -3428,10 +3428,10 @@ namespace { // Otherwise, don't do anything implicit with an unaudited function. if (!fn->hasAttr<CFAuditedTransferAttr>()) return ACC_invalid; - + // Otherwise, it's +0 unless it follows the create convention. if (ento::coreFoundation::followsCreateRule(fn)) - return Diagnose ? ACC_plusOne + return Diagnose ? ACC_plusOne : ACC_invalid; // ACC_plusOne if we start accepting this return ACC_plusZero; @@ -3458,7 +3458,7 @@ namespace { // return type is CF. if (!isAnyRetainable(TargetClass) || !isCFType(method->getReturnType())) return ACC_invalid; - + // If the method is explicitly marked not-retained, it's +0. if (method->hasAttr<CFReturnsNotRetainedAttr>()) return ACC_plusZero; @@ -3517,12 +3517,12 @@ static void addFixitForObjCARCConversion(Sema &S, SourceRange range(NCE->getOperatorLoc(), NCE->getAngleBrackets().getEnd()); SmallString<32> BridgeCall; - + SourceManager &SM = S.getSourceManager(); char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1)); if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts())) BridgeCall += ' '; - + BridgeCall += CFBridgeName; DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall)); } @@ -3623,7 +3623,7 @@ diagnoseObjCARCConversion(Sema &S, SourceRange castRange, Sema::CheckedConversionKind CCK) { SourceLocation loc = (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc()); - + if (S.makeUnavailableInSystemHeader(loc, UnavailableAttr::IR_ARCForbiddenConversion)) return; @@ -3637,7 +3637,7 @@ diagnoseObjCARCConversion(Sema &S, SourceRange castRange, (exprACTC == ACTC_coreFoundation && castACTC == ACTC_retainable && ObjCBridgeRelatedAttrFromType(castExprType, TDNDecl))) return; - + unsigned srcKind = 0; switch (exprACTC) { case ACTC_none: @@ -3652,7 +3652,7 @@ diagnoseObjCARCConversion(Sema &S, SourceRange castRange, srcKind = 4; break; } - + // Check whether this could be fixed with a bridge cast. SourceLocation afterLParen = S.getLocForEndOfToken(castRange.getBegin()); SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc; @@ -3671,12 +3671,12 @@ diagnoseObjCARCConversion(Sema &S, SourceRange castRange, << castRange << castExpr->getSourceRange(); bool br = S.isKnownName("CFBridgingRelease"); - ACCResult CreateRule = + ACCResult CreateRule = ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr); assert(CreateRule != ACC_bottom && "This cast should already be accepted."); if (CreateRule != ACC_plusOne) { - DiagnosticBuilder DiagB = + DiagnosticBuilder DiagB = (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge) : S.Diag(noteLoc, diag::note_arc_cstyle_bridge); @@ -3700,7 +3700,7 @@ diagnoseObjCARCConversion(Sema &S, SourceRange castRange, return; } - + // Bridge from a CF type to an ARC type. if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) { bool br = S.isKnownName("CFBridgingRetain"); @@ -3712,7 +3712,7 @@ diagnoseObjCARCConversion(Sema &S, SourceRange castRange, << castType << castRange << castExpr->getSourceRange(); - ACCResult CreateRule = + ACCResult CreateRule = ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr); assert(CreateRule != ACC_bottom && "This cast should already be accepted."); if (CreateRule != ACC_plusOne) @@ -3740,7 +3740,7 @@ diagnoseObjCARCConversion(Sema &S, SourceRange castRange, return; } - + S.Diag(loc, diag::err_arc_mismatched_cast) << !convKindForDiag << srcKind << castExprType << castType @@ -3759,7 +3759,7 @@ static bool CheckObjCBridgeNSCast(Sema &S, QualType castType, Expr *castExpr, HadTheAttribute = true; if (Parm->isStr("id")) return true; - + NamedDecl *Target = nullptr; // Check for an existing type with this name. LookupResult R(S, DeclarationName(Parm), SourceLocation(), @@ -3897,7 +3897,7 @@ void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) { HasObjCBridgeMutableAttr, false); if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr) return; - + if (HasObjCBridgeAttr) CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr, true); @@ -3918,7 +3918,7 @@ void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) { HasObjCBridgeMutableAttr, false); if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr) return; - + if (HasObjCBridgeAttr) CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr, true); @@ -3940,7 +3940,7 @@ void Sema::CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr) { SrcType = Getter->getReturnType(); } } - + ARCConversionTypeClass srcExprACTC = classifyTypeForARCConversion(SrcType); ARCConversionTypeClass castExprACTC = classifyTypeForARCConversion(castType); if (srcExprACTC != ACTC_retainable || castExprACTC != ACTC_coreFoundation) @@ -3977,7 +3977,7 @@ bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc, ObjCBridgeRelatedAttr *ObjCBAttr = ObjCBridgeRelatedAttrFromType(T, TDNDecl); if (!ObjCBAttr) return false; - + IdentifierInfo *RCId = ObjCBAttr->getRelatedClass(); IdentifierInfo *CMId = ObjCBAttr->getClassMethod(); IdentifierInfo *IMId = ObjCBAttr->getInstanceMethod(); @@ -4008,7 +4008,7 @@ bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc, } return false; } - + // Check for an existing class method with the given selector name. if (CfToNs && CMId) { Selector Sel = Context.Selectors.getUnarySelector(CMId); @@ -4022,7 +4022,7 @@ bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc, return false; } } - + // Check for an existing instance method with the given selector name. if (!CfToNs && IMId) { Selector Sel = Context.Selectors.getNullarySelector(IMId); @@ -4049,7 +4049,7 @@ Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc, bool NsToCf = (rhsExprACTC == ACTC_retainable && lhsExprACTC == ACTC_coreFoundation); if (!CfToNs && !NsToCf) return false; - + ObjCInterfaceDecl *RelatedClass; ObjCMethodDecl *ClassMethod = nullptr; ObjCMethodDecl *InstanceMethod = nullptr; @@ -4058,7 +4058,7 @@ Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc, ClassMethod, InstanceMethod, TDNDecl, CfToNs, Diagnose)) return false; - + if (CfToNs) { // Implicit conversion from CF to ObjC object is needed. if (ClassMethod) { @@ -4075,7 +4075,7 @@ Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc, << FixItHint::CreateInsertion(SrcExprEndLoc, "]"); Diag(RelatedClass->getLocStart(), diag::note_declared_at); Diag(TDNDecl->getLocStart(), diag::note_declared_at); - + QualType receiverType = Context.getObjCInterfaceType(RelatedClass); // Argument. Expr *args[] = { SrcExpr }; @@ -4118,7 +4118,7 @@ Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc, } Diag(RelatedClass->getLocStart(), diag::note_declared_at); Diag(TDNDecl->getLocStart(), diag::note_declared_at); - + ExprResult msg = BuildInstanceMessageImplicit(SrcExpr, SrcType, InstanceMethod->getLocation(), @@ -4144,7 +4144,7 @@ Sema::CheckObjCConversion(SourceRange castRange, QualType castType, QualType effCastType = castType; if (const ReferenceType *ref = castType->getAs<ReferenceType>()) effCastType = ref->getPointeeType(); - + ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType); ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType); if (exprACTC == castACTC) { @@ -4167,7 +4167,7 @@ Sema::CheckObjCConversion(SourceRange castRange, QualType castType, if (QDT != castType && QDT.getObjCLifetime() != Qualifiers::OCL_None) { if (Diagnose) { - SourceLocation loc = (castRange.isValid() ? castRange.getBegin() + SourceLocation loc = (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc()); Diag(loc, diag::err_arc_nolifetime_behavior); } @@ -4188,7 +4188,7 @@ Sema::CheckObjCConversion(SourceRange castRange, QualType castType, // vice-versa). if (castACTC == ACTC_none && castType->isIntegralType(Context)) return ACR_okay; - + // Allow casts between pointers to lifetime types (e.g., __strong id*) // and pointers to void (e.g., cv void *). Casting from void* to lifetime* // must be explicit. @@ -4229,7 +4229,7 @@ Sema::CheckObjCConversion(SourceRange castRange, QualType castType, if (castACTC == ACTC_retainable && exprACTC == ACTC_none && ConversionToObjCStringLiteralCheck(castType, castExpr, Diagnose)) return ACR_error; - + // Do not issue "bridge cast" diagnostic when implicit casting // a retainable object to a CF type parameter belonging to an audited // CF API function. Let caller issue a normal type mismatched diagnostic @@ -4322,9 +4322,9 @@ Expr *Sema::stripARCUnbridgedCast(Expr *e) { bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType, QualType exprType) { - QualType canCastType = + QualType canCastType = Context.getCanonicalType(castType).getUnqualifiedType(); - QualType canExprType = + QualType canExprType = Context.getCanonicalType(exprType).getUnqualifiedType(); if (isa<ObjCObjectPointerType>(canCastType) && castType.getObjCLifetime() == Qualifiers::OCL_Weak && @@ -4399,7 +4399,7 @@ ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc, switch (Kind) { case OBC_Bridge: break; - + case OBC_BridgeRetained: { bool br = isKnownName("CFBridgingRelease"); Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind) @@ -4413,14 +4413,14 @@ ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc, << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge"); Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer) << FromType << br - << FixItHint::CreateReplacement(BridgeKeywordLoc, - br ? "CFBridgingRelease " + << FixItHint::CreateReplacement(BridgeKeywordLoc, + br ? "CFBridgingRelease " : "__bridge_transfer "); Kind = OBC_Bridge; break; } - + case OBC_BridgeTransfer: // We must consume the Objective-C object produced by the cast. MustConsume = true; @@ -4435,14 +4435,14 @@ ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc, // is very dangerous, so we don't do it. SubExpr = maybeUndoReclaimObject(SubExpr); break; - - case OBC_BridgeRetained: + + case OBC_BridgeRetained: // Produce the object before casting it. SubExpr = ImplicitCastExpr::Create(Context, FromType, CK_ARCProduceObject, SubExpr, nullptr, VK_RValue); break; - + case OBC_BridgeTransfer: { bool br = isKnownName("CFBridgingRetain"); Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind) @@ -4452,14 +4452,14 @@ ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc, << T << SubExpr->getSourceRange() << Kind; - + Diag(BridgeKeywordLoc, diag::note_arc_bridge) << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge "); Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained) << T << br - << FixItHint::CreateReplacement(BridgeKeywordLoc, + << FixItHint::CreateReplacement(BridgeKeywordLoc, br ? "CFBridgingRetain " : "__bridge_retained"); - + Kind = OBC_Bridge; break; } @@ -4475,13 +4475,13 @@ ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc, Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK, BridgeKeywordLoc, TSInfo, SubExpr); - + if (MustConsume) { Cleanup.setExprNeedsCleanups(true); - Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result, + Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result, nullptr, VK_RValue); } - + return Result; } @@ -4498,6 +4498,6 @@ ExprResult Sema::ActOnObjCBridgedCast(Scope *S, CheckTollFreeBridgeCast(T, SubExpr); if (!TSInfo) TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc); - return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo, + return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo, SubExpr); } diff --git a/lib/Sema/SemaInit.cpp b/lib/Sema/SemaInit.cpp index 3ee5ec4a4929..f006a677b678 100644 --- a/lib/Sema/SemaInit.cpp +++ b/lib/Sema/SemaInit.cpp @@ -191,7 +191,7 @@ static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT, if (SL->isPascal()) StrLength--; } - + // [dcl.init.string]p2 if (StrLength > CAT->getSize().getZExtValue()) S.Diag(Str->getLocStart(), @@ -450,7 +450,7 @@ ExprResult InitListChecker::PerformEmptyInit(Sema &SemaRef, IsInStd = true; } - if (IsInStd && llvm::StringSwitch<bool>(R->getName()) + if (IsInStd && llvm::StringSwitch<bool>(R->getName()) .Cases("basic_string", "deque", "forward_list", true) .Cases("list", "map", "multimap", "multiset", true) .Cases("priority_queue", "queue", "set", "stack", true) @@ -1578,7 +1578,7 @@ void InitListChecker::CheckVectorType(const InitializedEntity &Entity, T->getVectorKind() == VectorType::NeonPolyVector)) { // The ability to use vector initializer lists is a GNU vector extension // and is unrelated to the NEON intrinsics in arm_neon.h. On little - // endian machines it works fine, however on big endian machines it + // endian machines it works fine, however on big endian machines it // exhibits surprising behaviour: // // uint32x2_t x = {42, 64}; @@ -2225,7 +2225,7 @@ InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity, SemaRef.Diag(D->getLocStart(), diag::warn_subobject_initializer_overrides) << SourceRange(D->getLocStart(), DIE->getLocEnd()); - + SemaRef.Diag(ExistingInit->getLocStart(), diag::note_previous_initializer) << /*FIXME:has side effects=*/0 @@ -3000,7 +3000,7 @@ DeclarationName InitializedEntity::getName() const { case EK_LambdaCapture: return DeclarationName(Capture.VarID); - + case EK_Result: case EK_StmtExprResult: case EK_Exception: @@ -3653,13 +3653,13 @@ ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc, CandidateSet, SuppressUserConversions); else { // C++ [over.match.copy]p1: - // - When initializing a temporary to be bound to the first parameter + // - When initializing a temporary to be bound to the first parameter // of a constructor [for type T] that takes a reference to possibly // cv-qualified T as its first argument, called with a single // argument in the context of direct-initialization, explicit // conversion functions are also considered. // FIXME: What if a constructor template instantiates to such a signature? - bool AllowExplicitConv = AllowExplicit && !CopyInitializing && + bool AllowExplicitConv = AllowExplicit && !CopyInitializing && Args.size() == 1 && hasCopyOrMoveCtorParam(S.Context, Info); S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args, @@ -4226,7 +4226,7 @@ static OverloadingResult TryRefInitWithConversionFunction( (void)DerivedToBase; (void)ObjCConversion; (void)ObjCLifetimeConversion; - + // Build the candidate set directly in the initialization sequence // structure, so that it will persist if we fail. OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); @@ -4646,7 +4646,7 @@ static void TryReferenceInitializationCore(Sema &S, /*FIXME:InOverloadResolution=*/false, /*CStyle=*/Kind.isCStyleOrFunctionalCast(), /*AllowObjCWritebackConversion=*/false); - + if (ICS.isBad()) { // FIXME: Use the conversion function set stored in ICS to turn // this into an overloading ambiguity diagnostic. However, we need @@ -4787,7 +4787,7 @@ static void TryDefaultInitialization(Sema &S, // To default-initialize an object of type T means: // - if T is an array type, each element is default-initialized; QualType DestType = S.Context.getBaseElementType(Entity.getType()); - + // - if T is a (possibly cv-qualified) class type (Clause 9), the default // constructor for T is called (and the initialization is ill-formed if // T has no accessible default constructor); @@ -5043,11 +5043,11 @@ static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e, // If we have a declaration reference, it had better be a local variable. } else if (isa<DeclRefExpr>(e)) { - // set isWeakAccess to true, to mean that there will be an implicit + // set isWeakAccess to true, to mean that there will be an implicit // load which requires a cleanup. if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak) isWeakAccess = true; - + if (!isAddressOf) return IIK_nonlocal; VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl()); @@ -5082,7 +5082,7 @@ static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) { assert(src->isRValue()); bool isWeakAccess = false; InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess); - // If isWeakAccess to true, there will be an implicit + // If isWeakAccess to true, there will be an implicit // load which requires a cleanup. if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess) S.Cleanup.setExprNeedsCleanups(true); @@ -5124,7 +5124,7 @@ static bool tryObjCWritebackConversion(Sema &S, ArgPointee = ArgArrayType->getElementType(); ArgType = S.Context.getPointerType(ArgPointee); } - + // Handle write-back conversion. QualType ConvertedArgType; if (!S.isObjCWritebackConversion(ArgType, Entity.getType(), @@ -5151,10 +5151,10 @@ static bool tryObjCWritebackConversion(Sema &S, ICS.Standard.First = ICK_Lvalue_To_Rvalue; ResultType = Initializer->getType().getNonLValueExprType(S.Context); } - + Sequence.AddConversionSequenceStep(ICS, ResultType); } - + Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy); return true; } @@ -5567,13 +5567,13 @@ void InitializationSequence::InitializeFrom(Sema &S, if (ICS.isStandard() && ICS.Standard.Second == ICK_Writeback_Conversion) { // Objective-C ARC writeback conversion. - + // We should copy unless we're passing to an argument explicitly // marked 'out'. bool ShouldCopy = true; if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl())) ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out); - + // If there was an lvalue adjustment, add it as a separate conversion. if (ICS.Standard.First == ICK_Array_To_Pointer || ICS.Standard.First == ICK_Lvalue_To_Rvalue) { @@ -5584,7 +5584,7 @@ void InitializationSequence::InitializeFrom(Sema &S, LvalueICS.Standard.First = ICS.Standard.First; AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0)); } - + AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy); } else if (ICS.isBad()) { DeclAccessPair dap; @@ -5635,9 +5635,9 @@ getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) { if (Entity.getDecl() && isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext())) return Sema::AA_Sending; - + return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited; - + case InitializedEntity::EK_Result: case InitializedEntity::EK_StmtExprResult: // FIXME: Not quite right. return Sema::AA_Returning; @@ -5743,7 +5743,7 @@ static SourceLocation getInitializationLoc(const InitializedEntity &Entity, case InitializedEntity::EK_LambdaCapture: return Entity.getCaptureLoc(); - + case InitializedEntity::EK_ArrayElement: case InitializedEntity::EK_Member: case InitializedEntity::EK_Parameter: @@ -6065,9 +6065,9 @@ PerformConstructorInitialization(Sema &S, ExprResult CurInit((Expr *)nullptr); // C++ [over.match.copy]p1: - // - When initializing a temporary to be bound to the first parameter - // of a constructor that takes a reference to possibly cv-qualified - // T as its first argument, called with a single argument in the + // - When initializing a temporary to be bound to the first parameter + // of a constructor that takes a reference to possibly cv-qualified + // T as its first argument, called with a single argument in the // context of direct-initialization, explicit conversion functions // are also considered. bool AllowExplicitConv = @@ -6322,12 +6322,14 @@ struct IndirectLocalPathEntry { AddressOf, VarInit, LValToRVal, + LifetimeBoundCall, } Kind; Expr *E; - Decl *D = nullptr; + const Decl *D = nullptr; IndirectLocalPathEntry() {} IndirectLocalPathEntry(EntryKind K, Expr *E) : Kind(K), E(E) {} - IndirectLocalPathEntry(EntryKind K, Expr *E, Decl *D) : Kind(K), E(E), D(D) {} + IndirectLocalPathEntry(EntryKind K, Expr *E, const Decl *D) + : Kind(K), E(E), D(D) {} }; using IndirectLocalPath = llvm::SmallVectorImpl<IndirectLocalPathEntry>; @@ -6361,6 +6363,68 @@ static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path, Expr *Init, LocalVisitor Visit, bool RevisitSubinits); +static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path, + Expr *Init, ReferenceKind RK, + LocalVisitor Visit); + +static bool implicitObjectParamIsLifetimeBound(const FunctionDecl *FD) { + const TypeSourceInfo *TSI = FD->getTypeSourceInfo(); + if (!TSI) + return false; + for (TypeLoc TL = TSI->getTypeLoc(); + auto ATL = TL.getAsAdjusted<AttributedTypeLoc>(); + TL = ATL.getModifiedLoc()) { + if (ATL.getAttrKind() == AttributedType::attr_lifetimebound) + return true; + } + return false; +} + +static void visitLifetimeBoundArguments(IndirectLocalPath &Path, Expr *Call, + LocalVisitor Visit) { + const FunctionDecl *Callee; + ArrayRef<Expr*> Args; + + if (auto *CE = dyn_cast<CallExpr>(Call)) { + Callee = CE->getDirectCallee(); + Args = llvm::makeArrayRef(CE->getArgs(), CE->getNumArgs()); + } else { + auto *CCE = cast<CXXConstructExpr>(Call); + Callee = CCE->getConstructor(); + Args = llvm::makeArrayRef(CCE->getArgs(), CCE->getNumArgs()); + } + if (!Callee) + return; + + Expr *ObjectArg = nullptr; + if (isa<CXXOperatorCallExpr>(Call) && Callee->isCXXInstanceMember()) { + ObjectArg = Args[0]; + Args = Args.slice(1); + } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) { + ObjectArg = MCE->getImplicitObjectArgument(); + } + + auto VisitLifetimeBoundArg = [&](const Decl *D, Expr *Arg) { + Path.push_back({IndirectLocalPathEntry::LifetimeBoundCall, Arg, D}); + if (Arg->isGLValue()) + visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding, + Visit); + else + visitLocalsRetainedByInitializer(Path, Arg, Visit, true); + Path.pop_back(); + }; + + if (ObjectArg && implicitObjectParamIsLifetimeBound(Callee)) + VisitLifetimeBoundArg(Callee, ObjectArg); + + for (unsigned I = 0, + N = std::min<unsigned>(Callee->getNumParams(), Args.size()); + I != N; ++I) { + if (Callee->getParamDecl(I)->hasAttr<LifetimeBoundAttr>()) + VisitLifetimeBoundArg(Callee->getParamDecl(I), Args[I]); + } +} + /// Visit the locals that would be reachable through a reference bound to the /// glvalue expression \c Init. static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path, @@ -6420,6 +6484,9 @@ static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path, true); } + if (isa<CallExpr>(Init)) + return visitLifetimeBoundArguments(Path, Init, Visit); + switch (Init->getStmtClass()) { case Stmt::DeclRefExprClass: { // If we find the name of a local non-reference parameter, we could have a @@ -6483,21 +6550,90 @@ static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path, bool RevisitSubinits) { RevertToOldSizeRAII RAII(Path); - // Step into CXXDefaultInitExprs so we can diagnose cases where a - // constructor inherits one as an implicit mem-initializer. - if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) { - Path.push_back({IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()}); - Init = DIE->getExpr(); - } + Expr *Old; + do { + Old = Init; - if (auto *EWC = dyn_cast<ExprWithCleanups>(Init)) - Init = EWC->getSubExpr(); + // Step into CXXDefaultInitExprs so we can diagnose cases where a + // constructor inherits one as an implicit mem-initializer. + if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) { + Path.push_back({IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()}); + Init = DIE->getExpr(); + } - // Dig out the expression which constructs the extended temporary. - Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments()); + if (auto *EWC = dyn_cast<ExprWithCleanups>(Init)) + Init = EWC->getSubExpr(); + + // Dig out the expression which constructs the extended temporary. + Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments()); - if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init)) - Init = BTE->getSubExpr(); + if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init)) + Init = BTE->getSubExpr(); + + Init = Init->IgnoreParens(); + + // Step over value-preserving rvalue casts. + if (auto *CE = dyn_cast<CastExpr>(Init)) { + switch (CE->getCastKind()) { + case CK_LValueToRValue: + // If we can match the lvalue to a const object, we can look at its + // initializer. + Path.push_back({IndirectLocalPathEntry::LValToRVal, CE}); + return visitLocalsRetainedByReferenceBinding( + Path, Init, RK_ReferenceBinding, + [&](IndirectLocalPath &Path, Local L, ReferenceKind RK) -> bool { + if (auto *DRE = dyn_cast<DeclRefExpr>(L)) { + auto *VD = dyn_cast<VarDecl>(DRE->getDecl()); + if (VD && VD->getType().isConstQualified() && VD->getInit() && + !isVarOnPath(Path, VD)) { + Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD}); + visitLocalsRetainedByInitializer(Path, VD->getInit(), Visit, true); + } + } else if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L)) { + if (MTE->getType().isConstQualified()) + visitLocalsRetainedByInitializer(Path, MTE->GetTemporaryExpr(), + Visit, true); + } + return false; + }); + + // We assume that objects can be retained by pointers cast to integers, + // but not if the integer is cast to floating-point type or to _Complex. + // We assume that casts to 'bool' do not preserve enough information to + // retain a local object. + case CK_NoOp: + case CK_BitCast: + case CK_BaseToDerived: + case CK_DerivedToBase: + case CK_UncheckedDerivedToBase: + case CK_Dynamic: + case CK_ToUnion: + case CK_UserDefinedConversion: + case CK_ConstructorConversion: + case CK_IntegralToPointer: + case CK_PointerToIntegral: + case CK_VectorSplat: + case CK_IntegralCast: + case CK_CPointerToObjCPointerCast: + case CK_BlockPointerToObjCPointerCast: + case CK_AnyPointerToBlockPointerCast: + case CK_AddressSpaceConversion: + break; + + case CK_ArrayToPointerDecay: + // Model array-to-pointer decay as taking the address of the array + // lvalue. + Path.push_back({IndirectLocalPathEntry::AddressOf, CE}); + return visitLocalsRetainedByReferenceBinding(Path, CE->getSubExpr(), + RK_ReferenceBinding, Visit); + + default: + return; + } + + Init = CE->getSubExpr(); + } + } while (Old != Init); // C++17 [dcl.init.list]p6: // initializing an initializer_list object from the array extends the @@ -6558,66 +6694,9 @@ static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path, return; } - // Step over value-preserving rvalue casts. - while (auto *CE = dyn_cast<CastExpr>(Init)) { - switch (CE->getCastKind()) { - case CK_LValueToRValue: - // If we can match the lvalue to a const object, we can look at its - // initializer. - Path.push_back({IndirectLocalPathEntry::LValToRVal, CE}); - return visitLocalsRetainedByReferenceBinding( - Path, Init, RK_ReferenceBinding, - [&](IndirectLocalPath &Path, Local L, ReferenceKind RK) -> bool { - if (auto *DRE = dyn_cast<DeclRefExpr>(L)) { - auto *VD = dyn_cast<VarDecl>(DRE->getDecl()); - if (VD && VD->getType().isConstQualified() && VD->getInit()) { - Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD}); - visitLocalsRetainedByInitializer(Path, VD->getInit(), Visit, true); - } - } else if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L)) { - if (MTE->getType().isConstQualified()) - visitLocalsRetainedByInitializer(Path, MTE->GetTemporaryExpr(), - Visit, true); - } - return false; - }); - - // We assume that objects can be retained by pointers cast to integers, - // but not if the integer is cast to floating-point type or to _Complex. - // We assume that casts to 'bool' do not preserve enough information to - // retain a local object. - case CK_NoOp: - case CK_BitCast: - case CK_BaseToDerived: - case CK_DerivedToBase: - case CK_UncheckedDerivedToBase: - case CK_Dynamic: - case CK_ToUnion: - case CK_IntegralToPointer: - case CK_PointerToIntegral: - case CK_VectorSplat: - case CK_IntegralCast: - case CK_CPointerToObjCPointerCast: - case CK_BlockPointerToObjCPointerCast: - case CK_AnyPointerToBlockPointerCast: - case CK_AddressSpaceConversion: - break; - - case CK_ArrayToPointerDecay: - // Model array-to-pointer decay as taking the address of the array - // lvalue. - Path.push_back({IndirectLocalPathEntry::AddressOf, CE}); - return visitLocalsRetainedByReferenceBinding(Path, CE->getSubExpr(), - RK_ReferenceBinding, Visit); - - default: - return; - } - - Init = CE->getSubExpr(); - } + if (isa<CallExpr>(Init) || isa<CXXConstructExpr>(Init)) + return visitLifetimeBoundArguments(Path, Init, Visit); - Init = Init->IgnoreParens(); switch (Init->getStmtClass()) { case Stmt::UnaryOperatorClass: { auto *UO = cast<UnaryOperator>(Init); @@ -6697,6 +6776,7 @@ static SourceRange nextPathEntryRange(const IndirectLocalPath &Path, unsigned I, switch (Path[I].Kind) { case IndirectLocalPathEntry::AddressOf: case IndirectLocalPathEntry::LValToRVal: + case IndirectLocalPathEntry::LifetimeBoundCall: // These exist primarily to mark the path as not permitting or // supporting lifetime extension. break; @@ -6767,8 +6847,9 @@ void Sema::checkInitializerLifetime(const InitializedEntity &Entity, return false; Diag(DiagLoc, diag::warn_dangling_variable) - << RK << !Entity.getParent() << ExtendingEntity->getDecl() - << Init->isGLValue() << DiagRange; + << RK << !Entity.getParent() + << ExtendingEntity->getDecl()->isImplicit() + << ExtendingEntity->getDecl() << Init->isGLValue() << DiagRange; } break; } @@ -6875,6 +6956,10 @@ void Sema::checkInitializerLifetime(const InitializedEntity &Entity, // supporting lifetime extension. break; + case IndirectLocalPathEntry::LifetimeBoundCall: + // FIXME: Consider adding a note for this. + break; + case IndirectLocalPathEntry::DefaultInit: { auto *FD = cast<FieldDecl>(Elem.D); Diag(FD->getLocation(), diag::note_init_with_default_member_initalizer) @@ -6885,7 +6970,8 @@ void Sema::checkInitializerLifetime(const InitializedEntity &Entity, case IndirectLocalPathEntry::VarInit: const VarDecl *VD = cast<VarDecl>(Elem.D); Diag(VD->getLocation(), diag::note_local_var_initializer) - << VD->getType()->isReferenceType() << VD->getDeclName() + << VD->getType()->isReferenceType() + << VD->isImplicit() << VD->getDeclName() << nextPathEntryRange(Path, I + 1, L); break; } @@ -7129,7 +7215,7 @@ InitializationSequence::Perform(Sema &S, Args); } assert(Kind.getKind() == InitializationKind::IK_Copy || - Kind.isExplicitCast() || + Kind.isExplicitCast() || Kind.getKind() == InitializationKind::IK_DirectList); return ExprResult(Args[0]); } @@ -7831,7 +7917,7 @@ InitializationSequence::Perform(Sema &S, // this has already been done when parsing the variable declaration. if (!Init->isConstantInitializer(S.Context, false)) break; - + if (!SourceType->isIntegerType() || 32 != S.Context.getIntWidth(SourceType)) { S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer) @@ -7867,7 +7953,7 @@ InitializationSequence::Perform(Sema &S, break; } case SK_OCLZeroEvent: { - assert(Step->Type->isEventT() && + assert(Step->Type->isEventT() && "Event initialization on non-event type."); CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, @@ -8364,7 +8450,7 @@ bool InitializationSequence::Diagnose(Sema &S, llvm_unreachable("Inconsistent overload resolution?"); break; } - + // If this is a defaulted or implicitly-declared function, then // it was implicitly deleted. Make it clear that the deletion was // implicit. diff --git a/lib/Sema/SemaLambda.cpp b/lib/Sema/SemaLambda.cpp index a42b2e827e9b..440567e032e4 100644 --- a/lib/Sema/SemaLambda.cpp +++ b/lib/Sema/SemaLambda.cpp @@ -25,28 +25,28 @@ using namespace clang; using namespace sema; /// Examines the FunctionScopeInfo stack to determine the nearest -/// enclosing lambda (to the current lambda) that is 'capture-ready' for +/// enclosing lambda (to the current lambda) that is 'capture-ready' for /// the variable referenced in the current lambda (i.e. \p VarToCapture). /// If successful, returns the index into Sema's FunctionScopeInfo stack /// of the capture-ready lambda's LambdaScopeInfo. -/// -/// Climbs down the stack of lambdas (deepest nested lambda - i.e. current +/// +/// Climbs down the stack of lambdas (deepest nested lambda - i.e. current /// lambda - is on top) to determine the index of the nearest enclosing/outer -/// lambda that is ready to capture the \p VarToCapture being referenced in -/// the current lambda. +/// lambda that is ready to capture the \p VarToCapture being referenced in +/// the current lambda. /// As we climb down the stack, we want the index of the first such lambda - -/// that is the lambda with the highest index that is 'capture-ready'. -/// +/// that is the lambda with the highest index that is 'capture-ready'. +/// /// A lambda 'L' is capture-ready for 'V' (var or this) if: /// - its enclosing context is non-dependent /// - and if the chain of lambdas between L and the lambda in which -/// V is potentially used (i.e. the lambda at the top of the scope info +/// V is potentially used (i.e. the lambda at the top of the scope info /// stack), can all capture or have already captured V. /// If \p VarToCapture is 'null' then we are trying to capture 'this'. -/// +/// /// Note that a lambda that is deemed 'capture-ready' still needs to be checked /// for whether it is 'capture-capable' (see -/// getStackIndexOfNearestEnclosingCaptureCapableLambda), before it can truly +/// getStackIndexOfNearestEnclosingCaptureCapableLambda), before it can truly /// capture. /// /// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a @@ -120,7 +120,7 @@ getStackIndexOfNearestEnclosingCaptureReadyLambda( return NoLambdaIsCaptureReady; } EnclosingDC = getLambdaAwareParentOfDeclContext(EnclosingDC); - + assert(CurScopeIndex); --CurScopeIndex; } while (!EnclosingDC->isTranslationUnit() && @@ -136,13 +136,13 @@ getStackIndexOfNearestEnclosingCaptureReadyLambda( } /// Examines the FunctionScopeInfo stack to determine the nearest -/// enclosing lambda (to the current lambda) that is 'capture-capable' for +/// enclosing lambda (to the current lambda) that is 'capture-capable' for /// the variable referenced in the current lambda (i.e. \p VarToCapture). /// If successful, returns the index into Sema's FunctionScopeInfo stack /// of the capture-capable lambda's LambdaScopeInfo. /// /// Given the current stack of lambdas being processed by Sema and -/// the variable of interest, to identify the nearest enclosing lambda (to the +/// the variable of interest, to identify the nearest enclosing lambda (to the /// current lambda at the top of the stack) that can truly capture /// a variable, it has to have the following two properties: /// a) 'capture-ready' - be the innermost lambda that is 'capture-ready': @@ -175,7 +175,7 @@ Optional<unsigned> clang::getStackIndexOfNearestEnclosingCaptureCapableLambda( VarDecl *VarToCapture, Sema &S) { const Optional<unsigned> NoLambdaIsCaptureCapable; - + const Optional<unsigned> OptionalStackIndex = getStackIndexOfNearestEnclosingCaptureReadyLambda(FunctionScopes, VarToCapture); @@ -190,7 +190,7 @@ Optional<unsigned> clang::getStackIndexOfNearestEnclosingCaptureCapableLambda( const sema::LambdaScopeInfo *const CaptureReadyLambdaLSI = cast<sema::LambdaScopeInfo>(FunctionScopes[IndexOfCaptureReadyLambda]); - + // If VarToCapture is null, we are attempting to capture 'this' const bool IsCapturingThis = !VarToCapture; const bool IsCapturingVariable = !IsCapturingThis; @@ -220,7 +220,7 @@ Optional<unsigned> clang::getStackIndexOfNearestEnclosingCaptureCapableLambda( &IndexOfCaptureReadyLambda); if (!CanCaptureThis) return NoLambdaIsCaptureCapable; - } + } return IndexOfCaptureReadyLambda; } @@ -245,18 +245,18 @@ getGenericLambdaTemplateParameterList(LambdaScopeInfo *LSI, Sema &SemaRef) { CXXRecordDecl *Sema::createLambdaClosureType(SourceRange IntroducerRange, TypeSourceInfo *Info, - bool KnownDependent, + bool KnownDependent, LambdaCaptureDefault CaptureDefault) { DeclContext *DC = CurContext; while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext())) DC = DC->getParent(); bool IsGenericLambda = getGenericLambdaTemplateParameterList(getCurLambda(), - *this); + *this); // Start constructing the lambda class. CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(Context, DC, Info, IntroducerRange.getBegin(), - KnownDependent, - IsGenericLambda, + KnownDependent, + IsGenericLambda, CaptureDefault); DC->addDecl(Class); @@ -270,10 +270,10 @@ static bool isInInlineFunction(const DeclContext *DC) { if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) if (FD->isInlined()) return true; - + DC = DC->getLexicalParent(); } - + return false; } @@ -379,10 +379,10 @@ CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class, ArrayRef<ParmVarDecl *> Params, const bool IsConstexprSpecified) { QualType MethodType = MethodTypeInfo->getType(); - TemplateParameterList *TemplateParams = + TemplateParameterList *TemplateParams = getGenericLambdaTemplateParameterList(getCurLambda(), *this); // If a lambda appears in a dependent context or is a generic lambda (has - // template parameters) and has an 'auto' return type, deduce it to a + // template parameters) and has an 'auto' return type, deduce it to a // dependent type. if (Class->isDependentContext() || TemplateParams) { const FunctionProtoType *FPT = MethodType->castAs<FunctionProtoType>(); @@ -395,9 +395,9 @@ CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class, } // C++11 [expr.prim.lambda]p5: - // The closure type for a lambda-expression has a public inline function + // The closure type for a lambda-expression has a public inline function // call operator (13.5.4) whose parameters and return type are described by - // the lambda-expression's parameter-declaration-clause and + // the lambda-expression's parameter-declaration-clause and // trailing-return-type respectively. DeclarationName MethodName = Context.DeclarationNames.getCXXOperatorName(OO_Call); @@ -408,7 +408,7 @@ CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class, = IntroducerRange.getEnd().getRawEncoding(); CXXMethodDecl *Method = CXXMethodDecl::Create(Context, Class, EndLoc, - DeclarationNameInfo(MethodName, + DeclarationNameInfo(MethodName, IntroducerRange.getBegin(), MethodNameLoc), MethodType, MethodTypeInfo, @@ -417,14 +417,14 @@ CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class, IsConstexprSpecified, EndLoc); Method->setAccess(AS_public); - + // Temporarily set the lexical declaration context to the current // context, so that the Scope stack matches the lexical nesting. - Method->setLexicalDeclContext(CurContext); + Method->setLexicalDeclContext(CurContext); // Create a function template if we have a template parameter list FunctionTemplateDecl *const TemplateMethod = TemplateParams ? FunctionTemplateDecl::Create(Context, Class, - Method->getLocation(), MethodName, + Method->getLocation(), MethodName, TemplateParams, Method) : nullptr; if (TemplateMethod) { @@ -432,7 +432,7 @@ CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class, TemplateMethod->setAccess(AS_public); Method->setDescribedFunctionTemplate(TemplateMethod); } - + // Add parameters. if (!Params.empty()) { Method->setParams(Params); @@ -493,16 +493,16 @@ void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) { LSI->finishedExplicitCaptures(); } -void Sema::addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope) { +void Sema::addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope) { // Introduce our parameters into the function scope - for (unsigned p = 0, NumParams = CallOperator->getNumParams(); + for (unsigned p = 0, NumParams = CallOperator->getNumParams(); p < NumParams; ++p) { ParmVarDecl *Param = CallOperator->getParamDecl(p); - + // If this has an identifier, add it to the scope stack. if (CurScope && Param->getIdentifier()) { CheckShadow(CurScope, Param); - + PushOnScopeChains(Param, CurScope); } } @@ -637,7 +637,7 @@ static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns, void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) { assert(CSI.HasImplicitReturnType); // If it was ever a placeholder, it had to been deduced to DependentTy. - assert(CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType()); + assert(CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType()); assert((!isa<LambdaScopeInfo>(CSI) || !getLangOpts().CPlusPlus14) && "lambda expressions use auto deduction in C++14 onwards"); @@ -851,7 +851,7 @@ void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, SmallVector<ParmVarDecl *, 8> Params; if (ParamInfo.getNumTypeObjects() == 0) { // C++11 [expr.prim.lambda]p4: - // If a lambda-expression does not include a lambda-declarator, it is as + // If a lambda-expression does not include a lambda-declarator, it is as // if the lambda-declarator were (). FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention( /*IsVariadic=*/false, /*IsCXXMethod=*/true)); @@ -878,8 +878,8 @@ void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo(); // C++11 [expr.prim.lambda]p5: - // This function call operator is declared const (9.3.1) if and only if - // the lambda-expression's parameter-declaration-clause is not followed + // This function call operator is declared const (9.3.1) if and only if + // the lambda-expression's parameter-declaration-clause is not followed // by mutable. It is neither virtual nor declared volatile. [...] if (!FTI.hasMutableQualifier()) FTI.TypeQuals |= DeclSpec::TQ_const; @@ -917,8 +917,8 @@ void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, // code_seg attribute on lambda apply to the method. if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true)) Method->addAttr(A); - - // Attributes on the lambda apply to the method. + + // Attributes on the lambda apply to the method. ProcessDeclAttributes(CurScope, Method, ParamInfo); // CUDA lambdas get implicit attributes based on the scope in which they're @@ -928,7 +928,7 @@ void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, // Introduce the function call operator as the current declaration context. PushDeclContext(CurScope, Method); - + // Build the lambda scope. buildLambdaScope(LSI, Method, Intro.Range, Intro.Default, Intro.DefaultLoc, ExplicitParams, ExplicitResultType, !Method->isConst()); @@ -959,13 +959,13 @@ void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, for (auto C = Intro.Captures.begin(), E = Intro.Captures.end(); C != E; PrevCaptureLoc = C->Loc, ++C) { if (C->Kind == LCK_This || C->Kind == LCK_StarThis) { - if (C->Kind == LCK_StarThis) + if (C->Kind == LCK_StarThis) Diag(C->Loc, !getLangOpts().CPlusPlus17 ? diag::ext_star_this_lambda_capture_cxx17 : diag::warn_cxx14_compat_star_this_lambda_capture); // C++11 [expr.prim.lambda]p8: - // An identifier or this shall not appear more than once in a + // An identifier or this shall not appear more than once in a // lambda-capture. if (LSI->isCXXThisCaptured()) { Diag(C->Loc, diag::err_capture_more_than_once) @@ -993,7 +993,7 @@ void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, Diag(C->Loc, diag::err_this_capture) << true; continue; } - + CheckCXXThisCapture(C->Loc, /*Explicit=*/true, /*BuildAndDiagnose*/ true, /*FunctionScopeIndexToStopAtPtr*/ nullptr, C->Kind == LCK_StarThis); @@ -1018,9 +1018,9 @@ void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, // If the initializer expression is usable, but the InitCaptureType // is not, then an error has occurred - so ignore the capture for now. // for e.g., [n{0}] { }; <-- if no <initializer_list> is included. - // FIXME: we should create the init capture variable and mark it invalid + // FIXME: we should create the init capture variable and mark it invalid // in this case. - if (C->InitCaptureType.get().isNull()) + if (C->InitCaptureType.get().isNull()) continue; unsigned InitStyle; @@ -1050,7 +1050,7 @@ void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, "init capture has valid but null init?"); // C++11 [expr.prim.lambda]p8: - // If a lambda-capture includes a capture-default that is &, the + // If a lambda-capture includes a capture-default that is &, the // identifiers in the lambda-capture shall not be preceded by &. // If a lambda-capture includes a capture-default that is =, [...] // each identifier it contains shall be preceded by &. @@ -1131,7 +1131,7 @@ void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, } else { Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) << SourceRange(C->Loc); - + // Just ignore the ellipsis. } } else if (Var->isParameterPack()) { @@ -1189,14 +1189,14 @@ QualType Sema::getLambdaConversionFunctionResultType( // The function type inside the pointer type is the same as the call // operator with some tweaks. The calling convention is the default free // function convention, and the type qualifications are lost. - const FunctionProtoType::ExtProtoInfo CallOpExtInfo = - CallOpProto->getExtProtoInfo(); + const FunctionProtoType::ExtProtoInfo CallOpExtInfo = + CallOpProto->getExtProtoInfo(); FunctionProtoType::ExtProtoInfo InvokerExtInfo = CallOpExtInfo; CallingConv CC = Context.getDefaultCallingConvention( CallOpProto->isVariadic(), /*IsCXXMethod=*/false); InvokerExtInfo.ExtInfo = InvokerExtInfo.ExtInfo.withCallingConv(CC); InvokerExtInfo.TypeQuals = 0; - assert(InvokerExtInfo.RefQualifier == RQ_None && + assert(InvokerExtInfo.RefQualifier == RQ_None && "Lambda's call operator should not have a reference qualifier"); return Context.getFunctionType(CallOpProto->getReturnType(), CallOpProto->getParamTypes(), InvokerExtInfo); @@ -1227,7 +1227,7 @@ static void addFunctionPointerConversion(Sema &S, /*IsVariadic=*/false, /*IsCXXMethod=*/true)); // The conversion function is always const. ConvExtInfo.TypeQuals = Qualifiers::Const; - QualType ConvTy = + QualType ConvTy = S.Context.getFunctionType(PtrToFunctionTy, None, ConvExtInfo); SourceLocation Loc = IntroducerRange.getBegin(); @@ -1236,8 +1236,8 @@ static void addFunctionPointerConversion(Sema &S, S.Context.getCanonicalType(PtrToFunctionTy)); DeclarationNameLoc ConvNameLoc; // Construct a TypeSourceInfo for the conversion function, and wire - // all the parameters appropriately for the FunctionProtoTypeLoc - // so that everything works during transformation/instantiation of + // all the parameters appropriately for the FunctionProtoTypeLoc + // so that everything works during transformation/instantiation of // generic lambdas. // The main reason for wiring up the parameters of the conversion // function with that of the call operator is so that constructs @@ -1247,46 +1247,46 @@ static void addFunctionPointerConversion(Sema &S, // return a; // }; // }; - // int (*fp)(int) = L(5); + // int (*fp)(int) = L(5); // Because the trailing return type can contain DeclRefExprs that refer - // to the original call operator's variables, we hijack the call + // to the original call operator's variables, we hijack the call // operators ParmVarDecls below. - TypeSourceInfo *ConvNamePtrToFunctionTSI = + TypeSourceInfo *ConvNamePtrToFunctionTSI = S.Context.getTrivialTypeSourceInfo(PtrToFunctionTy, Loc); ConvNameLoc.NamedType.TInfo = ConvNamePtrToFunctionTSI; // The conversion function is a conversion to a pointer-to-function. TypeSourceInfo *ConvTSI = S.Context.getTrivialTypeSourceInfo(ConvTy, Loc); - FunctionProtoTypeLoc ConvTL = + FunctionProtoTypeLoc ConvTL = ConvTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>(); // Get the result of the conversion function which is a pointer-to-function. - PointerTypeLoc PtrToFunctionTL = + PointerTypeLoc PtrToFunctionTL = ConvTL.getReturnLoc().getAs<PointerTypeLoc>(); // Do the same for the TypeSourceInfo that is used to name the conversion // operator. - PointerTypeLoc ConvNamePtrToFunctionTL = + PointerTypeLoc ConvNamePtrToFunctionTL = ConvNamePtrToFunctionTSI->getTypeLoc().getAs<PointerTypeLoc>(); - + // Get the underlying function types that the conversion function will // be converting to (should match the type of the call operator). - FunctionProtoTypeLoc CallOpConvTL = + FunctionProtoTypeLoc CallOpConvTL = PtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>(); - FunctionProtoTypeLoc CallOpConvNameTL = + FunctionProtoTypeLoc CallOpConvNameTL = ConvNamePtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>(); - + // Wire up the FunctionProtoTypeLocs with the call operator's parameters. // These parameter's are essentially used to transform the name and // the type of the conversion operator. By using the same parameters // as the call operator's we don't have to fix any back references that - // the trailing return type of the call operator's uses (such as + // the trailing return type of the call operator's uses (such as // decltype(some_type<decltype(a)>::type{} + decltype(a){}) etc.) - // - we can simply use the return type of the call operator, and - // everything should work. + // - we can simply use the return type of the call operator, and + // everything should work. SmallVector<ParmVarDecl *, 4> InvokerParams; for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) { ParmVarDecl *From = CallOperator->getParamDecl(I); - InvokerParams.push_back(ParmVarDecl::Create(S.Context, + InvokerParams.push_back(ParmVarDecl::Create(S.Context, // Temporarily add to the TU. This is set to the invoker below. S.Context.getTranslationUnitDecl(), From->getLocStart(), @@ -1300,14 +1300,14 @@ static void addFunctionPointerConversion(Sema &S, CallOpConvNameTL.setParam(I, From); } - CXXConversionDecl *Conversion - = CXXConversionDecl::Create(S.Context, Class, Loc, - DeclarationNameInfo(ConversionName, + CXXConversionDecl *Conversion + = CXXConversionDecl::Create(S.Context, Class, Loc, + DeclarationNameInfo(ConversionName, Loc, ConvNameLoc), - ConvTy, + ConvTy, ConvTSI, /*isInline=*/true, /*isExplicit=*/false, - /*isConstexpr=*/S.getLangOpts().CPlusPlus17, + /*isConstexpr=*/S.getLangOpts().CPlusPlus17, CallOperator->getBody()->getLocEnd()); Conversion->setAccess(AS_public); Conversion->setImplicit(true); @@ -1315,7 +1315,7 @@ static void addFunctionPointerConversion(Sema &S, if (Class->isGenericLambda()) { // Create a template version of the conversion operator, using the template // parameter list of the function call operator. - FunctionTemplateDecl *TemplateCallOperator = + FunctionTemplateDecl *TemplateCallOperator = CallOperator->getDescribedFunctionTemplate(); FunctionTemplateDecl *ConversionTemplate = FunctionTemplateDecl::Create(S.Context, Class, @@ -1337,19 +1337,19 @@ static void addFunctionPointerConversion(Sema &S, // using FunctionTy & Loc and get its TypeLoc as a FunctionProtoTypeLoc // then rewire the parameters accordingly, by hoisting up the InvokeParams // loop below and then use its Params to set Invoke->setParams(...) below. - // This would avoid the 'const' qualifier of the calloperator from - // contaminating the type of the invoker, which is currently adjusted + // This would avoid the 'const' qualifier of the calloperator from + // contaminating the type of the invoker, which is currently adjusted // in SemaTemplateDeduction.cpp:DeduceTemplateArguments. Fixing the // trailing return type of the invoker would require a visitor to rebuild // the trailing return type and adjusting all back DeclRefExpr's to refer // to the new static invoker parameters - not the call operator's. CXXMethodDecl *Invoke - = CXXMethodDecl::Create(S.Context, Class, Loc, - DeclarationNameInfo(InvokerName, Loc), + = CXXMethodDecl::Create(S.Context, Class, Loc, + DeclarationNameInfo(InvokerName, Loc), InvokerFunctionTy, - CallOperator->getTypeSourceInfo(), + CallOperator->getTypeSourceInfo(), SC_Static, /*IsInline=*/true, - /*IsConstexpr=*/false, + /*IsConstexpr=*/false, CallOperator->getBody()->getLocEnd()); for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) InvokerParams[I]->setOwningFunction(Invoke); @@ -1357,7 +1357,7 @@ static void addFunctionPointerConversion(Sema &S, Invoke->setAccess(AS_private); Invoke->setImplicit(true); if (Class->isGenericLambda()) { - FunctionTemplateDecl *TemplateCallOperator = + FunctionTemplateDecl *TemplateCallOperator = CallOperator->getDescribedFunctionTemplate(); FunctionTemplateDecl *StaticInvokerTemplate = FunctionTemplateDecl::Create( S.Context, Class, Loc, InvokerName, @@ -1372,7 +1372,7 @@ static void addFunctionPointerConversion(Sema &S, } /// Add a lambda's conversion to block pointer. -static void addBlockPointerConversion(Sema &S, +static void addBlockPointerConversion(Sema &S, SourceRange IntroducerRange, CXXRecordDecl *Class, CXXMethodDecl *CallOperator) { @@ -1392,13 +1392,13 @@ static void addBlockPointerConversion(Sema &S, S.Context.getCanonicalType(BlockPtrTy)); DeclarationNameLoc NameLoc; NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc); - CXXConversionDecl *Conversion - = CXXConversionDecl::Create(S.Context, Class, Loc, + CXXConversionDecl *Conversion + = CXXConversionDecl::Create(S.Context, Class, Loc, DeclarationNameInfo(Name, Loc, NameLoc), - ConvTy, + ConvTy, S.Context.getTrivialTypeSourceInfo(ConvTy, Loc), /*isInline=*/true, /*isExplicit=*/false, - /*isConstexpr=*/false, + /*isConstexpr=*/false, CallOperator->getBody()->getLocEnd()); Conversion->setAccess(AS_public); Conversion->setImplicit(true); @@ -1421,7 +1421,7 @@ static ExprResult performLambdaVarCaptureInitialization(Sema &S, // direct-initialized in increasing subscript order.) These // initializations are performed in the (unspecified) order in // which the non-static data members are declared. - + // C++ [expr.prim.lambda]p12: // An entity captured by a lambda-expression is odr-used (3.2) in // the scope containing the lambda-expression. @@ -1437,8 +1437,8 @@ static ExprResult performLambdaVarCaptureInitialization(Sema &S, InitializationSequence Init(S, Entity, InitKind, Ref); return Init.Perform(S, Entity, InitKind, Ref); } - -ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body, + +ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body, Scope *CurScope) { LambdaScopeInfo LSI = *cast<LambdaScopeInfo>(FunctionScopes.back()); ActOnFinishFunctionBody(LSI.CallOperator, Body); @@ -1531,9 +1531,9 @@ ExprResult Sema::BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc, IsGenericLambda = Class->isGenericLambda(); CallOperator->setLexicalDeclContext(Class); - Decl *TemplateOrNonTemplateCallOperatorDecl = - CallOperator->getDescribedFunctionTemplate() - ? CallOperator->getDescribedFunctionTemplate() + Decl *TemplateOrNonTemplateCallOperatorDecl = + CallOperator->getDescribedFunctionTemplate() + ? CallOperator->getDescribedFunctionTemplate() : cast<Decl>(CallOperator); TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class); @@ -1646,7 +1646,7 @@ ExprResult Sema::BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc, // FIXME: Fix generic lambda to block conversions. if (getLangOpts().Blocks && getLangOpts().ObjC1 && !IsGenericLambda) addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator); - + // Finalize the lambda class. SmallVector<Decl*, 4> Fields(Class->fields()); ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(), @@ -1656,9 +1656,9 @@ ExprResult Sema::BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc, Cleanup.mergeFrom(LambdaCleanup); - LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange, + LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange, CaptureDefault, CaptureDefaultLoc, - Captures, + Captures, ExplicitParams, ExplicitResultType, CaptureInits, EndLoc, ContainsUnexpandedParameterPack); @@ -1718,7 +1718,7 @@ ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation, Expr *Src) { // Make sure that the lambda call operator is marked used. CXXRecordDecl *Lambda = Conv->getParent(); - CXXMethodDecl *CallOperator + CXXMethodDecl *CallOperator = cast<CXXMethodDecl>( Lambda->lookup( Context.DeclarationNames.getCXXOperatorName(OO_Call)).front()); @@ -1731,10 +1731,10 @@ ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation, CurrentLocation, Src); if (!Init.isInvalid()) Init = ActOnFinishFullExpr(Init.get()); - + if (Init.isInvalid()) return ExprError(); - + // Create the new block to be returned. BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation); diff --git a/lib/Sema/SemaLookup.cpp b/lib/Sema/SemaLookup.cpp index 2732112c00b6..0ab70e9dca37 100644 --- a/lib/Sema/SemaLookup.cpp +++ b/lib/Sema/SemaLookup.cpp @@ -1621,7 +1621,7 @@ bool Sema::isVisibleSlow(const NamedDecl *D) { bool Sema::shouldLinkPossiblyHiddenDecl(LookupResult &R, const NamedDecl *New) { // FIXME: If there are both visible and hidden declarations, we need to take // into account whether redeclaration is possible. Example: - // + // // Non-imported module: // int f(T); // #1 // Some TU: @@ -1795,7 +1795,7 @@ bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) { // actually exists in a Scope). while (S && !S->isDeclScope(D)) S = S->getParent(); - + // If the scope containing the declaration is the translation unit, // then we'll need to perform our checks based on the matching // DeclContexts rather than matching scopes. @@ -1806,7 +1806,7 @@ bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) { DeclContext *DC = nullptr; if (!S) DC = (*I)->getDeclContext()->getRedeclContext(); - + IdentifierResolver::iterator LastI = I; for (++LastI; LastI != IEnd; ++LastI) { if (S) { @@ -1815,7 +1815,7 @@ bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) { break; } else { // Match based on DeclContext. - DeclContext *LastDC + DeclContext *LastDC = (*LastI)->getDeclContext()->getRedeclContext(); if (!LastDC->Equals(DC)) break; @@ -1843,8 +1843,8 @@ bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) { if (AllowBuiltinCreation && LookupBuiltin(*this, R)) return true; - // If we didn't find a use of this identifier, the ExternalSource - // may be able to handle the situation. + // If we didn't find a use of this identifier, the ExternalSource + // may be able to handle the situation. // Note: some lookup failures are expected! // See e.g. R.isForRedeclaration(). return (ExternalSource && ExternalSource->LookupUnqualified(R, S)); @@ -2037,11 +2037,11 @@ bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool oldVal; DeclContext *Context; // Set flag in DeclContext informing debugger that we're looking for qualified name - QualifiedLookupInScope(DeclContext *ctx) : Context(ctx) { - oldVal = ctx->setUseQualifiedLookup(); + QualifiedLookupInScope(DeclContext *ctx) : Context(ctx) { + oldVal = ctx->setUseQualifiedLookup(); } - ~QualifiedLookupInScope() { - Context->setUseQualifiedLookup(oldVal); + ~QualifiedLookupInScope() { + Context->setUseQualifiedLookup(oldVal); } } QL(LookupCtx); @@ -2738,7 +2738,7 @@ addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) { case Type::DeducedTemplateSpecialization: break; - // If T is an Objective-C object or interface type, or a pointer to an + // If T is an Objective-C object or interface type, or a pointer to an // object or interface type, the associated namespace is the global // namespace. case Type::ObjCObject: @@ -4434,7 +4434,7 @@ static void AddKeywordsToConsumer(Sema &SemaRef, // Add type-specifier keywords to the set of results. static const char *const CTypeSpecs[] = { "char", "const", "double", "enum", "float", "int", "long", "short", - "signed", "struct", "union", "unsigned", "void", "volatile", + "signed", "struct", "union", "unsigned", "void", "volatile", "_Complex", "_Imaginary", // storage-specifiers as well "extern", "inline", "static", "typedef" @@ -4450,7 +4450,7 @@ static void AddKeywordsToConsumer(Sema &SemaRef, Consumer.addKeywordResult("bool"); else if (SemaRef.getLangOpts().C99) Consumer.addKeywordResult("_Bool"); - + if (SemaRef.getLangOpts().CPlusPlus) { Consumer.addKeywordResult("class"); Consumer.addKeywordResult("typename"); diff --git a/lib/Sema/SemaObjCProperty.cpp b/lib/Sema/SemaObjCProperty.cpp index 2983ec51f49e..3e55cf003fce 100644 --- a/lib/Sema/SemaObjCProperty.cpp +++ b/lib/Sema/SemaObjCProperty.cpp @@ -307,15 +307,15 @@ makePropertyAttributesAsWritten(unsigned Attributes) { attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_atomic; if (Attributes & ObjCDeclSpec::DQ_PR_class) attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_class; - + return (ObjCPropertyDecl::PropertyAttributeKind)attributesAsWritten; } -static bool LocPropertyAttribute( ASTContext &Context, const char *attrName, +static bool LocPropertyAttribute( ASTContext &Context, const char *attrName, SourceLocation LParenLoc, SourceLocation &Loc) { if (LParenLoc.isMacroID()) return false; - + SourceManager &SM = Context.getSourceManager(); std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(LParenLoc); // Try to load the file buffer. @@ -324,7 +324,7 @@ static bool LocPropertyAttribute( ASTContext &Context, const char *attrName, if (invalidTemp) return false; const char *tokenBegin = file.data() + locInfo.second; - + // Lex from the start of the given location. Lexer lexer(SM.getLocForStartOfFile(locInfo.first), Context.getLangOpts(), @@ -365,7 +365,7 @@ static void checkAtomicPropertyMismatch(Sema &S, if (Attrs & ObjCPropertyDecl::OBJC_PR_nonatomic) return false; // Was 'atomic' specified directly? - if (Property->getPropertyAttributesAsWritten() & + if (Property->getPropertyAttributesAsWritten() & ObjCPropertyDecl::OBJC_PR_atomic) return false; @@ -382,7 +382,7 @@ static void checkAtomicPropertyMismatch(Sema &S, Attrs = Attrs & ~AtomicityMask; if (OldIsAtomic) Attrs |= ObjCPropertyDecl::OBJC_PR_atomic; - else + else Attrs |= ObjCPropertyDecl::OBJC_PR_nonatomic; NewProperty->overwritePropertyAttributes(Attrs); @@ -429,7 +429,7 @@ Sema::HandlePropertyInClassExtension(Scope *S, DeclContext *DC = CurContext; IdentifierInfo *PropertyId = FD.D.getIdentifier(); ObjCInterfaceDecl *CCPrimary = CDecl->getClassInterface(); - + // We need to look in the @interface to see if the @property was // already declared. if (!CCPrimary) { @@ -445,7 +445,7 @@ Sema::HandlePropertyInClassExtension(Scope *S, ObjCPropertyDecl *PIDecl = CCPrimary->FindPropertyVisibleInPrimaryClass( PropertyId, ObjCPropertyDecl::getQueryKind(isClassProperty)); - // If we found a property in an extension, complain. + // If we found a property in an extension, complain. if (PIDecl && isa<ObjCCategoryDecl>(PIDecl->getDeclContext())) { Diag(AtLoc, diag::err_duplicate_property); Diag(PIDecl->getLocation(), diag::note_property_declare); @@ -482,7 +482,7 @@ Sema::HandlePropertyInClassExtension(Scope *S, << PIDecl->getGetterName() << GetterSel; Diag(PIDecl->getLocation(), diag::note_property_declare); } - + // Always adopt the getter from the original declaration. GetterSel = PIDecl->getGetterName(); Attributes |= ObjCDeclSpec::DQ_PR_getter; @@ -503,7 +503,7 @@ Sema::HandlePropertyInClassExtension(Scope *S, Attributes = (Attributes & ~OwnershipMask) | ExistingOwnership; } - // If the redeclaration is 'weak' but the original property is not, + // If the redeclaration is 'weak' but the original property is not, if ((Attributes & ObjCPropertyDecl::OBJC_PR_weak) && !(PIDecl->getPropertyAttributesAsWritten() & ObjCPropertyDecl::OBJC_PR_weak) && @@ -511,7 +511,7 @@ Sema::HandlePropertyInClassExtension(Scope *S, PIDecl->getType().getObjCLifetime() == Qualifiers::OCL_None) { Diag(AtLoc, diag::warn_property_implicitly_mismatched); Diag(PIDecl->getLocation(), diag::note_property_declare); - } + } } // Create a new ObjCPropertyDecl with the DeclContext being @@ -546,13 +546,13 @@ Sema::HandlePropertyInClassExtension(Scope *S, (!isObjCPointerConversion(ClassExtPropertyT, PrimaryClassPropertyT, ConvertedType, IncompatibleObjC)) || IncompatibleObjC) { - Diag(AtLoc, + Diag(AtLoc, diag::err_type_mismatch_continuation_class) << PDecl->getType(); Diag(PIDecl->getLocation(), diag::note_property_declare); return nullptr; } } - + // Check that atomicity of property in class extension matches the previous // declaration. checkAtomicPropertyMismatch(*this, PIDecl, PDecl, true); @@ -621,7 +621,7 @@ ObjCPropertyDecl *Sema::CreatePropertyDecl(Scope *S, DeclContext *DC = CDecl; ObjCPropertyDecl *PDecl = ObjCPropertyDecl::Create(Context, DC, FD.D.getIdentifierLoc(), - PropertyId, AtLoc, + PropertyId, AtLoc, LParenLoc, T, TInfo); bool isClassProperty = (AttributesAsWritten & ObjCDeclSpec::DQ_PR_class) || @@ -770,7 +770,7 @@ static void checkARCPropertyImpl(Sema &S, SourceLocation propertyImplLoc, S.Diag(ivar->getLocation(), diag::err_arc_assign_property_ownership) << property->getDeclName() << ivar->getDeclName() - << ((property->getPropertyAttributesAsWritten() + << ((property->getPropertyAttributesAsWritten() & ObjCPropertyDecl::OBJC_PR_assign) != 0); break; @@ -794,12 +794,12 @@ static void checkARCPropertyImpl(Sema &S, SourceLocation propertyImplLoc, /// life-time is assumed 'strong'. static void setImpliedPropertyAttributeForReadOnlyProperty( ObjCPropertyDecl *property, ObjCIvarDecl *ivar) { - Qualifiers::ObjCLifetime propertyLifetime = + Qualifiers::ObjCLifetime propertyLifetime = getImpliedARCOwnership(property->getPropertyAttributes(), property->getType()); if (propertyLifetime != Qualifiers::OCL_None) return; - + if (!ivar) { // if no backing ivar, make property 'strong'. property->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_strong); @@ -1094,7 +1094,7 @@ Decl *Sema::ActOnPropertyImplDecl(Scope *S, Diag(IC->getLocation(), diag::warn_auto_implicit_atomic_property); Diag(property->getLocation(), diag::note_property_declare); } - + if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(property->getDeclContext())) { if (!CD->IsClassExtension()) { @@ -1121,17 +1121,17 @@ Decl *Sema::ActOnPropertyImplDecl(Scope *S, } } } - + if (!ReadWriteProperty) { Diag(property->getLocation(), diag::warn_auto_readonly_iboutlet_property) << property; SourceLocation readonlyLoc; - if (LocPropertyAttribute(Context, "readonly", + if (LocPropertyAttribute(Context, "readonly", property->getLParenLoc(), readonlyLoc)) { - SourceLocation endLoc = + SourceLocation endLoc = readonlyLoc.getLocWithOffset(strlen("readonly")-1); SourceRange ReadonlySourceRange(readonlyLoc, endLoc); - Diag(property->getLocation(), + Diag(property->getLocation(), diag::note_auto_readonly_iboutlet_fixup_suggest) << FixItHint::CreateReplacement(ReadonlySourceRange, "readwrite"); } @@ -1194,10 +1194,10 @@ Decl *Sema::ActOnPropertyImplDecl(Scope *S, (property->getPropertyAttributesAsWritten() & ObjCPropertyDecl::OBJC_PR_readonly) && PropertyIvarType->isObjCRetainableType()) { - setImpliedPropertyAttributeForReadOnlyProperty(property, Ivar); + setImpliedPropertyAttributeForReadOnlyProperty(property, Ivar); } - - ObjCPropertyDecl::PropertyAttributeKind kind + + ObjCPropertyDecl::PropertyAttributeKind kind = property->getPropertyAttributes(); bool isARCWeak = false; @@ -1244,16 +1244,16 @@ Decl *Sema::ActOnPropertyImplDecl(Scope *S, } if (AtLoc.isInvalid()) { - // Check when default synthesizing a property that there is + // Check when default synthesizing a property that there is // an ivar matching property name and issue warning; since this // is the most common case of not using an ivar used for backing // property in non-default synthesis case. ObjCInterfaceDecl *ClassDeclared=nullptr; - ObjCIvarDecl *originalIvar = - IDecl->lookupInstanceVariable(property->getIdentifier(), + ObjCIvarDecl *originalIvar = + IDecl->lookupInstanceVariable(property->getIdentifier(), ClassDeclared); if (originalIvar) { - Diag(PropertyDiagLoc, + Diag(PropertyDiagLoc, diag::warn_autosynthesis_property_ivar_match) << PropertyId << (Ivar == nullptr) << PropertyIvar << originalIvar->getIdentifier(); @@ -1261,7 +1261,7 @@ Decl *Sema::ActOnPropertyImplDecl(Scope *S, Diag(originalIvar->getLocation(), diag::note_ivar_decl); } } - + if (!Ivar) { // In ARC, give the ivar a lifetime qualifier based on the // property attributes. @@ -1280,10 +1280,10 @@ Decl *Sema::ActOnPropertyImplDecl(Scope *S, Qualifiers::ObjCLifetime lifetime = getImpliedARCOwnership(kind, PropertyIvarType); assert(lifetime && "no lifetime for property?"); - + Qualifiers qs; qs.addObjCLifetime(lifetime); - PropertyIvarType = Context.getQualifiedType(PropertyIvarType, qs); + PropertyIvarType = Context.getQualifiedType(PropertyIvarType, qs); } } @@ -1333,7 +1333,7 @@ Decl *Sema::ActOnPropertyImplDecl(Scope *S, // Check that type of property and its ivar are type compatible. if (!Context.hasSameType(PropertyIvarType, IvarType)) { - if (isa<ObjCObjectPointerType>(PropertyIvarType) + if (isa<ObjCObjectPointerType>(PropertyIvarType) && isa<ObjCObjectPointerType>(IvarType)) compat = Context.canAssignObjCInterfaces( @@ -1390,7 +1390,7 @@ Decl *Sema::ActOnPropertyImplDecl(Scope *S, } else if (PropertyIvar) // @dynamic Diag(PropertyDiagLoc, diag::err_dynamic_property_ivar_decl); - + assert (property && "ActOnPropertyImplDecl - property declaration missing"); ObjCPropertyImplDecl *PIDecl = ObjCPropertyImplDecl::Create(Context, CurContext, AtLoc, PropertyLoc, @@ -1412,7 +1412,7 @@ Decl *Sema::ActOnPropertyImplDecl(Scope *S, // FIXME. Eventually we want to do this for Objective-C as well. SynthesizedFunctionScope Scope(*this, getterMethod); ImplicitParamDecl *SelfDecl = getterMethod->getSelfDecl(); - DeclRefExpr *SelfExpr = + DeclRefExpr *SelfExpr = new (Context) DeclRefExpr(SelfDecl, false, SelfDecl->getType(), VK_LValue, PropertyDiagLoc); MarkDeclRefReferenced(SelfExpr); @@ -1440,7 +1440,7 @@ Decl *Sema::ActOnPropertyImplDecl(Scope *S, } if (property->hasAttr<NSReturnsNotRetainedAttr>() && !getterMethod->hasAttr<NSReturnsNotRetainedAttr>()) { - Diag(getterMethod->getLocation(), + Diag(getterMethod->getLocation(), diag::warn_property_getter_owning_mismatch); Diag(property->getLocation(), diag::note_property_declare); } @@ -1464,7 +1464,7 @@ Decl *Sema::ActOnPropertyImplDecl(Scope *S, // FIXME. Eventually we want to do this for Objective-C as well. SynthesizedFunctionScope Scope(*this, setterMethod); ImplicitParamDecl *SelfDecl = setterMethod->getSelfDecl(); - DeclRefExpr *SelfExpr = + DeclRefExpr *SelfExpr = new (Context) DeclRefExpr(SelfDecl, false, SelfDecl->getType(), VK_LValue, PropertyDiagLoc); MarkDeclRefReferenced(SelfExpr); @@ -1484,27 +1484,27 @@ Decl *Sema::ActOnPropertyImplDecl(Scope *S, DeclRefExpr *rhs = new (Context) DeclRefExpr(Param, false, T, VK_LValue, PropertyDiagLoc); MarkDeclRefReferenced(rhs); - ExprResult Res = BuildBinOp(S, PropertyDiagLoc, + ExprResult Res = BuildBinOp(S, PropertyDiagLoc, BO_Assign, lhs, rhs); - if (property->getPropertyAttributes() & + if (property->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic) { Expr *callExpr = Res.getAs<Expr>(); - if (const CXXOperatorCallExpr *CXXCE = + if (const CXXOperatorCallExpr *CXXCE = dyn_cast_or_null<CXXOperatorCallExpr>(callExpr)) if (const FunctionDecl *FuncDecl = CXXCE->getDirectCallee()) if (!FuncDecl->isTrivial()) if (property->getType()->isReferenceType()) { - Diag(PropertyDiagLoc, + Diag(PropertyDiagLoc, diag::err_atomic_property_nontrivial_assign_op) << property->getType(); - Diag(FuncDecl->getLocStart(), + Diag(FuncDecl->getLocStart(), diag::note_callee_decl) << FuncDecl; } } PIDecl->setSetterCXXAssignment(Res.getAs<Expr>()); } } - + if (IC) { if (Synthesize) if (ObjCPropertyImplDecl *PPIDecl = @@ -1537,9 +1537,9 @@ Decl *Sema::ActOnPropertyImplDecl(Scope *S, Ivar = IDecl->lookupInstanceVariable(PropertyId, ClassDeclared); } // Issue diagnostics only if Ivar belongs to current class. - if (Ivar && Ivar->getSynthesize() && + if (Ivar && Ivar->getSynthesize() && declaresSameEntity(IC->getClassInterface(), ClassDeclared)) { - Diag(Ivar->getLocation(), diag::err_undeclared_var_use) + Diag(Ivar->getLocation(), diag::err_undeclared_var_use) << PropertyId; Ivar->setInvalidDecl(); } @@ -1582,7 +1582,7 @@ Sema::DiagnosePropertyMismatch(ObjCPropertyDecl *Property, Property->getPropertyAttributes(); ObjCPropertyDecl::PropertyAttributeKind SAttr = SuperProperty->getPropertyAttributes(); - + // We allow readonly properties without an explicit ownership // (assign/unsafe_unretained/weak/retain/strong/copy) in super class // to be overridden by a property with any explicit ownership in the subclass. @@ -1642,7 +1642,7 @@ Sema::DiagnosePropertyMismatch(ObjCPropertyDecl *Property, // FIXME. For future support of covariant property types, revisit this. bool IncompatibleObjC = false; QualType ConvertedType; - if (!isObjCPointerConversion(RHSType, LHSType, + if (!isObjCPointerConversion(RHSType, LHSType, ConvertedType, IncompatibleObjC) || IncompatibleObjC) { Diag(Property->getLocation(), diag::warn_property_types_are_incompatible) @@ -1683,7 +1683,7 @@ bool Sema::DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *property, compat = false; } } - + if (!compat) { Diag(Loc, diag::warn_accessor_property_type_mismatch) << property->getDeclName() @@ -1744,9 +1744,9 @@ CollectImmediateProperties(ObjCContainerDecl *CDecl, ObjCPropertyDecl *PropertyFromSuper = SuperPropMap[std::make_pair(Prop->getIdentifier(), Prop->isClassProperty())]; - // Exclude property for protocols which conform to class's super-class, + // Exclude property for protocols which conform to class's super-class, // as super-class has to implement the property. - if (!PropertyFromSuper || + if (!PropertyFromSuper || PropertyFromSuper->getIdentifier() != Prop->getIdentifier()) { ObjCPropertyDecl *&PropEntry = PropMap[std::make_pair(Prop->getIdentifier(), @@ -1788,7 +1788,7 @@ Sema::IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace, Method->isInstanceMethod()); if (!IMD || !IMD->isPropertyAccessor()) return false; - + // look up a property declaration whose one of its accessors is implemented // by this method. for (const auto *Property : IFace->instance_properties()) { @@ -1841,7 +1841,7 @@ void Sema::DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl, return; ObjCInterfaceDecl::PropertyMap SuperPropMap; CollectSuperClassPropertyImplementations(IDecl, SuperPropMap); - + for (unsigned i = 0, e = PropertyOrder.size(); i != e; i++) { ObjCPropertyDecl *Prop = PropertyOrder[i]; // Is there a matching property synthesize/dynamic? @@ -1997,7 +1997,7 @@ void Sema::DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl, } if (IDecl) CollectSuperClassPropertyImplementations(IDecl, NoNeedToImplPropMap); - + // When SynthesizeProperties is true, we only check class properties. CollectImmediateProperties(CDecl, PropMap, NoNeedToImplPropMap, SynthesizeProperties/*CollectClassPropsOnly*/); @@ -2048,7 +2048,7 @@ void Sema::DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl, // Collect property accessors implemented in current implementation. for (const auto *I : IMPDecl->methods()) InsMap.insert(I); - + ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl); ObjCInterfaceDecl *PrimaryClass = nullptr; if (C && !C->IsClassExtension()) @@ -2121,7 +2121,7 @@ Sema::AtomicPropertySetterGetterRules (ObjCImplDecl* IMPDecl, for (const auto *Ext : IDecl->known_extensions()) for (auto *Prop : Ext->properties()) PM[std::make_pair(Prop->getIdentifier(), Prop->isClassProperty())] = Prop; - + for (ObjCContainerDecl::PropertyMap::iterator I = PM.begin(), E = PM.end(); I != E; ++I) { const ObjCPropertyDecl *Property = I->second; @@ -2191,7 +2191,7 @@ Sema::AtomicPropertySetterGetterRules (ObjCImplDecl* IMPDecl, << FixItHint::CreateInsertion(AfterLParen, NonatomicStr); } else if (Property->getLParenLoc().isInvalid()) { //@property id etc. - SourceLocation startLoc = + SourceLocation startLoc = Property->getTypeSourceInfo()->getTypeLoc().getBeginLoc(); Diag(Property->getLocation(), diag::note_atomic_property_fixup_suggest) @@ -2301,8 +2301,8 @@ static void AddPropertyAttrs(Sema &S, ObjCMethodDecl *PropertyMethod, ObjCPropertyDecl *Property) { // Should we just clone all attributes over? for (const auto *A : Property->attrs()) { - if (isa<DeprecatedAttr>(A) || - isa<UnavailableAttr>(A) || + if (isa<DeprecatedAttr>(A) || + isa<UnavailableAttr>(A) || isa<AvailabilityAttr>(A)) PropertyMethod->addAttr(A->clone(S.Context)); } @@ -2332,7 +2332,7 @@ void Sema::ProcessPropertyDecl(ObjCPropertyDecl *property) { getClassMethod(property->getGetterName()) : CatDecl->getClassInterface()-> getInstanceMethod(property->getGetterName()); - + SetterMethod = IsClassProperty ? CD->getClassMethod(property->getSetterName()) : CD->getInstanceMethod(property->getSetterName()); @@ -2352,7 +2352,7 @@ void Sema::ProcessPropertyDecl(ObjCPropertyDecl *property) { Diag(SetterMethod->getLocation(), diag::err_setter_type_void); if (SetterMethod->param_size() != 1 || !Context.hasSameUnqualifiedType( - (*SetterMethod->param_begin())->getType().getNonReferenceType(), + (*SetterMethod->param_begin())->getType().getNonReferenceType(), property->getType().getNonReferenceType())) { Diag(property->getLocation(), diag::warn_accessor_property_type_mismatch) @@ -2406,11 +2406,11 @@ void Sema::ProcessPropertyDecl(ObjCPropertyDecl *property) { if (property->hasAttr<NSReturnsNotRetainedAttr>()) GetterMethod->addAttr(NSReturnsNotRetainedAttr::CreateImplicit(Context, Loc)); - + if (property->hasAttr<ObjCReturnsInnerPointerAttr>()) GetterMethod->addAttr( ObjCReturnsInnerPointerAttr::CreateImplicit(Context, Loc)); - + if (const SectionAttr *SA = property->getAttr<SectionAttr>()) GetterMethod->addAttr( SectionAttr::CreateImplicit(Context, SectionAttr::GNU_section, @@ -2535,12 +2535,12 @@ void Sema::CheckObjCPropertyAttributes(Decl *PDecl, // FIXME: Improve the reported location. if (!PDecl || PDecl->isInvalidDecl()) return; - + if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) && (Attributes & ObjCDeclSpec::DQ_PR_readwrite)) Diag(Loc, diag::err_objc_property_attr_mutually_exclusive) << "readonly" << "readwrite"; - + ObjCPropertyDecl *PropertyDecl = cast<ObjCPropertyDecl>(PDecl); QualType PropertyTy = PropertyDecl->getType(); @@ -2656,19 +2656,19 @@ void Sema::CheckObjCPropertyAttributes(Decl *PDecl, if (Attributes & ObjCDeclSpec::DQ_PR_readonly) { // do nothing } else if (getLangOpts().ObjCAutoRefCount) { - // With arc, @property definitions should default to strong when + // With arc, @property definitions should default to strong when // not specified. PropertyDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_strong); } else if (PropertyTy->isObjCObjectPointerType()) { - bool isAnyClassTy = - (PropertyTy->isObjCClassType() || + bool isAnyClassTy = + (PropertyTy->isObjCClassType() || PropertyTy->isObjCQualifiedClassType()); // In non-gc, non-arc mode, 'Class' is treated as a 'void *' no need to // issue any warning. if (isAnyClassTy && getLangOpts().getGC() == LangOptions::NonGC) ; else if (propertyInPrimaryClass) { - // Don't issue warning on property with no life time in class + // Don't issue warning on property with no life time in class // extension as it is inherited from property in primary class. // Skip this warning in gc-only mode. if (getLangOpts().getGC() != LangOptions::GCOnly) @@ -2696,7 +2696,7 @@ void Sema::CheckObjCPropertyAttributes(Decl *PDecl, !(Attributes & ObjCDeclSpec::DQ_PR_strong) && PropertyTy->isBlockPointerType()) Diag(Loc, diag::warn_objc_property_retain_of_block); - + if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) && (Attributes & ObjCDeclSpec::DQ_PR_setter)) Diag(Loc, diag::warn_objc_readonly_property_has_setter); diff --git a/lib/Sema/SemaPseudoObject.cpp b/lib/Sema/SemaPseudoObject.cpp index 4484e9b3513b..a8af75d87c8d 100644 --- a/lib/Sema/SemaPseudoObject.cpp +++ b/lib/Sema/SemaPseudoObject.cpp @@ -316,10 +316,10 @@ namespace { OpaqueValueExpr *InstanceKey; ObjCMethodDecl *AtIndexGetter; Selector AtIndexGetterSelector; - + ObjCMethodDecl *AtIndexSetter; Selector AtIndexSetterSelector; - + public: ObjCSubscriptOpBuilder(Sema &S, ObjCSubscriptRefExpr *refExpr, bool IsUnique) : PseudoOpBuilder(S, refExpr->getSourceRange().getBegin(), IsUnique), @@ -367,7 +367,7 @@ namespace { /// Capture the given expression in an OpaqueValueExpr. OpaqueValueExpr *PseudoOpBuilder::capture(Expr *e) { // Make a new OVE whose source is the given expression. - OpaqueValueExpr *captured = + OpaqueValueExpr *captured = new (S.Context) OpaqueValueExpr(GenericLoc, e->getType(), e->getValueKind(), e->getObjectKind(), e); @@ -389,7 +389,7 @@ OpaqueValueExpr *PseudoOpBuilder::captureValueAsResult(Expr *e) { assert(ResultIndex == PseudoObjectExpr::NoResult); // If the expression hasn't already been captured, just capture it - // and set the new semantic + // and set the new semantic if (!isa<OpaqueValueExpr>(e)) { OpaqueValueExpr *cap = capture(e); setResultToLastSemantic(); @@ -618,11 +618,11 @@ bool ObjCPropertyOpBuilder::findGetter() { // Must build the getter selector the hard way. ObjCMethodDecl *setter = RefExpr->getImplicitPropertySetter(); assert(setter && "both setter and getter are null - cannot happen"); - IdentifierInfo *setterName = + IdentifierInfo *setterName = setter->getSelector().getIdentifierInfoForSlot(0); IdentifierInfo *getterName = &S.Context.Idents.get(setterName->getName().substr(3)); - GetterSelector = + GetterSelector = S.PP.getSelectorTable().getNullarySelector(getterName); return false; } @@ -636,7 +636,7 @@ bool ObjCPropertyOpBuilder::findGetter() { /// Try to find the most accurate setter declaration for the property /// reference. /// -/// \return true if a setter was found, in which case Setter +/// \return true if a setter was found, in which case Setter bool ObjCPropertyOpBuilder::findSetter(bool warn) { // For implicit properties, just trust the lookup we already did. if (RefExpr->isImplicitProperty()) { @@ -987,9 +987,9 @@ ExprResult ObjCPropertyOpBuilder::complete(Expr *SyntacticForm) { // ObjCSubscript build stuff. // -/// objective-c subscripting-specific behavior for doing lvalue-to-rvalue +/// objective-c subscripting-specific behavior for doing lvalue-to-rvalue /// conversion. -/// FIXME. Remove this routine if it is proven that no additional +/// FIXME. Remove this routine if it is proven that no additional /// specifity is needed. ExprResult ObjCSubscriptOpBuilder::buildRValueOperation(Expr *op) { ExprResult result = PseudoOpBuilder::buildRValueOperation(op); @@ -1007,21 +1007,21 @@ ObjCSubscriptOpBuilder::buildAssignmentOperation(Scope *Sc, // There must be a method to do the Index'ed assignment. if (!findAtIndexSetter()) return ExprError(); - + // Verify that we can do a compound assignment. if (opcode != BO_Assign && !findAtIndexGetter()) return ExprError(); - + ExprResult result = PseudoOpBuilder::buildAssignmentOperation(Sc, opcLoc, opcode, LHS, RHS); if (result.isInvalid()) return ExprError(); - + // Various warnings about objc Index'ed assignments in ARC. if (S.getLangOpts().ObjCAutoRefCount && InstanceBase) { S.checkRetainCycles(InstanceBase->getSourceExpr(), RHS); S.checkUnsafeExprAssigns(opcLoc, LHS, RHS); } - + return result; } @@ -1049,15 +1049,15 @@ Expr *ObjCSubscriptOpBuilder::rebuildAndCaptureObject(Expr *syntacticBase) { return syntacticBase; } -/// CheckSubscriptingKind - This routine decide what type +/// CheckSubscriptingKind - This routine decide what type /// of indexing represented by "FromE" is being done. -Sema::ObjCSubscriptKind +Sema::ObjCSubscriptKind Sema::CheckSubscriptingKind(Expr *FromE) { // If the expression already has integral or enumeration type, we're golden. QualType T = FromE->getType(); if (T->isIntegralOrEnumerationType()) return OS_Array; - + // If we don't have a class type in C++, there's no way we can get an // expression of integral or enumeration type. const RecordType *RecordTy = T->getAs<RecordType>(); @@ -1066,7 +1066,7 @@ Sema::ObjCSubscriptKind // All other scalar cases are assumed to be dictionary indexing which // caller handles, with diagnostics if needed. return OS_Dictionary; - if (!getLangOpts().CPlusPlus || + if (!getLangOpts().CPlusPlus || !RecordTy || RecordTy->isIncompleteType()) { // No indexing can be done. Issue diagnostics and quit. const Expr *IndexExpr = FromE->IgnoreParenImpCasts(); @@ -1078,12 +1078,12 @@ Sema::ObjCSubscriptKind << T; return OS_Error; } - + // We must have a complete class type. - if (RequireCompleteType(FromE->getExprLoc(), T, + if (RequireCompleteType(FromE->getExprLoc(), T, diag::err_objc_index_incomplete_class_type, FromE)) return OS_Error; - + // Look for a conversion to an integral, enumeration type, or // objective-C pointer type. int NoIntegrals=0, NoObjCIdPointers=0; @@ -1125,17 +1125,17 @@ Sema::ObjCSubscriptKind /// CheckKeyForObjCARCConversion - This routine suggests bridge casting of CF /// objects used as dictionary subscript key objects. -static void CheckKeyForObjCARCConversion(Sema &S, QualType ContainerT, +static void CheckKeyForObjCARCConversion(Sema &S, QualType ContainerT, Expr *Key) { if (ContainerT.isNull()) return; // dictionary subscripting. // - (id)objectForKeyedSubscript:(id)key; IdentifierInfo *KeyIdents[] = { - &S.Context.Idents.get("objectForKeyedSubscript") + &S.Context.Idents.get("objectForKeyedSubscript") }; Selector GetterSelector = S.Context.Selectors.getSelector(1, KeyIdents); - ObjCMethodDecl *Getter = S.LookupMethodInObjectType(GetterSelector, ContainerT, + ObjCMethodDecl *Getter = S.LookupMethodInObjectType(GetterSelector, ContainerT, true /*instance*/); if (!Getter) return; @@ -1147,25 +1147,25 @@ static void CheckKeyForObjCARCConversion(Sema &S, QualType ContainerT, bool ObjCSubscriptOpBuilder::findAtIndexGetter() { if (AtIndexGetter) return true; - + Expr *BaseExpr = RefExpr->getBaseExpr(); QualType BaseT = BaseExpr->getType(); - + QualType ResultType; if (const ObjCObjectPointerType *PTy = BaseT->getAs<ObjCObjectPointerType>()) { ResultType = PTy->getPointeeType(); } - Sema::ObjCSubscriptKind Res = + Sema::ObjCSubscriptKind Res = S.CheckSubscriptingKind(RefExpr->getKeyExpr()); if (Res == Sema::OS_Error) { if (S.getLangOpts().ObjCAutoRefCount) - CheckKeyForObjCARCConversion(S, ResultType, + CheckKeyForObjCARCConversion(S, ResultType, RefExpr->getKeyExpr()); return false; } bool arrayRef = (Res == Sema::OS_Array); - + if (ResultType.isNull()) { S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_base_type) << BaseExpr->getType() << arrayRef; @@ -1175,24 +1175,24 @@ bool ObjCSubscriptOpBuilder::findAtIndexGetter() { // dictionary subscripting. // - (id)objectForKeyedSubscript:(id)key; IdentifierInfo *KeyIdents[] = { - &S.Context.Idents.get("objectForKeyedSubscript") + &S.Context.Idents.get("objectForKeyedSubscript") }; AtIndexGetterSelector = S.Context.Selectors.getSelector(1, KeyIdents); } else { // - (id)objectAtIndexedSubscript:(size_t)index; IdentifierInfo *KeyIdents[] = { - &S.Context.Idents.get("objectAtIndexedSubscript") + &S.Context.Idents.get("objectAtIndexedSubscript") }; - + AtIndexGetterSelector = S.Context.Selectors.getSelector(1, KeyIdents); } - - AtIndexGetter = S.LookupMethodInObjectType(AtIndexGetterSelector, ResultType, + + AtIndexGetter = S.LookupMethodInObjectType(AtIndexGetterSelector, ResultType, true /*instance*/); - + if (!AtIndexGetter && S.getLangOpts().DebuggerObjCLiteral) { - AtIndexGetter = ObjCMethodDecl::Create(S.Context, SourceLocation(), + AtIndexGetter = ObjCMethodDecl::Create(S.Context, SourceLocation(), SourceLocation(), AtIndexGetterSelector, S.Context.getObjCIdType() /*ReturnType*/, nullptr /*TypeSourceInfo */, @@ -1220,20 +1220,20 @@ bool ObjCSubscriptOpBuilder::findAtIndexGetter() { << BaseExpr->getType() << 0 << arrayRef; return false; } - AtIndexGetter = - S.LookupInstanceMethodInGlobalPool(AtIndexGetterSelector, - RefExpr->getSourceRange(), + AtIndexGetter = + S.LookupInstanceMethodInGlobalPool(AtIndexGetterSelector, + RefExpr->getSourceRange(), true); } - + if (AtIndexGetter) { QualType T = AtIndexGetter->parameters()[0]->getType(); if ((arrayRef && !T->isIntegralOrEnumerationType()) || (!arrayRef && !T->isObjCObjectPointerType())) { - S.Diag(RefExpr->getKeyExpr()->getExprLoc(), + S.Diag(RefExpr->getKeyExpr()->getExprLoc(), arrayRef ? diag::err_objc_subscript_index_type : diag::err_objc_subscript_key_type) << T; - S.Diag(AtIndexGetter->parameters()[0]->getLocation(), + S.Diag(AtIndexGetter->parameters()[0]->getLocation(), diag::note_parameter_type) << T; return false; } @@ -1251,32 +1251,32 @@ bool ObjCSubscriptOpBuilder::findAtIndexGetter() { bool ObjCSubscriptOpBuilder::findAtIndexSetter() { if (AtIndexSetter) return true; - + Expr *BaseExpr = RefExpr->getBaseExpr(); QualType BaseT = BaseExpr->getType(); - + QualType ResultType; if (const ObjCObjectPointerType *PTy = BaseT->getAs<ObjCObjectPointerType>()) { ResultType = PTy->getPointeeType(); } - - Sema::ObjCSubscriptKind Res = + + Sema::ObjCSubscriptKind Res = S.CheckSubscriptingKind(RefExpr->getKeyExpr()); if (Res == Sema::OS_Error) { if (S.getLangOpts().ObjCAutoRefCount) - CheckKeyForObjCARCConversion(S, ResultType, + CheckKeyForObjCARCConversion(S, ResultType, RefExpr->getKeyExpr()); return false; } bool arrayRef = (Res == Sema::OS_Array); - + if (ResultType.isNull()) { S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_base_type) << BaseExpr->getType() << arrayRef; return false; } - + if (!arrayRef) { // dictionary subscripting. // - (void)setObject:(id)object forKeyedSubscript:(id)key; @@ -1294,7 +1294,7 @@ bool ObjCSubscriptOpBuilder::findAtIndexSetter() { }; AtIndexSetterSelector = S.Context.Selectors.getSelector(2, KeyIdents); } - AtIndexSetter = S.LookupMethodInObjectType(AtIndexSetterSelector, ResultType, + AtIndexSetter = S.LookupMethodInObjectType(AtIndexSetterSelector, ResultType, true /*instance*/); if (!AtIndexSetter && S.getLangOpts().DebuggerObjCLiteral) { @@ -1328,35 +1328,35 @@ bool ObjCSubscriptOpBuilder::findAtIndexSetter() { Params.push_back(key); AtIndexSetter->setMethodParams(S.Context, Params, None); } - + if (!AtIndexSetter) { if (!BaseT->isObjCIdType()) { - S.Diag(BaseExpr->getExprLoc(), + S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_method_not_found) << BaseExpr->getType() << 1 << arrayRef; return false; } - AtIndexSetter = - S.LookupInstanceMethodInGlobalPool(AtIndexSetterSelector, - RefExpr->getSourceRange(), + AtIndexSetter = + S.LookupInstanceMethodInGlobalPool(AtIndexSetterSelector, + RefExpr->getSourceRange(), true); } - + bool err = false; if (AtIndexSetter && arrayRef) { QualType T = AtIndexSetter->parameters()[1]->getType(); if (!T->isIntegralOrEnumerationType()) { - S.Diag(RefExpr->getKeyExpr()->getExprLoc(), + S.Diag(RefExpr->getKeyExpr()->getExprLoc(), diag::err_objc_subscript_index_type) << T; - S.Diag(AtIndexSetter->parameters()[1]->getLocation(), + S.Diag(AtIndexSetter->parameters()[1]->getLocation(), diag::note_parameter_type) << T; err = true; } T = AtIndexSetter->parameters()[0]->getType(); if (!T->isObjCObjectPointerType()) { - S.Diag(RefExpr->getBaseExpr()->getExprLoc(), + S.Diag(RefExpr->getBaseExpr()->getExprLoc(), diag::err_objc_subscript_object_type) << T << arrayRef; - S.Diag(AtIndexSetter->parameters()[0]->getLocation(), + S.Diag(AtIndexSetter->parameters()[0]->getLocation(), diag::note_parameter_type) << T; err = true; } @@ -1371,7 +1371,7 @@ bool ObjCSubscriptOpBuilder::findAtIndexSetter() { else S.Diag(RefExpr->getBaseExpr()->getExprLoc(), diag::err_objc_subscript_dic_object_type) << T; - S.Diag(AtIndexSetter->parameters()[i]->getLocation(), + S.Diag(AtIndexSetter->parameters()[i]->getLocation(), diag::note_parameter_type) << T; err = true; } @@ -1385,13 +1385,13 @@ bool ObjCSubscriptOpBuilder::findAtIndexSetter() { ExprResult ObjCSubscriptOpBuilder::buildGet() { if (!findAtIndexGetter()) return ExprError(); - + QualType receiverType = InstanceBase->getType(); - + // Build a message-send. ExprResult msg; Expr *Index = InstanceKey; - + // Arguments. Expr *args[] = { Index }; assert(InstanceBase); @@ -1417,17 +1417,17 @@ ExprResult ObjCSubscriptOpBuilder::buildSet(Expr *op, SourceLocation opcLoc, S.DiagnoseUseOfDecl(AtIndexSetter, GenericLoc); QualType receiverType = InstanceBase->getType(); Expr *Index = InstanceKey; - + // Arguments. Expr *args[] = { op, Index }; - + // Build a message-send. ExprResult msg = S.BuildInstanceMessageImplicit(InstanceBase, receiverType, GenericLoc, AtIndexSetterSelector, AtIndexSetter, MultiExprArg(args, 2)); - + if (!msg.isInvalid() && captureSetValueAsResult) { ObjCMessageExpr *msgExpr = cast<ObjCMessageExpr>(msg.get()->IgnoreImplicit()); @@ -1435,7 +1435,7 @@ ExprResult ObjCSubscriptOpBuilder::buildSet(Expr *op, SourceLocation opcLoc, if (CanCaptureValue(arg)) msgExpr->setArg(0, captureValueAsResult(arg)); } - + return msg; } diff --git a/lib/Sema/SemaStmt.cpp b/lib/Sema/SemaStmt.cpp index b2f9783d44f1..377e2c4dfa23 100644 --- a/lib/Sema/SemaStmt.cpp +++ b/lib/Sema/SemaStmt.cpp @@ -216,7 +216,7 @@ void Sema::DiagnoseUnusedExprResult(const Stmt *S) { // expression is a call to a function with the warn_unused_result attribute, // we warn no matter the location. Because of the order in which the various // checks need to happen, we factor out the macro-related test here. - bool ShouldSuppress = + bool ShouldSuppress = SourceMgr.isMacroBodyExpansion(ExprLoc) || SourceMgr.isInSystemMacro(ExprLoc); @@ -1879,7 +1879,7 @@ Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc, VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl()); if (!D || D->isInvalidDecl()) return StmtError(); - + FirstType = D->getType(); // C99 6.8.5p3: The declaration part of a 'for' statement shall only // declare identifiers for objects having storage class 'auto' or @@ -2373,7 +2373,7 @@ Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation CoawaitLoc, // Rather, we need to determine what it was when the array was first // created - so we resort to using sizeof(vla)/sizeof(element). // For e.g. - // void f(int b) { + // void f(int b) { // int vla[b]; // b = -1; <-- This should not affect the num of iterations below // for (int &c : vla) { .. } @@ -2399,7 +2399,7 @@ Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation CoawaitLoc, EndVar->getSourceRange()); if (SizeOfVLAExprR.isInvalid()) return StmtError(); - + ExprResult SizeOfEachElementExprR = ActOnUnaryExprOrTypeTraitExpr( EndVar->getLocation(), UETT_SizeOf, /*isType=*/true, @@ -2416,7 +2416,7 @@ Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation CoawaitLoc, SizeOfVLAExprR.get(), SizeOfEachElementExprR.get()); if (BoundExpr.isInvalid()) return StmtError(); - + } else { // Can't be a DependentSizedArrayType or an IncompleteArrayType since // UnqAT is not incomplete and Range is not type-dependent. @@ -3366,7 +3366,7 @@ bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD, // statement with a non-type-dependent operand. assert(AT->isDeduced() && "should have deduced to dependent type"); return false; - } + } if (RetExpr) { // Otherwise, [...] deduce a value for U using the rules of template diff --git a/lib/Sema/SemaStmtAsm.cpp b/lib/Sema/SemaStmtAsm.cpp index 7e26b71c0482..0db15ea1f646 100644 --- a/lib/Sema/SemaStmtAsm.cpp +++ b/lib/Sema/SemaStmtAsm.cpp @@ -603,7 +603,7 @@ StmtResult Sema::ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple, Context.getTargetInfo(), Context); if (ConstraintLoc.isValid()) return Diag(ConstraintLoc, diag::error_inoutput_conflict_with_clobber); - + return NS; } diff --git a/lib/Sema/SemaTemplate.cpp b/lib/Sema/SemaTemplate.cpp index dd1163267119..fa002de3f5f1 100644 --- a/lib/Sema/SemaTemplate.cpp +++ b/lib/Sema/SemaTemplate.cpp @@ -888,7 +888,7 @@ ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) { // This is a normal type template argument. Note, if the type template // argument is an injected-class-name for a template, it has a dual nature - // and can be used as either a type or a template. We handle that in + // and can be used as either a type or a template. We handle that in // convertTypeTemplateArgumentToTemplate. return ParsedTemplateArgument(ParsedTemplateArgument::Type, ParsedType.get().getAsOpaquePtr(), @@ -1044,14 +1044,14 @@ NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, // Check that we have valid decl-specifiers specified. auto CheckValidDeclSpecifiers = [this, &D] { // C++ [temp.param] - // p1 + // p1 // template-parameter: // ... // parameter-declaration - // p2 + // p2 // ... A storage class shall not be specified in a template-parameter // declaration. - // [dcl.typedef]p1: + // [dcl.typedef]p1: // The typedef specifier [...] shall not be used in the decl-specifier-seq // of a parameter-declaration const DeclSpec &DS = D.getDeclSpec(); @@ -1061,22 +1061,22 @@ NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, }; if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) EmitDiag(DS.getStorageClassSpecLoc()); - + if (DS.getThreadStorageClassSpec() != TSCS_unspecified) EmitDiag(DS.getThreadStorageClassSpecLoc()); - - // [dcl.inline]p1: - // The inline specifier can be applied only to the declaration or + + // [dcl.inline]p1: + // The inline specifier can be applied only to the declaration or // definition of a variable or function. - + if (DS.isInlineSpecified()) EmitDiag(DS.getInlineSpecLoc()); - + // [dcl.constexpr]p1: - // The constexpr specifier shall be applied only to the definition of a - // variable or variable template or the declaration of a function or + // The constexpr specifier shall be applied only to the definition of a + // variable or variable template or the declaration of a function or // function template. - + if (DS.isConstexprSpecified()) EmitDiag(DS.getConstexprSpecLoc()); @@ -1094,7 +1094,7 @@ NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, }; CheckValidDeclSpecifiers(); - + if (TInfo->getType()->isUndeducedType()) { Diag(D.getIdentifierLoc(), diag::warn_cxx14_compat_template_nontype_parm_auto_type) @@ -1659,6 +1659,23 @@ DeclResult Sema::CheckClassTemplate( } namespace { +/// Tree transform to "extract" a transformed type from a class template's +/// constructor to a deduction guide. +class ExtractTypeForDeductionGuide + : public TreeTransform<ExtractTypeForDeductionGuide> { +public: + typedef TreeTransform<ExtractTypeForDeductionGuide> Base; + ExtractTypeForDeductionGuide(Sema &SemaRef) : Base(SemaRef) {} + + TypeSourceInfo *transform(TypeSourceInfo *TSI) { return TransformType(TSI); } + + QualType TransformTypedefType(TypeLocBuilder &TLB, TypedefTypeLoc TL) { + return TransformType( + TLB, + TL.getTypedefNameDecl()->getTypeSourceInfo()->getTypeLoc()); + } +}; + /// Transform to convert portions of a constructor declaration into the /// corresponding deduction guide, per C++1z [over.match.class.deduct]p1. struct ConvertConstructorToDeductionGuideTransform { @@ -1880,9 +1897,7 @@ private: MultiLevelTemplateArgumentList &Args) { TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo(); TypeSourceInfo *NewDI; - if (!Args.getNumLevels()) - NewDI = OldDI; - else if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) { + if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) { // Expand out the one and only element in each inner pack. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0); NewDI = @@ -1898,23 +1913,17 @@ private: if (!NewDI) return nullptr; - // Canonicalize the type. This (for instance) replaces references to - // typedef members of the current instantiations with the definitions of - // those typedefs, avoiding triggering instantiation of the deduced type - // during deduction. - // FIXME: It would be preferable to retain type sugar and source - // information here (and handle this in substitution instead). - NewDI = SemaRef.Context.getTrivialTypeSourceInfo( - SemaRef.Context.getCanonicalType(NewDI->getType()), - OldParam->getLocation()); + // Extract the type. This (for instance) replaces references to typedef + // members of the current instantiations with the definitions of those + // typedefs, avoiding triggering instantiation of the deduced type during + // deduction. + NewDI = ExtractTypeForDeductionGuide(SemaRef).transform(NewDI); // Resolving a wording defect, we also inherit default arguments from the // constructor. ExprResult NewDefArg; if (OldParam->hasDefaultArg()) { - NewDefArg = Args.getNumLevels() - ? SemaRef.SubstExpr(OldParam->getDefaultArg(), Args) - : OldParam->getDefaultArg(); + NewDefArg = SemaRef.SubstExpr(OldParam->getDefaultArg(), Args); if (NewDefArg.isInvalid()) return nullptr; } @@ -1929,6 +1938,7 @@ private: NewDefArg.get()); NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(), OldParam->getFunctionScopeIndex()); + SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam, NewParam); return NewParam; } diff --git a/lib/Sema/SemaTemplateDeduction.cpp b/lib/Sema/SemaTemplateDeduction.cpp index 633b2837e1fe..df46d6115a20 100644 --- a/lib/Sema/SemaTemplateDeduction.cpp +++ b/lib/Sema/SemaTemplateDeduction.cpp @@ -4599,7 +4599,7 @@ bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, CXXRecordDecl *Lambda = cast<CXXMethodDecl>(FD)->getParent(); FunctionDecl *CallOp = Lambda->getLambdaCallOperator(); - // For a generic lambda, instantiate the call operator if needed. + // For a generic lambda, instantiate the call operator if needed. if (auto *Args = FD->getTemplateSpecializationArgs()) { CallOp = InstantiateFunctionDeclaration( CallOp->getDescribedFunctionTemplate(), Args, Loc); diff --git a/lib/Sema/SemaTemplateInstantiate.cpp b/lib/Sema/SemaTemplateInstantiate.cpp index bc2ee42400b7..1aa69bd35d67 100644 --- a/lib/Sema/SemaTemplateInstantiate.cpp +++ b/lib/Sema/SemaTemplateInstantiate.cpp @@ -52,7 +52,7 @@ using namespace sema; /// used to determine the proper set of template instantiation arguments for /// friend function template specializations. MultiLevelTemplateArgumentList -Sema::getTemplateInstantiationArgs(NamedDecl *D, +Sema::getTemplateInstantiationArgs(NamedDecl *D, const TemplateArgumentList *Innermost, bool RelativeToPrimary, const FunctionDecl *Pattern) { @@ -61,7 +61,7 @@ Sema::getTemplateInstantiationArgs(NamedDecl *D, if (Innermost) Result.addOuterTemplateArguments(Innermost); - + DeclContext *Ctx = dyn_cast<DeclContext>(D); if (!Ctx) { Ctx = D->getDeclContext(); @@ -100,7 +100,7 @@ Sema::getTemplateInstantiationArgs(NamedDecl *D, // use empty template parameter lists for all of the outer templates // to avoid performing any substitutions. if (Ctx->isTranslationUnit()) { - if (TemplateTemplateParmDecl *TTP + if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) { for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I) Result.addOuterTemplateArguments(None); @@ -108,7 +108,7 @@ Sema::getTemplateInstantiationArgs(NamedDecl *D, } } } - + while (!Ctx->isFileContext()) { // Add template arguments from a class template instantiation. if (ClassTemplateSpecializationDecl *Spec @@ -119,8 +119,8 @@ Sema::getTemplateInstantiationArgs(NamedDecl *D, break; Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs()); - - // If this class template specialization was instantiated from a + + // If this class template specialization was instantiated from a // specialized member that is a class template, we're done. assert(Spec->getSpecializedTemplate() && "No class template?"); if (Spec->getSpecializedTemplate()->isMemberSpecialization()) @@ -129,11 +129,11 @@ Sema::getTemplateInstantiationArgs(NamedDecl *D, // Add template arguments from a function template specialization. else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) { if (!RelativeToPrimary && - (Function->getTemplateSpecializationKind() == + (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && !Function->getClassScopeSpecializationPattern())) break; - + if (const TemplateArgumentList *TemplateArgs = Function->getTemplateSpecializationArgs()) { // Add the template arguments for this specialization. @@ -154,7 +154,7 @@ Sema::getTemplateInstantiationArgs(NamedDecl *D, // Add the "injected" template arguments. Result.addOuterTemplateArguments(FunTmpl->getInjectedTemplateArgs()); } - + // If this is a friend declaration and it declares an entity at // namespace scope, take arguments from its lexical parent // instead of its semantic parent, unless of course the pattern we're @@ -200,7 +200,7 @@ bool Sema::CodeSynthesisContext::isInstantiationRecord() const { case DeclaringSpecialMember: case DefiningSynthesizedFunction: return false; - + // This function should never be called when Kind's value is Memoization. case Memoization: break; @@ -413,7 +413,7 @@ bool Sema::InstantiatingTemplate::CheckInstantiationDepth( SourceRange InstantiationRange) { assert(SemaRef.NonInstantiationEntries <= SemaRef.CodeSynthesisContexts.size()); - if ((SemaRef.CodeSynthesisContexts.size() - + if ((SemaRef.CodeSynthesisContexts.size() - SemaRef.NonInstantiationEntries) <= SemaRef.getLangOpts().InstantiationDepth) return false; @@ -517,9 +517,9 @@ void Sema::PrintInstantiationStack() { FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity); Diags.Report(Active->PointOfInstantiation, diag::note_explicit_template_arg_substitution_here) - << FnTmpl - << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(), - Active->TemplateArgs, + << FnTmpl + << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(), + Active->TemplateArgs, Active->NumTemplateArgs) << Active->InstantiationRange; break; @@ -531,8 +531,8 @@ void Sema::PrintInstantiationStack() { Diags.Report(Active->PointOfInstantiation, diag::note_function_template_deduction_instantiation_here) << FnTmpl - << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(), - Active->TemplateArgs, + << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(), + Active->TemplateArgs, Active->NumTemplateArgs) << Active->InstantiationRange; } else { @@ -556,7 +556,7 @@ void Sema::PrintInstantiationStack() { Diags.Report(Active->PointOfInstantiation, diag::note_deduced_template_arg_substitution_here) << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity) - << getTemplateArgumentBindingsText(Params, Active->TemplateArgs, + << getTemplateArgumentBindingsText(Params, Active->TemplateArgs, Active->NumTemplateArgs) << Active->InstantiationRange; } @@ -596,8 +596,8 @@ void Sema::PrintInstantiationStack() { diag::note_prior_template_arg_substitution) << isa<TemplateTemplateParmDecl>(Parm) << Name - << getTemplateArgumentBindingsText(TemplateParams, - Active->TemplateArgs, + << getTemplateArgumentBindingsText(TemplateParams, + Active->TemplateArgs, Active->NumTemplateArgs) << Active->InstantiationRange; break; @@ -614,8 +614,8 @@ void Sema::PrintInstantiationStack() { Diags.Report(Active->PointOfInstantiation, diag::note_template_default_arg_checking) - << getTemplateArgumentBindingsText(TemplateParams, - Active->TemplateArgs, + << getTemplateArgumentBindingsText(TemplateParams, + Active->TemplateArgs, Active->NumTemplateArgs) << Active->InstantiationRange; break; @@ -660,7 +660,7 @@ Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const { Active = CodeSynthesisContexts.rbegin(), ActiveEnd = CodeSynthesisContexts.rend(); Active != ActiveEnd; - ++Active) + ++Active) { switch (Active->Kind) { case CodeSynthesisContext::TemplateInstantiation: @@ -678,7 +678,7 @@ Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const { case CodeSynthesisContext::PriorTemplateArgumentSubstitution: case CodeSynthesisContext::DefaultTemplateArgumentChecking: // A default template argument instantiation and substitution into - // template parameters with arguments for prior parameters may or may + // template parameters with arguments for prior parameters may or may // not be a SFINAE context; look further up the stack. break; @@ -752,18 +752,18 @@ namespace { ArrayRef<UnexpandedParameterPack> Unexpanded, bool &ShouldExpand, bool &RetainExpansion, Optional<unsigned> &NumExpansions) { - return getSema().CheckParameterPacksForExpansion(EllipsisLoc, + return getSema().CheckParameterPacksForExpansion(EllipsisLoc, PatternRange, Unexpanded, - TemplateArgs, + TemplateArgs, ShouldExpand, RetainExpansion, NumExpansions); } - void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { + void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack); } - + TemplateArgument ForgetPartiallySubstitutedPack() { TemplateArgument Result; if (NamedDecl *PartialPack @@ -777,14 +777,14 @@ namespace { TemplateArgs.setArgument(Depth, Index, TemplateArgument()); } } - + return Result; } - + void RememberPartiallySubstitutedPack(TemplateArgument Arg) { if (Arg.isNull()) return; - + if (NamedDecl *PartialPack = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){ MultiLevelTemplateArgumentList &TemplateArgs @@ -799,7 +799,7 @@ namespace { /// this declaration. Decl *TransformDecl(SourceLocation Loc, Decl *D); - void transformAttrs(Decl *Old, Decl *New) { + void transformAttrs(Decl *Old, Decl *New) { SemaRef.InstantiateAttrs(TemplateArgs, Old, New); } @@ -817,7 +817,7 @@ namespace { NewMD->setInstantiationOfMemberFunction(OldMD, TSK_ImplicitInstantiation); } - + SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New); // We recreated a local declaration, but not by instantiating it. There @@ -825,7 +825,7 @@ namespace { if (auto *DC = dyn_cast<DeclContext>(Old)) SemaRef.PerformDependentDiagnostics(DC, TemplateArgs); } - + /// Transform the definition of the given declaration by /// instantiating it. Decl *TransformDefinition(SourceLocation Loc, Decl *D); @@ -833,20 +833,20 @@ namespace { /// Transform the first qualifier within a scope by instantiating the /// declaration. NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc); - + /// Rebuild the exception declaration and register the declaration /// as an instantiated local. - VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl, + VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl, TypeSourceInfo *Declarator, SourceLocation StartLoc, SourceLocation NameLoc, IdentifierInfo *Name); - /// Rebuild the Objective-C exception declaration and register the + /// Rebuild the Objective-C exception declaration and register the /// declaration as an instantiated local. - VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl, + VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl, TypeSourceInfo *TSInfo, QualType T); - + /// Check for tag mismatches when instantiating an /// elaborated type. QualType RebuildElaboratedType(SourceLocation KeywordLoc, @@ -921,11 +921,11 @@ namespace { TemplateParameterList *TransformTemplateParameterList( TemplateParameterList *OrigTPL) { if (!OrigTPL || !OrigTPL->size()) return OrigTPL; - + DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext(); - TemplateDeclInstantiator DeclInstantiator(getSema(), + TemplateDeclInstantiator DeclInstantiator(getSema(), /* DeclContext *Owner */ Owner, TemplateArgs); - return DeclInstantiator.SubstTemplateParams(OrigTPL); + return DeclInstantiator.SubstTemplateParams(OrigTPL); } private: ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm, @@ -937,17 +937,17 @@ namespace { bool TemplateInstantiator::AlreadyTransformed(QualType T) { if (T.isNull()) return true; - + if (T->isInstantiationDependentType() || T->isVariablyModifiedType()) return false; - + getSema().MarkDeclarationsReferencedInType(Loc, T); return true; } static TemplateArgument getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) { - assert(S.ArgumentPackSubstitutionIndex >= 0); + assert(S.ArgumentPackSubstitutionIndex >= 0); assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size()); Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex]; if (Arg.isPackExpansion()) @@ -970,9 +970,9 @@ Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) { return D; TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition()); - + if (TTP->isParameterPack()) { - assert(Arg.getKind() == TemplateArgument::Pack && + assert(Arg.getKind() == TemplateArgument::Pack && "Missing argument pack"); Arg = getPackSubstitutedTemplateArgument(getSema(), Arg); } @@ -1000,22 +1000,22 @@ Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) { } NamedDecl * -TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D, +TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc) { - // If the first part of the nested-name-specifier was a template type + // If the first part of the nested-name-specifier was a template type // parameter, instantiate that type parameter down to a tag type. if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) { - const TemplateTypeParmType *TTP + const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD)); - + if (TTP->getDepth() < TemplateArgs.getNumLevels()) { // FIXME: This needs testing w/ member access expressions. TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex()); - + if (TTP->isParameterPack()) { - assert(Arg.getKind() == TemplateArgument::Pack && + assert(Arg.getKind() == TemplateArgument::Pack && "Missing argument pack"); - + if (getSema().ArgumentPackSubstitutionIndex == -1) return nullptr; @@ -1025,16 +1025,16 @@ TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D, QualType T = Arg.getAsType(); if (T.isNull()) return cast_or_null<NamedDecl>(TransformDecl(Loc, D)); - + if (const TagType *Tag = T->getAs<TagType>()) return Tag->getDecl(); - + // The resulting type is not a tag; complain. getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T; return nullptr; } } - + return cast_or_null<NamedDecl>(TransformDecl(Loc, D)); } @@ -1051,8 +1051,8 @@ TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl, return Var; } -VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl, - TypeSourceInfo *TSInfo, +VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl, + TypeSourceInfo *TSInfo, QualType T) { VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T); if (Var) @@ -1107,13 +1107,13 @@ TemplateName TemplateInstantiator::TransformTemplateName( if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(), TTP->getPosition())) return Name; - + TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition()); - + if (TTP->isParameterPack()) { - assert(Arg.getKind() == TemplateArgument::Pack && + assert(Arg.getKind() == TemplateArgument::Pack && "Missing argument pack"); - + if (getSema().ArgumentPackSubstitutionIndex == -1) { // We have the template argument pack to substitute, but we're not // actually expanding the enclosing pack expansion yet. So, just @@ -1123,7 +1123,7 @@ TemplateName TemplateInstantiator::TransformTemplateName( Arg = getPackSubstitutedTemplateArgument(getSema(), Arg); } - + TemplateName Template = Arg.getAsTemplate().getNameToSubstitute(); assert(!Template.isNull() && "Null template template argument"); assert(!Template.getAsQualifiedTemplateName() && @@ -1133,12 +1133,12 @@ TemplateName TemplateInstantiator::TransformTemplateName( return Template; } } - + if (SubstTemplateTemplateParmPackStorage *SubstPack = Name.getAsSubstTemplateTemplateParmPack()) { if (getSema().ArgumentPackSubstitutionIndex == -1) return Name; - + TemplateArgument Arg = SubstPack->getArgumentPack(); Arg = getPackSubstitutedTemplateArgument(getSema(), Arg); return Arg.getAsTemplate().getNameToSubstitute(); @@ -1149,7 +1149,7 @@ TemplateName TemplateInstantiator::TransformTemplateName( AllowInjectedClassName); } -ExprResult +ExprResult TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) { if (!E->isTypeDependent()) return E; @@ -1187,15 +1187,15 @@ TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E, } if (NTTP->isParameterPack()) { - assert(Arg.getKind() == TemplateArgument::Pack && + assert(Arg.getKind() == TemplateArgument::Pack && "Missing argument pack"); - + if (getSema().ArgumentPackSubstitutionIndex == -1) { // We have an argument pack, but we can't select a particular argument // out of it yet. Therefore, we'll build an expression to hold on to that // argument pack. QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs, - E->getLocation(), + E->getLocation(), NTTP->getDeclName()); if (TargetType.isNull()) return ExprError(); @@ -1205,7 +1205,7 @@ TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E, TargetType->isReferenceType() ? VK_LValue : VK_RValue, NTTP, E->getLocation(), Arg); } - + Arg = getPackSubstitutedTemplateArgument(getSema(), Arg); } @@ -1260,12 +1260,12 @@ ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef( // Propagate NULL template argument. VD = nullptr; } - + // Derive the type we want the substituted decl to have. This had // better be non-dependent, or these checks will have serious problems. if (parm->isExpandedParameterPack()) { type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex); - } else if (parm->isParameterPack() && + } else if (parm->isParameterPack() && isa<PackExpansionType>(parm->getType())) { type = SemaRef.SubstType( cast<PackExpansionType>(parm->getType())->getPattern(), @@ -1292,8 +1292,8 @@ ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef( return new (SemaRef.Context) SubstNonTypeTemplateParmExpr( type, resultExpr->getValueKind(), loc, parm, resultExpr); } - -ExprResult + +ExprResult TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr( SubstNonTypeTemplateParmPackExpr *E) { if (getSema().ArgumentPackSubstitutionIndex == -1) { @@ -1387,7 +1387,7 @@ TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) { if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) { if (NTTP->getDepth() < TemplateArgs.getNumLevels()) return TransformTemplateParmRefExpr(E, NTTP); - + // We have a non-type template parameter that isn't fully substituted; // FindInstantiatedDecl will find it in the local instantiation scope. } @@ -1406,7 +1406,7 @@ ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr( getDescribedFunctionTemplate() && "Default arg expressions are never formed in dependent cases."); return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(), - cast<FunctionDecl>(E->getParam()->getDeclContext()), + cast<FunctionDecl>(E->getParam()->getDeclContext()), E->getParam()); } @@ -1451,11 +1451,11 @@ TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB, } TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex()); - + if (T->isParameterPack()) { - assert(Arg.getKind() == TemplateArgument::Pack && + assert(Arg.getKind() == TemplateArgument::Pack && "Missing argument pack"); - + if (getSema().ArgumentPackSubstitutionIndex == -1) { // We have the template argument pack, but we're not expanding the // enclosing pack expansion yet. Just save the template argument @@ -1467,10 +1467,10 @@ TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB, NewTL.setNameLoc(TL.getNameLoc()); return Result; } - + Arg = getPackSubstitutedTemplateArgument(getSema(), Arg); } - + assert(Arg.getKind() == TemplateArgument::Type && "Template argument kind mismatch"); @@ -1502,7 +1502,7 @@ TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB, return Result; } -QualType +QualType TemplateInstantiator::TransformSubstTemplateTypeParmPackType( TypeLocBuilder &TLB, SubstTemplateTypeParmPackTypeLoc TL) { @@ -1565,8 +1565,8 @@ TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T, assert(!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the " "instantiation stack"); - - if (!T->getType()->isInstantiationDependentType() && + + if (!T->getType()->isInstantiationDependentType() && !T->getType()->isVariablyModifiedType()) return T; @@ -1582,11 +1582,11 @@ TypeSourceInfo *Sema::SubstType(TypeLoc TL, assert(!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the " "instantiation stack"); - + if (TL.getType().isNull()) return nullptr; - if (!TL.getType()->isInstantiationDependentType() && + if (!TL.getType()->isInstantiationDependentType() && !TL.getType()->isVariablyModifiedType()) { // FIXME: Make a copy of the TypeLoc data here, so that we can // return a new TypeSourceInfo. Inefficient! @@ -1716,7 +1716,7 @@ void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, UpdateExceptionSpec(New, ESI); } -ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm, +ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm, const MultiLevelTemplateArgumentList &TemplateArgs, int indexAdjustment, Optional<unsigned> NumExpansions, @@ -1727,9 +1727,9 @@ ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm, TypeLoc OldTL = OldDI->getTypeLoc(); if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) { - // We have a function parameter pack. Substitute into the pattern of the + // We have a function parameter pack. Substitute into the pattern of the // expansion. - NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs, + NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs, OldParm->getLocation(), OldParm->getDeclName()); if (!NewDI) return nullptr; @@ -1745,16 +1745,16 @@ ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm, // itself is not a pack expansion type), so complain. This can occur when // the substitution goes through an alias template that "loses" the // pack expansion. - Diag(OldParm->getLocation(), + Diag(OldParm->getLocation(), diag::err_function_parameter_pack_without_parameter_packs) << NewDI->getType(); return nullptr; - } + } } else { - NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(), + NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(), OldParm->getDeclName()); } - + if (!NewDI) return nullptr; @@ -1801,15 +1801,15 @@ ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm, } NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg()); - + if (OldParm->isParameterPack() && !NewParm->isParameterPack()) { // Add the new parameter to the instantiated parameter pack. CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm); } else { // Introduce an Old -> New mapping - CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm); + CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm); } - + // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext // can be anything, is this right ? NewParm->setDeclContext(CurContext); @@ -1819,7 +1819,7 @@ ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm, InstantiateAttrs(TemplateArgs, OldParm, NewParm); - return NewParm; + return NewParm; } /// Substitute the given template arguments into the given set of @@ -1835,8 +1835,8 @@ bool Sema::SubstParmTypes( assert(!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the " "instantiation stack"); - - TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, + + TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, DeclarationName()); return Instantiator.TransformFunctionTypeParams( Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos); @@ -1875,21 +1875,21 @@ Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation, bool ShouldExpand = false; bool RetainExpansion = false; Optional<unsigned> NumExpansions; - if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(), + if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(), Base.getSourceRange(), Unexpanded, - TemplateArgs, ShouldExpand, + TemplateArgs, ShouldExpand, RetainExpansion, NumExpansions)) { Invalid = true; continue; } - + // If we should expand this pack expansion now, do so. if (ShouldExpand) { for (unsigned I = 0; I != *NumExpansions; ++I) { Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I); - + TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(), TemplateArgs, Base.getSourceRange().getBegin(), @@ -1898,7 +1898,7 @@ Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation, Invalid = true; continue; } - + if (CXXBaseSpecifier *InstantiatedBase = CheckBaseSpecifier(Instantiation, Base.getSourceRange(), @@ -1910,10 +1910,10 @@ Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation, else Invalid = true; } - + continue; } - + // The resulting base specifier will (still) be a pack expansion. EllipsisLoc = Base.getEllipsisLoc(); Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1); @@ -1927,7 +1927,7 @@ Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation, Base.getSourceRange().getBegin(), DeclarationName()); } - + if (!BaseTypeLoc) { Invalid = true; continue; @@ -1999,11 +1999,11 @@ Sema::InstantiateClass(SourceLocation PointOfInstantiation, Pattern = PatternDef; // Record the point of instantiation. - if (MemberSpecializationInfo *MSInfo + if (MemberSpecializationInfo *MSInfo = Instantiation->getMemberSpecializationInfo()) { MSInfo->setTemplateSpecializationKind(TSK); MSInfo->setPointOfInstantiation(PointOfInstantiation); - } else if (ClassTemplateSpecializationDecl *Spec + } else if (ClassTemplateSpecializationDecl *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) { Spec->setTemplateSpecializationKind(TSK); Spec->setPointOfInstantiation(PointOfInstantiation); @@ -2563,15 +2563,15 @@ Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation, if (auto *Function = dyn_cast<FunctionDecl>(D)) { if (FunctionDecl *Pattern = Function->getInstantiatedFromMemberFunction()) { - MemberSpecializationInfo *MSInfo + MemberSpecializationInfo *MSInfo = Function->getMemberSpecializationInfo(); assert(MSInfo && "No member specialization information?"); if (MSInfo->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) continue; - - if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK, - Function, + + if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK, + Function, MSInfo->getTemplateSpecializationKind(), MSInfo->getPointOfInstantiation(), SuppressNew) || @@ -2610,31 +2610,31 @@ Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation, if (MSInfo->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) continue; - - if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK, - Var, + + if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK, + Var, MSInfo->getTemplateSpecializationKind(), MSInfo->getPointOfInstantiation(), SuppressNew) || SuppressNew) continue; - + if (TSK == TSK_ExplicitInstantiationDefinition) { // C++0x [temp.explicit]p8: // An explicit instantiation definition that names a class template - // specialization explicitly instantiates the class template - // specialization and is only an explicit instantiation definition - // of members whose definition is visible at the point of + // specialization explicitly instantiates the class template + // specialization and is only an explicit instantiation definition + // of members whose definition is visible at the point of // instantiation. if (!Var->getInstantiatedFromStaticDataMember()->getDefinition()) continue; - + Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); InstantiateVariableDefinition(PointOfInstantiation, Var); } else { Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); } - } + } } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) { // Always skip the injected-class-name, along with any // redeclarations of nested classes, since both would cause us @@ -2644,10 +2644,10 @@ Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation, if (Record->isInjectedClassName() || Record->getPreviousDecl() || Record->isLambda()) continue; - + MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo(); assert(MSInfo && "No member specialization information?"); - + if (MSInfo->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) continue; @@ -2660,33 +2660,33 @@ Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation, continue; } - if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK, - Record, + if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK, + Record, MSInfo->getTemplateSpecializationKind(), MSInfo->getPointOfInstantiation(), SuppressNew) || SuppressNew) continue; - + CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass(); assert(Pattern && "Missing instantiated-from-template information"); - + if (!Record->getDefinition()) { if (!Pattern->getDefinition()) { // C++0x [temp.explicit]p8: // An explicit instantiation definition that names a class template - // specialization explicitly instantiates the class template - // specialization and is only an explicit instantiation definition - // of members whose definition is visible at the point of + // specialization explicitly instantiates the class template + // specialization and is only an explicit instantiation definition + // of members whose definition is visible at the point of // instantiation. if (TSK == TSK_ExplicitInstantiationDeclaration) { MSInfo->setTemplateSpecializationKind(TSK); MSInfo->setPointOfInstantiation(PointOfInstantiation); } - + continue; } - + InstantiateClass(PointOfInstantiation, Record, Pattern, TemplateArgs, TSK); @@ -2698,10 +2698,10 @@ Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation, MarkVTableUsed(PointOfInstantiation, Record, true); } } - + Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition()); if (Pattern) - InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs, + InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs, TSK); } else if (auto *Enum = dyn_cast<EnumDecl>(D)) { MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo(); @@ -2816,10 +2816,10 @@ bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall, NestedNameSpecifierLoc Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, - const MultiLevelTemplateArgumentList &TemplateArgs) { + const MultiLevelTemplateArgumentList &TemplateArgs) { if (!NNS) return NestedNameSpecifierLoc(); - + TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(), DeclarationName()); return Instantiator.TransformNestedNameSpecifierLoc(NNS); @@ -2850,7 +2850,7 @@ bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs, const MultiLevelTemplateArgumentList &TemplateArgs) { TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(), DeclarationName()); - + return Instantiator.TransformTemplateArguments(Args, NumArgs, Result); } @@ -2884,7 +2884,7 @@ LocalInstantiationScope::findInstantiationOf(const Decl *D) { LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD); if (Found != Current->LocalDecls.end()) return &Found->second; - + // If this is a tag declaration, it's possible that we need to look for // a previous declaration. if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD)) @@ -2892,8 +2892,8 @@ LocalInstantiationScope::findInstantiationOf(const Decl *D) { else CheckD = nullptr; } while (CheckD); - - // If we aren't combined with our outer scope, we're done. + + // If we aren't combined with our outer scope, we're done. if (!Current->CombineWithOuterScope) break; } @@ -2965,12 +2965,12 @@ void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) { ArgumentPacks.push_back(Pack); } -void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack, +void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack, const TemplateArgument *ExplicitArgs, unsigned NumExplicitArgs) { assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) && "Already have a partially-substituted pack"); - assert((!PartiallySubstitutedPack + assert((!PartiallySubstitutedPack || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) && "Wrong number of arguments in partially-substituted pack"); PartiallySubstitutedPack = Pack; @@ -2985,15 +2985,15 @@ NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack( *ExplicitArgs = nullptr; if (NumExplicitArgs) *NumExplicitArgs = 0; - - for (const LocalInstantiationScope *Current = this; Current; + + for (const LocalInstantiationScope *Current = this; Current; Current = Current->Outer) { if (Current->PartiallySubstitutedPack) { if (ExplicitArgs) *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack; if (NumExplicitArgs) *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack; - + return Current->PartiallySubstitutedPack; } diff --git a/lib/Sema/SemaTemplateInstantiateDecl.cpp b/lib/Sema/SemaTemplateInstantiateDecl.cpp index 5109dc8290f9..86492716f685 100644 --- a/lib/Sema/SemaTemplateInstantiateDecl.cpp +++ b/lib/Sema/SemaTemplateInstantiateDecl.cpp @@ -729,7 +729,7 @@ Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D, DI, D->getStorageClass()); // In ARC, infer 'retaining' for variables of retainable type. - if (SemaRef.getLangOpts().ObjCAutoRefCount && + if (SemaRef.getLangOpts().ObjCAutoRefCount && SemaRef.inferObjCARCLifetime(Var)) Var->setInvalidDecl(); @@ -2056,7 +2056,7 @@ TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D, // previous declaration we just found. if (isFriend && Method->getPreviousDecl()) Method->setAccess(Method->getPreviousDecl()->getAccess()); - else + else Method->setAccess(D->getAccess()); if (FunctionTemplate) FunctionTemplate->setAccess(Method->getAccess()); @@ -3417,7 +3417,7 @@ TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D, ThisContext = cast<CXXRecordDecl>(Owner); ThisTypeQuals = Method->getTypeQualifiers(); } - + TypeSourceInfo *NewTInfo = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs, D->getTypeSpecStartLoc(), @@ -4890,14 +4890,14 @@ NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, bool FindingInstantiatedContext) { DeclContext *ParentDC = D->getDeclContext(); - // FIXME: Parmeters of pointer to functions (y below) that are themselves + // FIXME: Parmeters of pointer to functions (y below) that are themselves // parameters (p below) can have their ParentDC set to the translation-unit - // - thus we can not consistently check if the ParentDC of such a parameter + // - thus we can not consistently check if the ParentDC of such a parameter // is Dependent or/and a FunctionOrMethod. - // For e.g. this code, during Template argument deduction tries to + // For e.g. this code, during Template argument deduction tries to // find an instantiated decl for (T y) when the ParentDC for y is - // the translation unit. - // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {} + // the translation unit. + // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {} // float baz(float(*)()) { return 0.0; } // Foo(baz); // The better fix here is perhaps to ensure that a ParmVarDecl, by the time diff --git a/lib/Sema/SemaTemplateVariadic.cpp b/lib/Sema/SemaTemplateVariadic.cpp index fc1641334273..6f9dddf5c05e 100644 --- a/lib/Sema/SemaTemplateVariadic.cpp +++ b/lib/Sema/SemaTemplateVariadic.cpp @@ -29,7 +29,7 @@ using namespace clang; namespace { /// A class that collects unexpanded parameter packs. class CollectUnexpandedParameterPacksVisitor : - public RecursiveASTVisitor<CollectUnexpandedParameterPacksVisitor> + public RecursiveASTVisitor<CollectUnexpandedParameterPacksVisitor> { typedef RecursiveASTVisitor<CollectUnexpandedParameterPacksVisitor> inherited; @@ -58,7 +58,7 @@ namespace { if (T->getDepth() < DepthLimit) Unexpanded.push_back({T, Loc}); } - + public: explicit CollectUnexpandedParameterPacksVisitor( SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) @@ -94,10 +94,10 @@ namespace { bool VisitDeclRefExpr(DeclRefExpr *E) { if (E->getDecl()->isParameterPack()) addUnexpanded(E->getDecl(), E->getLocation()); - + return true; } - + /// Record occurrences of template template parameter packs. bool TraverseTemplateName(TemplateName Template) { if (auto *TTP = dyn_cast_or_null<TemplateTemplateParmDecl>( @@ -105,7 +105,7 @@ namespace { if (TTP->isParameterPack()) addUnexpanded(TTP); } - + return inherited::TraverseTemplateName(Template); } @@ -131,7 +131,7 @@ namespace { /// Suppress traversal into statements and expressions that /// do not contain unexpanded parameter packs. - bool TraverseStmt(Stmt *S) { + bool TraverseStmt(Stmt *S) { Expr *E = dyn_cast_or_null<Expr>(S); if ((E && E->containsUnexpandedParameterPack()) || InLambda) return inherited::TraverseStmt(S); @@ -151,7 +151,7 @@ namespace { /// Suppress traversal into types with location information /// that do not contain unexpanded parameter packs. bool TraverseTypeLoc(TypeLoc TL) { - if ((!TL.getType().isNull() && + if ((!TL.getType().isNull() && TL.getType()->containsUnexpandedParameterPack()) || InLambda) return inherited::TraverseTypeLoc(TL); @@ -160,7 +160,7 @@ namespace { } /// Suppress traversal of parameter packs. - bool TraverseDecl(Decl *D) { + bool TraverseDecl(Decl *D) { // A function parameter pack is a pack expansion, so cannot contain // an unexpanded parameter pack. Likewise for a template parameter // pack that contains any references to other packs. @@ -215,7 +215,7 @@ namespace { bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc) { if (ArgLoc.getArgument().isPackExpansion()) return true; - + return inherited::TraverseTemplateArgumentLoc(ArgLoc); } @@ -335,7 +335,7 @@ Sema::DiagnoseUnexpandedParameterPacks(SourceLocation Loc, return false; } } - + SmallVector<SourceLocation, 4> Locations; SmallVector<IdentifierInfo *, 4> Names; llvm::SmallPtrSet<IdentifierInfo *, 4> NamesKnown; @@ -365,11 +365,11 @@ Sema::DiagnoseUnexpandedParameterPacks(SourceLocation Loc, return true; } -bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc, +bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC) { // C++0x [temp.variadic]p5: - // An appearance of a name of a parameter pack that is not expanded is + // An appearance of a name of a parameter pack that is not expanded is // ill-formed. if (!T->getType()->containsUnexpandedParameterPack()) return false; @@ -384,7 +384,7 @@ bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc, bool Sema::DiagnoseUnexpandedParameterPack(Expr *E, UnexpandedParameterPackContext UPPC) { // C++0x [temp.variadic]p5: - // An appearance of a name of a parameter pack that is not expanded is + // An appearance of a name of a parameter pack that is not expanded is // ill-formed. if (!E->containsUnexpandedParameterPack()) return false; @@ -398,9 +398,9 @@ bool Sema::DiagnoseUnexpandedParameterPack(Expr *E, bool Sema::DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS, UnexpandedParameterPackContext UPPC) { // C++0x [temp.variadic]p5: - // An appearance of a name of a parameter pack that is not expanded is + // An appearance of a name of a parameter pack that is not expanded is // ill-formed. - if (!SS.getScopeRep() || + if (!SS.getScopeRep() || !SS.getScopeRep()->containsUnexpandedParameterPack()) return false; @@ -415,7 +415,7 @@ bool Sema::DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS, bool Sema::DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo, UnexpandedParameterPackContext UPPC) { // C++0x [temp.variadic]p5: - // An appearance of a name of a parameter pack that is not expanded is + // An appearance of a name of a parameter pack that is not expanded is // ill-formed. switch (NameInfo.getName().getNameKind()) { case DeclarationName::Identifier: @@ -451,7 +451,7 @@ bool Sema::DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo, bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc, TemplateName Template, UnexpandedParameterPackContext UPPC) { - + if (Template.isNull() || !Template.containsUnexpandedParameterPack()) return false; @@ -464,10 +464,10 @@ bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc, bool Sema::DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg, UnexpandedParameterPackContext UPPC) { - if (Arg.getArgument().isNull() || + if (Arg.getArgument().isNull() || !Arg.getArgument().containsUnexpandedParameterPack()) return false; - + SmallVector<UnexpandedParameterPack, 2> Unexpanded; CollectUnexpandedParameterPacksVisitor(Unexpanded) .TraverseTemplateArgumentLoc(Arg); @@ -489,12 +489,12 @@ void Sema::collectUnexpandedParameterPacks(TemplateArgumentLoc Arg, void Sema::collectUnexpandedParameterPacks(QualType T, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) { - CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(T); -} + CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(T); +} void Sema::collectUnexpandedParameterPacks(TypeLoc TL, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) { - CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(TL); + CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(TL); } void Sema::collectUnexpandedParameterPacks( @@ -512,7 +512,7 @@ void Sema::collectUnexpandedParameterPacks( } -ParsedTemplateArgument +ParsedTemplateArgument Sema::ActOnPackExpansion(const ParsedTemplateArgument &Arg, SourceLocation EllipsisLoc) { if (Arg.isInvalid()) @@ -524,7 +524,7 @@ Sema::ActOnPackExpansion(const ParsedTemplateArgument &Arg, if (Result.isInvalid()) return ParsedTemplateArgument(); - return ParsedTemplateArgument(Arg.getKind(), Result.get().getAsOpaquePtr(), + return ParsedTemplateArgument(Arg.getKind(), Result.get().getAsOpaquePtr(), Arg.getLocation()); } @@ -532,11 +532,11 @@ Sema::ActOnPackExpansion(const ParsedTemplateArgument &Arg, ExprResult Result = ActOnPackExpansion(Arg.getAsExpr(), EllipsisLoc); if (Result.isInvalid()) return ParsedTemplateArgument(); - - return ParsedTemplateArgument(Arg.getKind(), Result.get(), + + return ParsedTemplateArgument(Arg.getKind(), Result.get(), Arg.getLocation()); } - + case ParsedTemplateArgument::Template: if (!Arg.getAsTemplate().get().containsUnexpandedParameterPack()) { SourceRange R(Arg.getLocation()); @@ -546,13 +546,13 @@ Sema::ActOnPackExpansion(const ParsedTemplateArgument &Arg, << R; return ParsedTemplateArgument(); } - + return Arg.getTemplatePackExpansion(EllipsisLoc); } llvm_unreachable("Unhandled template argument kind?"); } -TypeResult Sema::ActOnPackExpansion(ParsedType Type, +TypeResult Sema::ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc) { TypeSourceInfo *TSInfo; GetTypeFromParser(Type, &TSInfo); @@ -562,7 +562,7 @@ TypeResult Sema::ActOnPackExpansion(ParsedType Type, TypeSourceInfo *TSResult = CheckPackExpansion(TSInfo, EllipsisLoc, None); if (!TSResult) return true; - + return CreateParsedType(TSResult->getType(), TSResult); } @@ -570,7 +570,7 @@ TypeSourceInfo * Sema::CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions) { // Create the pack expansion type and source-location information. - QualType Result = CheckPackExpansion(Pattern->getType(), + QualType Result = CheckPackExpansion(Pattern->getType(), Pattern->getTypeLoc().getSourceRange(), EllipsisLoc, NumExpansions); if (Result.isNull()) @@ -608,7 +608,7 @@ ExprResult Sema::CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions) { if (!Pattern) return ExprError(); - + // C++0x [temp.variadic]p5: // The pattern of a pack expansion shall name one or more // parameter packs that are not expanded by a nested pack @@ -618,7 +618,7 @@ ExprResult Sema::CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc, << Pattern->getSourceRange(); return ExprError(); } - + // Create the pack expansion expression and source-location information. return new (Context) PackExpansionExpr(Context.DependentTy, Pattern, EllipsisLoc, NumExpansions); @@ -643,7 +643,7 @@ bool Sema::CheckParameterPacksForExpansion( unsigned Depth = 0, Index = 0; IdentifierInfo *Name; bool IsFunctionParameterPack = false; - + if (const TemplateTypeParmType *TTP = i->first.dyn_cast<const TemplateTypeParmType *>()) { Depth = TTP->getDepth(); @@ -658,13 +658,13 @@ bool Sema::CheckParameterPacksForExpansion( Name = ND->getIdentifier(); } - + // Determine the size of this argument pack. - unsigned NewPackSize; + unsigned NewPackSize; if (IsFunctionParameterPack) { // Figure out whether we're instantiating to an argument pack or not. typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack; - + llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation = CurrentInstantiationScope->findInstantiationOf( i->first.get<NamedDecl *>()); @@ -678,25 +678,25 @@ bool Sema::CheckParameterPacksForExpansion( continue; } } else { - // If we don't have a template argument at this depth/index, then we - // cannot expand the pack expansion. Make a note of this, but we still + // If we don't have a template argument at this depth/index, then we + // cannot expand the pack expansion. Make a note of this, but we still // want to check any parameter packs we *do* have arguments for. if (Depth >= TemplateArgs.getNumLevels() || !TemplateArgs.hasTemplateArgument(Depth, Index)) { ShouldExpand = false; continue; } - + // Determine the size of the argument pack. NewPackSize = TemplateArgs(Depth, Index).pack_size(); } - + // C++0x [temp.arg.explicit]p9: - // Template argument deduction can extend the sequence of template + // Template argument deduction can extend the sequence of template // arguments corresponding to a template parameter pack, even when the // sequence contains explicitly specified template arguments. if (!IsFunctionParameterPack && CurrentInstantiationScope) { - if (NamedDecl *PartialPack + if (NamedDecl *PartialPack = CurrentInstantiationScope->getPartiallySubstitutedPack()){ unsigned PartialDepth, PartialIndex; std::tie(PartialDepth, PartialIndex) = getDepthAndIndex(PartialPack); @@ -709,9 +709,9 @@ bool Sema::CheckParameterPacksForExpansion( } } } - + if (!NumExpansions) { - // The is the first pack we've seen for which we have an argument. + // The is the first pack we've seen for which we have an argument. // Record it. NumExpansions = NewPackSize; FirstPack.first = Name; @@ -719,10 +719,10 @@ bool Sema::CheckParameterPacksForExpansion( HaveFirstPack = true; continue; } - + if (NewPackSize != *NumExpansions) { // C++0x [temp.variadic]p5: - // All of the parameter packs expanded by a pack expansion shall have + // All of the parameter packs expanded by a pack expansion shall have // the same number of arguments specified. if (HaveFirstPack) Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict) @@ -772,17 +772,17 @@ Optional<unsigned> Sema::getNumArgumentsInExpansion(QualType T, // Compute the depth and index for this parameter pack. unsigned Depth; unsigned Index; - + if (const TemplateTypeParmType *TTP = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>()) { Depth = TTP->getDepth(); Index = TTP->getIndex(); - } else { + } else { NamedDecl *ND = Unexpanded[I].first.get<NamedDecl *>(); if (isa<ParmVarDecl>(ND)) { // Function parameter pack. typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack; - + llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation = CurrentInstantiationScope->findInstantiationOf( Unexpanded[I].first.get<NamedDecl *>()); @@ -804,13 +804,13 @@ Optional<unsigned> Sema::getNumArgumentsInExpansion(QualType T, // The pattern refers to an unknown template argument. We're not ready to // expand this pack yet. return None; - + // Determine the size of the argument pack. unsigned Size = TemplateArgs(Depth, Index).pack_size(); assert((!Result || *Result == Size) && "inconsistent pack sizes"); Result = Size; } - + return Result; } @@ -826,14 +826,14 @@ bool Sema::containsUnexpandedParameterPacks(Declarator &D) { return true; break; } - + case TST_typeofExpr: case TST_decltype: - if (DS.getRepAsExpr() && + if (DS.getRepAsExpr() && DS.getRepAsExpr()->containsUnexpandedParameterPack()) return true; break; - + case TST_unspecified: case TST_void: case TST_char: @@ -879,7 +879,7 @@ bool Sema::containsUnexpandedParameterPacks(Declarator &D) { case DeclaratorChunk::BlockPointer: // These declarator chunks cannot contain any parameter packs. break; - + case DeclaratorChunk::Array: if (Chunk.Arr.NumElts && Chunk.Arr.NumElts->containsUnexpandedParameterPack()) @@ -964,7 +964,7 @@ ExprResult Sema::ActOnSizeofParameterPackExpr(Scope *S, case LookupResult::Found: ParameterPack = R.getFoundDecl(); break; - + case LookupResult::NotFound: case LookupResult::NotFoundInCurrentInstantiation: if (TypoCorrection Corrected = diff --git a/lib/Sema/SemaType.cpp b/lib/Sema/SemaType.cpp index ac04cecaf774..284d34b22c04 100644 --- a/lib/Sema/SemaType.cpp +++ b/lib/Sema/SemaType.cpp @@ -2851,7 +2851,7 @@ static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state, case DeclaratorContext::ObjCParameterContext: case DeclaratorContext::ObjCResultContext: case DeclaratorContext::PrototypeContext: - Error = 0; + Error = 0; break; case DeclaratorContext::LambdaExprParameterContext: // In C++14, generic lambdas allow 'auto' in their parameters. @@ -2859,7 +2859,7 @@ static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state, !Auto || Auto->getKeyword() != AutoTypeKeyword::Auto) Error = 16; else { - // If auto is mentioned in a lambda parameter context, convert it to a + // If auto is mentioned in a lambda parameter context, convert it to a // template parameter type. sema::LambdaScopeInfo *LSI = SemaRef.getCurLambda(); assert(LSI && "No LambdaScopeInfo on the stack!"); @@ -2877,7 +2877,7 @@ static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state, TemplateParameterDepth, AutoParameterPosition, /*Identifier*/nullptr, false, IsParameterPack); LSI->AutoTemplateParams.push_back(CorrespondingTemplateParam); - // Replace the 'auto' in the function parameter with this invented + // Replace the 'auto' in the function parameter with this invented // template type parameter. // FIXME: Retain some type sugar to indicate that this was written // as 'auto'. @@ -4440,7 +4440,7 @@ static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state, S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return) << T << 0 /*pointer hint*/; D.setInvalidType(true); - } + } } else if (!S.getLangOpts().HalfArgsAndReturns) { S.Diag(D.getIdentifierLoc(), diag::err_parameters_retval_cannot_have_fp16_type) << 1; @@ -5233,6 +5233,8 @@ static ParsedAttr::Kind getAttrListKind(AttributedType::Kind kind) { return ParsedAttr::AT_ObjCKindOf; case AttributedType::attr_ns_returns_retained: return ParsedAttr::AT_NSReturnsRetained; + case AttributedType::attr_lifetimebound: + return ParsedAttr::AT_LifetimeBound; } llvm_unreachable("unexpected attribute kind!"); } @@ -5332,7 +5334,7 @@ namespace { TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>()); assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc()); } - + } void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr); @@ -5627,11 +5629,11 @@ Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T, } for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { - + if (DependentAddressSpaceTypeLoc DASTL = CurrTL.getAs<DependentAddressSpaceTypeLoc>()) { fillDependentAddressSpaceTypeLoc(DASTL, D.getTypeObject(i).getAttrs()); - CurrTL = DASTL.getPointeeTypeLoc().getUnqualifiedLoc(); + CurrTL = DASTL.getPointeeTypeLoc().getUnqualifiedLoc(); } // An AtomicTypeLoc might be produced by an atomic qualifier in this @@ -5727,13 +5729,13 @@ ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) { // Type Attribute Processing //===----------------------------------------------------------------------===// -/// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an expression -/// is uninstantiated. If instantiated it will apply the appropriate address space +/// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an expression +/// is uninstantiated. If instantiated it will apply the appropriate address space /// to the type. This function allows dependent template variables to be used in -/// conjunction with the address_space attribute +/// conjunction with the address_space attribute QualType Sema::BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace, SourceLocation AttrLoc) { - if (!AddrSpace->isValueDependent()) { + if (!AddrSpace->isValueDependent()) { llvm::APSInt addrSpace(32); if (!AddrSpace->isIntegerConstantExpr(addrSpace, Context)) { @@ -5783,8 +5785,8 @@ QualType Sema::BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace, } // A check with similar intentions as checking if a type already has an - // address space except for on a dependent types, basically if the - // current type is already a DependentAddressSpaceType then its already + // address space except for on a dependent types, basically if the + // current type is already a DependentAddressSpaceType then its already // lined up to have another address space on it and we can't have // multiple address spaces on the one pointer indirection if (T->getAs<DependentAddressSpaceType>()) { @@ -6116,7 +6118,7 @@ static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr, attr.setInvalid(); return true; } - + // Check the attribute arguments. if (!attr.isArgIdent(0)) { S.Diag(attr.getLoc(), diag::err_attribute_argument_type) @@ -6327,7 +6329,7 @@ static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State, << "'__sptr'" << "'__uptr'"; return true; } - + Desugared = AT->getEquivalentType(); AT = dyn_cast<AttributedType>(Desugared); } @@ -6384,7 +6386,7 @@ bool Sema::checkNullabilityTypeSpecifier(QualType &type, << FixItHint::CreateRemoval(nullabilityLoc); break; - } + } // Conflicting nullability. Diag(nullabilityLoc, diag::err_nullability_conflicting) @@ -6430,7 +6432,7 @@ bool Sema::checkNullabilityTypeSpecifier(QualType &type, << DiagNullabilityKind(nullability, isContextSensitive) << type; return true; } - + // For the context-sensitive keywords/Objective-C property // attributes, require that the type be a single-level pointer. if (isContextSensitive) { @@ -6472,7 +6474,7 @@ bool Sema::checkObjCKindOfType(QualType &type, SourceLocation loc) { // Find out if it's an Objective-C object or object pointer type; const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>(); - const ObjCObjectType *objType = ptrType ? ptrType->getObjectType() + const ObjCObjectType *objType = ptrType ? ptrType->getObjectType() : type->getAs<ObjCObjectType>(); // If not, we can't apply __kindof. @@ -6501,7 +6503,7 @@ bool Sema::checkObjCKindOfType(QualType &type, SourceLocation loc) { } // Build the attributed type to record where __kindof occurred. - type = Context.getAttributedType(AttributedType::attr_objc_kindof, + type = Context.getAttributedType(AttributedType::attr_objc_kindof, type, equivType); @@ -6601,7 +6603,7 @@ static bool distributeNullabilityTypeAttr(TypeProcessingState &state, } return false; - + // Don't walk through these. case DeclaratorChunk::Reference: case DeclaratorChunk::Pipe: @@ -6732,7 +6734,7 @@ static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr, if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr)) return true; - // If this is not a function type, warning will be asserted by subject + // If this is not a function type, warning will be asserted by subject // check. if (!unwrapped.isFunctionType()) return true; @@ -7194,6 +7196,18 @@ static void deduceOpenCLImplicitAddrSpace(TypeProcessingState &State, T = State.getSema().Context.getAddrSpaceQualType(T, ImpAddr); } +static void HandleLifetimeBoundAttr(QualType &CurType, + const ParsedAttr &Attr, + Sema &S, Declarator &D) { + if (D.isDeclarationOfFunction()) { + CurType = S.Context.getAttributedType(AttributedType::attr_lifetimebound, + CurType, CurType); + } else { + Attr.diagnoseAppertainsTo(S, nullptr); + } +} + + static void processTypeAttrs(TypeProcessingState &state, QualType &type, TypeAttrLocation TAL, ParsedAttributesView &attrs) { @@ -7298,6 +7312,13 @@ static void processTypeAttrs(TypeProcessingState &state, QualType &type, HandleOpenCLAccessAttr(type, attr, state.getSema()); attr.setUsedAsTypeAttr(); break; + case ParsedAttr::AT_LifetimeBound: + if (TAL == TAL_DeclChunk) { + HandleLifetimeBoundAttr(type, attr, state.getSema(), + state.getDeclarator()); + attr.setUsedAsTypeAttr(); + } + break; MS_TYPE_ATTRS_CASELIST: if (!handleMSPointerTypeQualifierAttr(state, attr, type)) @@ -7972,7 +7993,7 @@ static QualType getDecltypeForExpr(Sema &S, Expr *E) { } else if (auto *PE = dyn_cast<PredefinedExpr>(E)) { return PE->getType(); } - + // C++11 [expr.lambda.prim]p18: // Every occurrence of decltype((x)) where x is a possibly // parenthesized id-expression that names an entity of automatic diff --git a/lib/Sema/TreeTransform.h b/lib/Sema/TreeTransform.h index 3b3953991000..de962d775d73 100644 --- a/lib/Sema/TreeTransform.h +++ b/lib/Sema/TreeTransform.h @@ -1815,7 +1815,7 @@ public: OMPClause *RebuildOMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { - return getSema().ActOnOpenMPNumTeamsClause(NumTeams, StartLoc, LParenLoc, + return getSema().ActOnOpenMPNumTeamsClause(NumTeams, StartLoc, LParenLoc, EndLoc); } @@ -3033,7 +3033,7 @@ public: Sel, Method, LBracLoc, SelectorLocs, RBracLoc, Args); - + } /// Build a new Objective-C ivar reference expression. @@ -6356,7 +6356,7 @@ TreeTransform<Derived>::TransformObjCObjectType(TypeLocBuilder &TLB, TypeLocBuilder TypeArgBuilder; TypeArgBuilder.reserve(PatternLoc.getFullDataSize()); - QualType NewPatternType = getDerived().TransformType(TypeArgBuilder, + QualType NewPatternType = getDerived().TransformType(TypeArgBuilder, PatternLoc); if (NewPatternType.isNull()) return QualType(); @@ -10963,7 +10963,7 @@ TreeTransform<Derived>::TransformLambdaExpr(LambdaExpr *E) { TypeSourceInfo *NewCallOpTSI = nullptr; { TypeSourceInfo *OldCallOpTSI = E->getCallOperator()->getTypeSourceInfo(); - FunctionProtoTypeLoc OldCallOpFPTL = + FunctionProtoTypeLoc OldCallOpFPTL = OldCallOpTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>(); TypeLocBuilder NewCallOpTLBuilder; @@ -11059,7 +11059,7 @@ TreeTransform<Derived>::TransformLambdaExpr(LambdaExpr *E) { // Rebuild init-captures, including the implied field declaration. if (E->isInitCapture(C)) { - InitCaptureInfoTy InitExprTypePair = + InitCaptureInfoTy InitExprTypePair = InitCaptureExprsAndTypes[C - E->capture_begin()]; ExprResult Init = InitExprTypePair.first; QualType InitQualType = InitExprTypePair.second; diff --git a/lib/Sema/TypeLocBuilder.h b/lib/Sema/TypeLocBuilder.h index a088fe9de667..536ea1c07f49 100644 --- a/lib/Sema/TypeLocBuilder.h +++ b/lib/Sema/TypeLocBuilder.h @@ -37,7 +37,7 @@ class TypeLocBuilder { /// The last type pushed on this builder. QualType LastTy; #endif - + /// The inline buffer. enum { BufferMaxAlignment = alignof(void *) }; llvm::AlignedCharArray<BufferMaxAlignment, InlineCapacity> InlineBuffer; @@ -81,7 +81,7 @@ class TypeLocBuilder { #endif Index = Capacity; NumBytesAtAlign4 = NumBytesAtAlign8 = 0; - } + } /// Tell the TypeLocBuilder that the type it is storing has been /// modified in some safe way that doesn't affect type-location information. @@ -90,7 +90,7 @@ class TypeLocBuilder { LastTy = T; #endif } - + /// Pushes space for a new TypeLoc of the given type. Invalidates /// any TypeLocs previously retrieved from this builder. template <class TyLocType> TyLocType push(QualType T) { @@ -112,13 +112,13 @@ class TypeLocBuilder { return DI; } - /// Copies the type-location information to the given AST context and + /// Copies the type-location information to the given AST context and /// returns a \c TypeLoc referring into the AST context. TypeLoc getTypeLocInContext(ASTContext &Context, QualType T) { #ifndef NDEBUG assert(T == LastTy && "type doesn't match last type pushed!"); #endif - + size_t FullDataSize = Capacity - Index; void *Mem = Context.Allocate(FullDataSize); memcpy(Mem, &Buffer[Index], FullDataSize); @@ -135,7 +135,7 @@ private: /// Retrieve a temporary TypeLoc that refers into this \c TypeLocBuilder /// object. /// - /// The resulting \c TypeLoc should only be used so long as the + /// The resulting \c TypeLoc should only be used so long as the /// \c TypeLocBuilder is active and has not had more type information /// pushed into it. TypeLoc getTemporaryTypeLoc(QualType T) { diff --git a/lib/Serialization/ASTReader.cpp b/lib/Serialization/ASTReader.cpp index 9a3b9e1da39a..723839ff62bf 100644 --- a/lib/Serialization/ASTReader.cpp +++ b/lib/Serialization/ASTReader.cpp @@ -2632,7 +2632,9 @@ ASTReader::ReadControlBlock(ModuleFile &F, if (M && M->Directory) { // If we're implicitly loading a module, the base directory can't // change between the build and use. - if (F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) { + // Don't emit module relocation error if we have -fno-validate-pch + if (!PP.getPreprocessorOpts().DisablePCHValidation && + F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) { const DirectoryEntry *BuildDir = PP.getFileManager().getDirectory(Blob); if (!BuildDir || BuildDir != M->Directory) { @@ -3602,7 +3604,8 @@ ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F, Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName); auto &Map = PP.getHeaderSearchInfo().getModuleMap(); const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr; - if (!ModMap) { + // Don't emit module relocation error if we have -fno-validate-pch + if (!PP.getPreprocessorOpts().DisablePCHValidation && !ModMap) { assert(ImportedBy && "top-level import should be verified"); if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) { if (auto *ASTFE = M ? M->getASTFile() : nullptr) { @@ -5039,7 +5042,9 @@ ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) { if (!ParentModule) { if (const FileEntry *CurFile = CurrentModule->getASTFile()) { - if (CurFile != F.File) { + // Don't emit module relocation error if we have -fno-validate-pch + if (!PP.getPreprocessorOpts().DisablePCHValidation && + CurFile != F.File) { if (!Diags.isDiagnosticInFlight()) { Diag(diag::err_module_file_conflict) << CurrentModule->getTopLevelModuleName() @@ -6032,7 +6037,7 @@ QualType ASTReader::readTypeRecord(unsigned Index) { } QualType ResultType = readType(*Loc.F, Record, Idx); FunctionType::ExtInfo Info(Record[1], Record[2], Record[3], - (CallingConv)Record[4], Record[5], Record[6], + (CallingConv)Record[4], Record[5], Record[6], Record[7]); return Context.getFunctionNoProtoType(ResultType, Info); } diff --git a/lib/Serialization/ASTReaderDecl.cpp b/lib/Serialization/ASTReaderDecl.cpp index 7e2c4829b14c..ad37a2978df1 100644 --- a/lib/Serialization/ASTReaderDecl.cpp +++ b/lib/Serialization/ASTReaderDecl.cpp @@ -569,7 +569,7 @@ void ASTDeclReader::VisitDecl(Decl *D) { Reader.addPendingDeclContextInfo(D, SemaDCIDForTemplateParmDecl, LexicalDCIDForTemplateParmDecl); - D->setDeclContext(Reader.getContext().getTranslationUnitDecl()); + D->setDeclContext(Reader.getContext().getTranslationUnitDecl()); } else { auto *SemaDC = ReadDeclAs<DeclContext>(); auto *LexicalDC = ReadDeclAs<DeclContext>(); @@ -701,7 +701,7 @@ void ASTDeclReader::VisitTypeAliasDecl(TypeAliasDecl *TD) { ASTDeclReader::RedeclarableResult ASTDeclReader::VisitTagDecl(TagDecl *TD) { RedeclarableResult Redecl = VisitRedeclarable(TD); VisitTypeDecl(TD); - + TD->IdentifierNamespace = Record.readInt(); TD->setTagKind((TagDecl::TagKind)Record.readInt()); if (!isa<CXXRecordDecl>(TD)) @@ -710,7 +710,7 @@ ASTDeclReader::RedeclarableResult ASTDeclReader::VisitTagDecl(TagDecl *TD) { TD->setFreeStanding(Record.readInt()); TD->setCompleteDefinitionRequired(Record.readInt()); TD->setBraceRange(ReadSourceRange()); - + switch (Record.readInt()) { case 0: break; @@ -1717,7 +1717,7 @@ void ASTDeclReader::ReadCXXDefinitionData( bool IsImplicit = Record.readInt(); auto Kind = static_cast<LambdaCaptureKind>(Record.readInt()); switch (Kind) { - case LCK_StarThis: + case LCK_StarThis: case LCK_This: case LCK_VLAType: *ToCapture++ = Capture(Loc, IsImplicit, Kind, nullptr,SourceLocation()); @@ -2691,8 +2691,8 @@ static bool isConsumerInterestedIn(ASTContext &Ctx, Decl *D, bool HasBody) { return false; } - if (isa<FileScopeAsmDecl>(D) || - isa<ObjCProtocolDecl>(D) || + if (isa<FileScopeAsmDecl>(D) || + isa<ObjCProtocolDecl>(D) || isa<ObjCImplDecl>(D) || isa<ImportDecl>(D) || isa<PragmaCommentDecl>(D) || @@ -3274,7 +3274,7 @@ ASTDeclReader::FindExistingResult ASTDeclReader::findExisting(NamedDecl *D) { } } UpToDate(Name.getAsIdentifierInfo()); - for (IdentifierResolver::iterator I = IdResolver.begin(Name), + for (IdentifierResolver::iterator I = IdResolver.begin(Name), IEnd = IdResolver.end(); I != IEnd; ++I) { if (NamedDecl *Existing = getDeclForMerging(*I, TypedefNameForLinkage)) @@ -3439,22 +3439,16 @@ static void inheritDefaultTemplateArguments(ASTContext &Context, assert(FromTP->size() == ToTP->size() && "merged mismatched templates?"); for (unsigned I = 0, N = FromTP->size(); I != N; ++I) { - NamedDecl *FromParam = FromTP->getParam(N - I - 1); - if (FromParam->isParameterPack()) - continue; - NamedDecl *ToParam = ToTP->getParam(N - I - 1); + NamedDecl *FromParam = FromTP->getParam(I); + NamedDecl *ToParam = ToTP->getParam(I); - if (auto *FTTP = dyn_cast<TemplateTypeParmDecl>(FromParam)) { - if (!inheritDefaultTemplateArgument(Context, FTTP, ToParam)) - break; - } else if (auto *FNTTP = dyn_cast<NonTypeTemplateParmDecl>(FromParam)) { - if (!inheritDefaultTemplateArgument(Context, FNTTP, ToParam)) - break; - } else { - if (!inheritDefaultTemplateArgument( - Context, cast<TemplateTemplateParmDecl>(FromParam), ToParam)) - break; - } + if (auto *FTTP = dyn_cast<TemplateTypeParmDecl>(FromParam)) + inheritDefaultTemplateArgument(Context, FTTP, ToParam); + else if (auto *FNTTP = dyn_cast<NonTypeTemplateParmDecl>(FromParam)) + inheritDefaultTemplateArgument(Context, FNTTP, ToParam); + else + inheritDefaultTemplateArgument( + Context, cast<TemplateTemplateParmDecl>(FromParam), ToParam); } } @@ -3759,7 +3753,7 @@ Decl *ASTReader::ReadDeclRecord(DeclID ID) { Error("attempt to read a C++ ctor initializer record as a declaration"); return nullptr; case DECL_IMPORT: - // Note: last entry of the ImportDecl record is the number of stored source + // Note: last entry of the ImportDecl record is the number of stored source // locations. D = ImportDecl::CreateDeserialized(Context, ID, Record.back()); break; @@ -3819,7 +3813,7 @@ Decl *ASTReader::ReadDeclRecord(DeclID ID) { if (Class->isThisDeclarationADefinition() || PendingDefinitions.count(Class)) loadObjCCategories(ID, Class); - + // If we have deserialized a declaration that has a definition the // AST consumer might need to know about, queue it. // We don't pass it to the consumer immediately because we may be in recursive @@ -3981,17 +3975,17 @@ namespace { llvm::DenseMap<DeclarationName, ObjCCategoryDecl *> NameCategoryMap; serialization::GlobalDeclID InterfaceID; unsigned PreviousGeneration; - + void add(ObjCCategoryDecl *Cat) { // Only process each category once. if (!Deserialized.erase(Cat)) return; - + // Check for duplicate categories. if (Cat->getDeclName()) { ObjCCategoryDecl *&Existing = NameCategoryMap[Cat->getDeclName()]; - if (Existing && - Reader.getOwningModuleFile(Existing) + if (Existing && + Reader.getOwningModuleFile(Existing) != Reader.getOwningModuleFile(Cat)) { // FIXME: We should not warn for duplicates in diamond: // @@ -4001,8 +3995,8 @@ namespace { // \ / // // MB // // - // If there are duplicates in ML/MR, there will be warning when - // creating MB *and* when importing MB. We should not warn when + // If there are duplicates in ML/MR, there will be warning when + // creating MB *and* when importing MB. We should not warn when // importing. Reader.Diag(Cat->getLocation(), diag::warn_dup_category_def) << Interface->getDeclName() << Cat->getDeclName(); @@ -4012,7 +4006,7 @@ namespace { Existing = Cat; } } - + // Add this category to the end of the chain. if (Tail) ASTDeclReader::setNextObjCCategory(Tail, Cat); @@ -4020,7 +4014,7 @@ namespace { Interface->setCategoryListRaw(Cat); Tail = Cat; } - + public: ObjCCategoriesVisitor(ASTReader &Reader, ObjCInterfaceDecl *Interface, @@ -4033,7 +4027,7 @@ namespace { for (auto *Cat : Interface->known_categories()) { if (Cat->getDeclName()) NameCategoryMap[Cat->getDeclName()] = Cat; - + // Keep track of the tail of the category list. Tail = Cat; } @@ -4044,8 +4038,8 @@ namespace { // this module file, we're done. if (M.Generation <= PreviousGeneration) return true; - - // Map global ID of the definition down to the local ID used in this + + // Map global ID of the definition down to the local ID used in this // module file. If there is no such mapping, we'll find nothing here // (or in any module it imports). DeclID LocalID = Reader.mapGlobalIDToModuleFileGlobalID(M, InterfaceID); @@ -4057,7 +4051,7 @@ namespace { const ObjCCategoriesInfo Compare = { LocalID, 0 }; const ObjCCategoriesInfo *Result = std::lower_bound(M.ObjCCategoriesMap, - M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap, + M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap, Compare); if (Result == M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap || Result->DefinitionID != LocalID) { @@ -4066,7 +4060,7 @@ namespace { // so suppress further lookup. return Reader.isDeclIDFromModule(InterfaceID, M); } - + // We found something. Dig out all of the categories. unsigned Offset = Result->Offset; unsigned N = M.ObjCCategories[Offset]; diff --git a/lib/Serialization/ASTReaderInternals.h b/lib/Serialization/ASTReaderInternals.h index b5a1493a4f7e..37a929907dca 100644 --- a/lib/Serialization/ASTReaderInternals.h +++ b/lib/Serialization/ASTReaderInternals.h @@ -33,7 +33,7 @@ struct HeaderFileInfo; class HeaderSearch; class IdentifierTable; class ObjCMethodDecl; - + namespace serialization { class ModuleFile; @@ -45,7 +45,7 @@ namespace reader { class ASTDeclContextNameLookupTrait { ASTReader &Reader; ModuleFile &F; - + public: // Maximum number of lookup tables we allow before condensing the tables. static const int MaxTables = 4; @@ -141,31 +141,31 @@ public: } static hash_value_type ComputeHash(const internal_key_type& a); - + static std::pair<unsigned, unsigned> ReadKeyDataLength(const unsigned char*& d); // This hopefully will just get inlined and removed by the optimizer. static const internal_key_type& GetInternalKey(const external_key_type& x) { return x; } - + // This hopefully will just get inlined and removed by the optimizer. static const external_key_type& GetExternalKey(const internal_key_type& x) { return x; } - static internal_key_type ReadKey(const unsigned char* d, unsigned n); + static internal_key_type ReadKey(const unsigned char* d, unsigned n); }; /// Class that performs lookup for an identifier stored in an AST file. class ASTIdentifierLookupTrait : public ASTIdentifierLookupTraitBase { ASTReader &Reader; ModuleFile &F; - + // If we know the IdentifierInfo in advance, it is here and we will // not build a new one. Used when deserializing information about an // identifier that was constructed before the AST file was read. IdentifierInfo *KnownII; - + public: using data_type = IdentifierInfo *; @@ -176,12 +176,12 @@ public: data_type ReadData(const internal_key_type& k, const unsigned char* d, unsigned DataLen); - + IdentID ReadIdentifierID(const unsigned char *d); ASTReader &getReader() const { return Reader; } }; - + /// The on-disk hash table used to contain information about /// all of the identifiers in the program. using ASTIdentifierLookupTable = @@ -192,7 +192,7 @@ using ASTIdentifierLookupTable = class ASTSelectorLookupTrait { ASTReader &Reader; ModuleFile &F; - + public: struct data_type { SelectorID ID; @@ -203,40 +203,40 @@ public: SmallVector<ObjCMethodDecl *, 2> Instance; SmallVector<ObjCMethodDecl *, 2> Factory; }; - + using external_key_type = Selector; using internal_key_type = external_key_type; using hash_value_type = unsigned; using offset_type = unsigned; - + ASTSelectorLookupTrait(ASTReader &Reader, ModuleFile &F) : Reader(Reader), F(F) {} - + static bool EqualKey(const internal_key_type& a, const internal_key_type& b) { return a == b; } - + static hash_value_type ComputeHash(Selector Sel); - + static const internal_key_type& GetInternalKey(const external_key_type& x) { return x; } - + static std::pair<unsigned, unsigned> ReadKeyDataLength(const unsigned char*& d); - + internal_key_type ReadKey(const unsigned char* d, unsigned); data_type ReadData(Selector, const unsigned char* d, unsigned DataLen); }; - + /// The on-disk hash table used for the global method pool. using ASTSelectorLookupTable = llvm::OnDiskChainedHashTable<ASTSelectorLookupTrait>; - + /// Trait class used to search the on-disk hash table containing all of /// the header search information. /// -/// The on-disk hash table contains a mapping from each header path to +/// The on-disk hash table contains a mapping from each header path to /// information about that header (how many times it has been included, its /// controlling macro, etc.). Note that we actually hash based on the size /// and mtime, and support "deep" comparisons of file names based on current @@ -259,31 +259,31 @@ public: }; using internal_key_ref = const internal_key_type &; - + using data_type = HeaderFileInfo; using hash_value_type = unsigned; using offset_type = unsigned; - + HeaderFileInfoTrait(ASTReader &Reader, ModuleFile &M, HeaderSearch *HS, const char *FrameworkStrings) : Reader(Reader), M(M), HS(HS), FrameworkStrings(FrameworkStrings) {} - + static hash_value_type ComputeHash(internal_key_ref ikey); internal_key_type GetInternalKey(const FileEntry *FE); bool EqualKey(internal_key_ref a, internal_key_ref b); - + static std::pair<unsigned, unsigned> ReadKeyDataLength(const unsigned char*& d); - + static internal_key_type ReadKey(const unsigned char *d, unsigned); - + data_type ReadData(internal_key_ref,const unsigned char *d, unsigned DataLen); }; /// The on-disk hash table used for known header files. using HeaderFileInfoLookupTable = llvm::OnDiskChainedHashTable<HeaderFileInfoTrait>; - + } // namespace reader } // namespace serialization diff --git a/lib/Serialization/ASTWriterDecl.cpp b/lib/Serialization/ASTWriterDecl.cpp index 77e578f6bc57..7286f2cac178 100644 --- a/lib/Serialization/ASTWriterDecl.cpp +++ b/lib/Serialization/ASTWriterDecl.cpp @@ -271,7 +271,7 @@ void ASTDeclWriter::Visit(Decl *D) { // Handle FunctionDecl's body here and write it after all other Stmts/Exprs // have been written. We want it last because we will not read it back when - // retrieving it from the AST, we'll just lazily set the offset. + // retrieving it from the AST, we'll just lazily set the offset. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { Record.push_back(FD->doesThisDeclarationHaveABody()); if (FD->doesThisDeclarationHaveABody()) @@ -526,10 +526,10 @@ void ASTDeclWriter::VisitFunctionDecl(FunctionDecl *D) { VisitDeclaratorDecl(D); Record.AddDeclarationNameLoc(D->DNLoc, D->getDeclName()); Record.push_back(D->getIdentifierNamespace()); - + // FunctionDecl's body is handled last at ASTWriterDecl::Visit, // after everything else is written. - + Record.push_back((int)D->SClass); // FIXME: stable encoding Record.push_back(D->IsInline); Record.push_back(D->IsInlineSpecified); @@ -576,10 +576,10 @@ void ASTDeclWriter::VisitFunctionDecl(FunctionDecl *D) { Record.AddDeclRef(FTSInfo->getTemplate()); Record.push_back(FTSInfo->getTemplateSpecializationKind()); - + // Template arguments. Record.AddTemplateArgumentList(FTSInfo->TemplateArguments); - + // Template args as written. Record.push_back(FTSInfo->TemplateArgumentsAsWritten != nullptr); if (FTSInfo->TemplateArgumentsAsWritten) { @@ -591,7 +591,7 @@ void ASTDeclWriter::VisitFunctionDecl(FunctionDecl *D) { Record.AddSourceLocation(FTSInfo->TemplateArgumentsAsWritten->LAngleLoc); Record.AddSourceLocation(FTSInfo->TemplateArgumentsAsWritten->RAngleLoc); } - + Record.AddSourceLocation(FTSInfo->getPointOfInstantiation()); if (D->isCanonicalDecl()) { @@ -604,12 +604,12 @@ void ASTDeclWriter::VisitFunctionDecl(FunctionDecl *D) { case FunctionDecl::TK_DependentFunctionTemplateSpecialization: { DependentFunctionTemplateSpecializationInfo * DFTSInfo = D->getDependentSpecializationInfo(); - + // Templates. Record.push_back(DFTSInfo->getNumTemplates()); for (int i=0, e = DFTSInfo->getNumTemplates(); i != e; ++i) Record.AddDeclRef(DFTSInfo->getTemplate(i)); - + // Templates args. Record.push_back(DFTSInfo->getNumTemplateArgs()); for (int i=0, e = DFTSInfo->getNumTemplateArgs(); i != e; ++i) @@ -707,7 +707,7 @@ void ASTDeclWriter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) { if (D->isThisDeclarationADefinition()) { // Write the DefinitionData ObjCInterfaceDecl::DefinitionData &Data = D->data(); - + Record.AddTypeSourceInfo(D->getSuperClassTInfo()); Record.AddSourceLocation(D->getEndOfDefinitionLoc()); Record.push_back(Data.HasDesignatedInitializers); @@ -718,7 +718,7 @@ void ASTDeclWriter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) { Record.AddDeclRef(P); for (const auto &PL : D->protocol_locs()) Record.AddSourceLocation(PL); - + // Write out the protocols that are transitively referenced. Record.push_back(Data.AllReferencedProtocols.size()); for (ObjCList<ObjCProtocolDecl>::iterator @@ -727,17 +727,17 @@ void ASTDeclWriter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) { P != PEnd; ++P) Record.AddDeclRef(*P); - + if (ObjCCategoryDecl *Cat = D->getCategoryListRaw()) { // Ensure that we write out the set of categories for this class. Writer.ObjCClassesWithCategories.insert(D); - + // Make sure that the categories get serialized. for (; Cat; Cat = Cat->getNextClassCategoryRaw()) (void)Writer.GetDeclRef(Cat); } - } - + } + Code = serialization::DECL_OBJC_INTERFACE; } @@ -765,7 +765,7 @@ void ASTDeclWriter::VisitObjCIvarDecl(ObjCIvarDecl *D) { void ASTDeclWriter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) { VisitRedeclarable(D); VisitObjCContainerDecl(D); - + Record.push_back(D->isThisDeclarationADefinition()); if (D->isThisDeclarationADefinition()) { Record.push_back(D->protocol_size()); @@ -774,7 +774,7 @@ void ASTDeclWriter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) { for (const auto &PL : D->protocol_locs()) Record.AddSourceLocation(PL); } - + Code = serialization::DECL_OBJC_PROTOCOL; } @@ -964,7 +964,7 @@ void ASTDeclWriter::VisitVarDecl(VarDecl *D) { if (ModulesCodegen) Writer.ModularCodegenDecls.push_back(Writer.GetDeclRef(D)); } - + enum { VarNotTemplate = 0, VarTemplate, StaticDataMemberSpecialization }; @@ -1158,7 +1158,7 @@ void ASTDeclWriter::VisitNamespaceDecl(NamespaceDecl *D) { Record.AddDeclRef(D->getAnonymousNamespace()); Code = serialization::DECL_NAMESPACE; - if (Writer.hasChain() && D->isAnonymousNamespace() && + if (Writer.hasChain() && D->isAnonymousNamespace() && D == D->getMostRecentDecl()) { // This is a most recent reopening of the anonymous namespace. If its parent // is in a previous PCH (or is the TU), mark that parent for update, because @@ -1412,7 +1412,7 @@ void ASTDeclWriter::VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D) { if (D->getInstantiatedFromMemberTemplate()) Record.push_back(D->isMemberSpecialization()); } - + VisitTemplateDecl(D); Record.push_back(D->getIdentifierNamespace()); } @@ -1447,7 +1447,7 @@ void ASTDeclWriter::VisitClassTemplateSpecializationDecl( Record.push_back(D->isCanonicalDecl()); if (D->isCanonicalDecl()) { - // When reading, we'll add it to the folding set of the following template. + // When reading, we'll add it to the folding set of the following template. Record.AddDeclRef(D->getSpecializedTemplate()->getCanonicalDecl()); } @@ -1573,18 +1573,18 @@ void ASTDeclWriter::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) { // memory. if (D->isExpandedParameterPack()) Record.push_back(D->getNumExpansionTypes()); - + VisitDeclaratorDecl(D); // TemplateParmPosition. Record.push_back(D->getDepth()); Record.push_back(D->getPosition()); - + if (D->isExpandedParameterPack()) { for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) { Record.AddTypeRef(D->getExpansionType(I)); Record.AddTypeSourceInfo(D->getExpansionTypeSourceInfo(I)); } - + Code = serialization::DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK; } else { // Rest of NonTypeTemplateParmDecl. @@ -1709,7 +1709,7 @@ void ASTDeclWriter::VisitRedeclarable(Redeclarable<T> *D) { Record.AddDeclRef(FirstLocal); } - // Make sure that we serialize both the previous and the most-recent + // Make sure that we serialize both the previous and the most-recent // declarations, which (transitively) ensures that all declarations in the // chain get serialized. // @@ -2252,11 +2252,11 @@ void ASTWriter::WriteDecl(ASTContext &Context, Decl *D) { serialization::DeclID &IDR = DeclIDs[D]; if (IDR == 0) IDR = NextDeclID++; - + ID = IDR; assert(ID >= FirstDeclID && "invalid decl ID"); - + RecordData Record; ASTDeclWriter W(*this, Context, Record); diff --git a/lib/Serialization/ASTWriterStmt.cpp b/lib/Serialization/ASTWriterStmt.cpp index 3efb6482dd42..48c3f79a4380 100644 --- a/lib/Serialization/ASTWriterStmt.cpp +++ b/lib/Serialization/ASTWriterStmt.cpp @@ -247,7 +247,7 @@ void ASTStmtWriter::VisitGCCAsmStmt(GCCAsmStmt *S) { Record.AddStmt(S->getAsmString()); // Outputs - for (unsigned I = 0, N = S->getNumOutputs(); I != N; ++I) { + for (unsigned I = 0, N = S->getNumOutputs(); I != N; ++I) { Record.AddIdentifierRef(S->getOutputIdentifier(I)); Record.AddStmt(S->getOutputConstraintLiteral(I)); Record.AddStmt(S->getOutputExpr(I)); @@ -1000,7 +1000,7 @@ void ASTStmtWriter::VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) { Record.push_back(NumExpansions); } } - + Record.AddDeclRef(E->getDictWithObjectsMethod()); Record.AddSourceRange(E->getSourceRange()); Code = serialization::EXPR_OBJC_DICTIONARY_LITERAL; @@ -1064,7 +1064,7 @@ void ASTStmtWriter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) { Record.push_back(2); Record.AddDeclRef(E->getClassReceiver()); } - + Code = serialization::EXPR_OBJC_PROPERTY_REF_EXPR; } @@ -1075,7 +1075,7 @@ void ASTStmtWriter::VisitObjCSubscriptRefExpr(ObjCSubscriptRefExpr *E) { Record.AddStmt(E->getKeyExpr()); Record.AddDeclRef(E->getAtIndexMethodDecl()); Record.AddDeclRef(E->setAtIndexMethodDecl()); - + Code = serialization::EXPR_OBJC_SUBSCRIPT_REF_EXPR; } @@ -1108,9 +1108,9 @@ void ASTStmtWriter::VisitObjCMessageExpr(ObjCMessageExpr *E) { Record.AddDeclRef(E->getMethodDecl()); } else { Record.push_back(0); - Record.AddSelectorRef(E->getSelector()); + Record.AddSelectorRef(E->getSelector()); } - + Record.AddSourceLocation(E->getLeftLoc()); Record.AddSourceLocation(E->getRightLoc()); @@ -1296,14 +1296,14 @@ void ASTStmtWriter::VisitLambdaExpr(LambdaExpr *E) { Record.push_back(E->ExplicitParams); Record.push_back(E->ExplicitResultType); Record.AddSourceLocation(E->ClosingBrace); - + // Add capture initializers. for (LambdaExpr::capture_init_iterator C = E->capture_init_begin(), CEnd = E->capture_init_end(); C != CEnd; ++C) { Record.AddStmt(*C); } - + Code = serialization::EXPR_LAMBDA; } @@ -1450,7 +1450,7 @@ void ASTStmtWriter::VisitCXXDeleteExpr(CXXDeleteExpr *E) { Record.AddDeclRef(E->getOperatorDelete()); Record.AddStmt(E->getArgument()); Record.AddSourceLocation(E->getSourceRange().getBegin()); - + Code = serialization::EXPR_CXX_DELETE; } @@ -2691,7 +2691,7 @@ void ASTWriter::WriteSubStmt(Stmt *S) { RecordData Record; ASTStmtWriter Writer(*this, Record); ++NumStatements; - + if (!S) { Stream.EmitRecord(serialization::STMT_NULL_PTR, Record); return; @@ -2724,7 +2724,7 @@ void ASTWriter::WriteSubStmt(Stmt *S) { #endif Writer.Visit(S); - + uint64_t Offset = Writer.Emit(); SubStmtEntries[S] = Offset; } @@ -2739,7 +2739,7 @@ void ASTRecordWriter::FlushStmts() { for (unsigned I = 0, N = StmtsToEmit.size(); I != N; ++I) { Writer->WriteSubStmt(StmtsToEmit[I]); - + assert(N == StmtsToEmit.size() && "record modified while being written!"); // Note that we are at the end of a full expression. Any diff --git a/lib/Serialization/Module.cpp b/lib/Serialization/Module.cpp index f0ada809ad99..580e46e4f240 100644 --- a/lib/Serialization/Module.cpp +++ b/lib/Serialization/Module.cpp @@ -30,16 +30,16 @@ ModuleFile::~ModuleFile() { } template<typename Key, typename Offset, unsigned InitialCapacity> -static void +static void dumpLocalRemap(StringRef Name, const ContinuousRangeMap<Key, Offset, InitialCapacity> &Map) { if (Map.begin() == Map.end()) return; - + using MapType = ContinuousRangeMap<Key, Offset, InitialCapacity>; llvm::errs() << " " << Name << ":\n"; - for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end(); + for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end(); I != IEnd; ++I) { llvm::errs() << " " << I->first << " -> " << I->second << "\n"; } @@ -56,12 +56,12 @@ LLVM_DUMP_METHOD void ModuleFile::dump() { } llvm::errs() << "\n"; } - + // Remapping tables. - llvm::errs() << " Base source location offset: " << SLocEntryBaseOffset + llvm::errs() << " Base source location offset: " << SLocEntryBaseOffset << '\n'; dumpLocalRemap("Source location offset local -> global map", SLocRemap); - + llvm::errs() << " Base identifier ID: " << BaseIdentifierID << '\n' << " Number of identifiers: " << LocalNumIdentifiers << '\n'; dumpLocalRemap("Identifier ID local -> global map", IdentifierRemap); @@ -77,18 +77,18 @@ LLVM_DUMP_METHOD void ModuleFile::dump() { llvm::errs() << " Base selector ID: " << BaseSelectorID << '\n' << " Number of selectors: " << LocalNumSelectors << '\n'; dumpLocalRemap("Selector ID local -> global map", SelectorRemap); - + llvm::errs() << " Base preprocessed entity ID: " << BasePreprocessedEntityID - << '\n' - << " Number of preprocessed entities: " + << '\n' + << " Number of preprocessed entities: " << NumPreprocessedEntities << '\n'; - dumpLocalRemap("Preprocessed entity ID local -> global map", + dumpLocalRemap("Preprocessed entity ID local -> global map", PreprocessedEntityRemap); - + llvm::errs() << " Base type index: " << BaseTypeIndex << '\n' << " Number of types: " << LocalNumTypes << '\n'; dumpLocalRemap("Type index local -> global map", TypeRemap); - + llvm::errs() << " Base decl ID: " << BaseDeclID << '\n' << " Number of decls: " << LocalNumDecls << '\n'; dumpLocalRemap("Decl ID local -> global map", DeclRemap); diff --git a/lib/Serialization/ModuleManager.cpp b/lib/Serialization/ModuleManager.cpp index b512fa452cc1..57ebaca10c99 100644 --- a/lib/Serialization/ModuleManager.cpp +++ b/lib/Serialization/ModuleManager.cpp @@ -340,7 +340,7 @@ void ModuleManager::visit(llvm::function_ref<bool(ModuleFile &M)> Visitor, unsigned N = size(); VisitOrder.clear(); VisitOrder.reserve(N); - + // Record the number of incoming edges for each module. When we // encounter a module with no incoming edges, push it into the queue // to seed the queue. @@ -477,21 +477,21 @@ namespace llvm { static ChildIteratorType child_end(NodeRef Node) { return Node->Imports.end(); } - + static nodes_iterator nodes_begin(const ModuleManager &Manager) { return nodes_iterator(Manager.begin()); } - + static nodes_iterator nodes_end(const ModuleManager &Manager) { return nodes_iterator(Manager.end()); } }; - + template<> struct DOTGraphTraits<ModuleManager> : public DefaultDOTGraphTraits { explicit DOTGraphTraits(bool IsSimple = false) : DefaultDOTGraphTraits(IsSimple) {} - + static bool renderGraphFromBottomUp() { return true; } std::string getNodeLabel(ModuleFile *M, const ModuleManager&) { diff --git a/lib/StaticAnalyzer/Checkers/CStringChecker.cpp b/lib/StaticAnalyzer/Checkers/CStringChecker.cpp index 278452ec994a..12a576e5d80d 100644 --- a/lib/StaticAnalyzer/Checkers/CStringChecker.cpp +++ b/lib/StaticAnalyzer/Checkers/CStringChecker.cpp @@ -552,6 +552,7 @@ void CStringChecker::emitNullArgBug(CheckerContext &C, ProgramStateRef State, BuiltinBug *BT = static_cast<BuiltinBug *>(BT_Null.get()); auto Report = llvm::make_unique<BugReport>(*BT, WarningMsg, N); + Report->addRange(S->getSourceRange()); bugreporter::trackNullOrUndefValue(N, S, *Report); C.emitReport(std::move(Report)); } diff --git a/lib/StaticAnalyzer/Checkers/InnerPointerChecker.cpp b/lib/StaticAnalyzer/Checkers/InnerPointerChecker.cpp index ed877ab34518..29677f737f5c 100644 --- a/lib/StaticAnalyzer/Checkers/InnerPointerChecker.cpp +++ b/lib/StaticAnalyzer/Checkers/InnerPointerChecker.cpp @@ -91,37 +91,53 @@ public: ReserveFn("reserve"), ResizeFn("resize"), ShrinkToFitFn("shrink_to_fit"), SwapFn("swap") {} - /// Check whether the function called on the container object is a - /// member function that potentially invalidates pointers referring - /// to the objects's internal buffer. - bool mayInvalidateBuffer(const CallEvent &Call) const; - - /// Record the connection between the symbol returned by c_str() and the - /// corresponding string object region in the ProgramState. Mark the symbol - /// released if the string object is destroyed. + /// Check if the object of this member function call is a `basic_string`. + bool isCalledOnStringObject(const CXXInstanceCall *ICall) const; + + /// Check whether the called member function potentially invalidates + /// pointers referring to the container object's inner buffer. + bool isInvalidatingMemberFunction(const CallEvent &Call) const; + + /// Mark pointer symbols associated with the given memory region released + /// in the program state. + void markPtrSymbolsReleased(const CallEvent &Call, ProgramStateRef State, + const MemRegion *ObjRegion, + CheckerContext &C) const; + + /// Standard library functions that take a non-const `basic_string` argument by + /// reference may invalidate its inner pointers. Check for these cases and + /// mark the pointers released. + void checkFunctionArguments(const CallEvent &Call, ProgramStateRef State, + CheckerContext &C) const; + + /// Record the connection between raw pointers referring to a container + /// object's inner buffer and the object's memory region in the program state. + /// Mark potentially invalidated pointers released. void checkPostCall(const CallEvent &Call, CheckerContext &C) const; - /// Clean up the ProgramState map. + /// Clean up the program state map. void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const; }; } // end anonymous namespace -// [string.require] -// -// "References, pointers, and iterators referring to the elements of a -// basic_string sequence may be invalidated by the following uses of that -// basic_string object: -// -// -- TODO: As an argument to any standard library function taking a reference -// to non-const basic_string as an argument. For example, as an argument to -// non-member functions swap(), operator>>(), and getline(), or as an argument -// to basic_string::swap(). -// -// -- Calling non-const member functions, except operator[], at, front, back, -// begin, rbegin, end, and rend." -// -bool InnerPointerChecker::mayInvalidateBuffer(const CallEvent &Call) const { +bool InnerPointerChecker::isCalledOnStringObject( + const CXXInstanceCall *ICall) const { + const auto *ObjRegion = + dyn_cast_or_null<TypedValueRegion>(ICall->getCXXThisVal().getAsRegion()); + if (!ObjRegion) + return false; + + QualType ObjTy = ObjRegion->getValueType(); + if (ObjTy.isNull() || + ObjTy->getAsCXXRecordDecl()->getName() != "basic_string") + return false; + + return true; +} + +bool InnerPointerChecker::isInvalidatingMemberFunction( + const CallEvent &Call) const { if (const auto *MemOpCall = dyn_cast<CXXMemberOperatorCall>(&Call)) { OverloadedOperatorKind Opc = MemOpCall->getOriginExpr()->getOperator(); if (Opc == OO_Equal || Opc == OO_PlusEqual) @@ -137,53 +153,104 @@ bool InnerPointerChecker::mayInvalidateBuffer(const CallEvent &Call) const { Call.isCalled(SwapFn)); } -void InnerPointerChecker::checkPostCall(const CallEvent &Call, - CheckerContext &C) const { - const auto *ICall = dyn_cast<CXXInstanceCall>(&Call); - if (!ICall) +void InnerPointerChecker::markPtrSymbolsReleased(const CallEvent &Call, + ProgramStateRef State, + const MemRegion *MR, + CheckerContext &C) const { + if (const PtrSet *PS = State->get<RawPtrMap>(MR)) { + const Expr *Origin = Call.getOriginExpr(); + for (const auto Symbol : *PS) { + // NOTE: `Origin` may be null, and will be stored so in the symbol's + // `RefState` in MallocChecker's `RegionState` program state map. + State = allocation_state::markReleased(State, Symbol, Origin); + } + State = State->remove<RawPtrMap>(MR); + C.addTransition(State); return; + } +} - SVal Obj = ICall->getCXXThisVal(); - const auto *ObjRegion = dyn_cast_or_null<TypedValueRegion>(Obj.getAsRegion()); - if (!ObjRegion) - return; +void InnerPointerChecker::checkFunctionArguments(const CallEvent &Call, + ProgramStateRef State, + CheckerContext &C) const { + if (const auto *FC = dyn_cast<AnyFunctionCall>(&Call)) { + const FunctionDecl *FD = FC->getDecl(); + if (!FD || !FD->isInStdNamespace()) + return; - auto *TypeDecl = ObjRegion->getValueType()->getAsCXXRecordDecl(); - if (TypeDecl->getName() != "basic_string") - return; + for (unsigned I = 0, E = FD->getNumParams(); I != E; ++I) { + QualType ParamTy = FD->getParamDecl(I)->getType(); + if (!ParamTy->isReferenceType() || + ParamTy->getPointeeType().isConstQualified()) + continue; - ProgramStateRef State = C.getState(); + // In case of member operator calls, `this` is counted as an + // argument but not as a parameter. + bool isaMemberOpCall = isa<CXXMemberOperatorCall>(FC); + unsigned ArgI = isaMemberOpCall ? I+1 : I; - if (Call.isCalled(CStrFn) || Call.isCalled(DataFn)) { - SVal RawPtr = Call.getReturnValue(); - if (SymbolRef Sym = RawPtr.getAsSymbol(/*IncludeBaseRegions=*/true)) { - // Start tracking this raw pointer by adding it to the set of symbols - // associated with this container object in the program state map. - PtrSet::Factory &F = State->getStateManager().get_context<PtrSet>(); - const PtrSet *SetPtr = State->get<RawPtrMap>(ObjRegion); - PtrSet Set = SetPtr ? *SetPtr : F.getEmptySet(); - assert(C.wasInlined || !Set.contains(Sym)); - Set = F.add(Set, Sym); - State = State->set<RawPtrMap>(ObjRegion, Set); - C.addTransition(State); + SVal Arg = FC->getArgSVal(ArgI); + const auto *ArgRegion = + dyn_cast_or_null<TypedValueRegion>(Arg.getAsRegion()); + if (!ArgRegion) + continue; + + markPtrSymbolsReleased(Call, State, ArgRegion, C); } - return; } +} - if (mayInvalidateBuffer(Call)) { - if (const PtrSet *PS = State->get<RawPtrMap>(ObjRegion)) { - // Mark all pointer symbols associated with the deleted object released. - const Expr *Origin = Call.getOriginExpr(); - for (const auto Symbol : *PS) { - // NOTE: `Origin` may be null, and will be stored so in the symbol's - // `RefState` in MallocChecker's `RegionState` program state map. - State = allocation_state::markReleased(State, Symbol, Origin); +// [string.require] +// +// "References, pointers, and iterators referring to the elements of a +// basic_string sequence may be invalidated by the following uses of that +// basic_string object: +// +// -- As an argument to any standard library function taking a reference +// to non-const basic_string as an argument. For example, as an argument to +// non-member functions swap(), operator>>(), and getline(), or as an argument +// to basic_string::swap(). +// +// -- Calling non-const member functions, except operator[], at, front, back, +// begin, rbegin, end, and rend." + +void InnerPointerChecker::checkPostCall(const CallEvent &Call, + CheckerContext &C) const { + ProgramStateRef State = C.getState(); + + if (const auto *ICall = dyn_cast<CXXInstanceCall>(&Call)) { + if (isCalledOnStringObject(ICall)) { + const auto *ObjRegion = dyn_cast_or_null<TypedValueRegion>( + ICall->getCXXThisVal().getAsRegion()); + + if (Call.isCalled(CStrFn) || Call.isCalled(DataFn)) { + SVal RawPtr = Call.getReturnValue(); + if (SymbolRef Sym = RawPtr.getAsSymbol(/*IncludeBaseRegions=*/true)) { + // Start tracking this raw pointer by adding it to the set of symbols + // associated with this container object in the program state map. + + PtrSet::Factory &F = State->getStateManager().get_context<PtrSet>(); + const PtrSet *SetPtr = State->get<RawPtrMap>(ObjRegion); + PtrSet Set = SetPtr ? *SetPtr : F.getEmptySet(); + assert(C.wasInlined || !Set.contains(Sym)); + Set = F.add(Set, Sym); + + State = State->set<RawPtrMap>(ObjRegion, Set); + C.addTransition(State); + } + return; + } + + // Check [string.require] / second point. + if (isInvalidatingMemberFunction(Call)) { + markPtrSymbolsReleased(Call, State, ObjRegion, C); + return; } - State = State->remove<RawPtrMap>(ObjRegion); - C.addTransition(State); - return; } } + + // Check [string.require] / first point. + checkFunctionArguments(Call, State, C); } void InnerPointerChecker::checkDeadSymbols(SymbolReaper &SymReaper, @@ -216,7 +283,6 @@ InnerPointerChecker::InnerPointerBRVisitor::VisitNode(const ExplodedNode *N, const ExplodedNode *PrevN, BugReporterContext &BRC, BugReport &BR) { - if (!isSymbolTracked(N->getState(), PtrToBuf) || isSymbolTracked(PrevN->getState(), PtrToBuf)) return nullptr; diff --git a/lib/StaticAnalyzer/Checkers/IteratorChecker.cpp b/lib/StaticAnalyzer/Checkers/IteratorChecker.cpp index 56c250cd1678..520c32e1c770 100644 --- a/lib/StaticAnalyzer/Checkers/IteratorChecker.cpp +++ b/lib/StaticAnalyzer/Checkers/IteratorChecker.cpp @@ -291,6 +291,7 @@ const ContainerData *getContainerData(ProgramStateRef State, const MemRegion *Cont); ProgramStateRef setContainerData(ProgramStateRef State, const MemRegion *Cont, const ContainerData &CData); +bool hasLiveIterators(ProgramStateRef State, const MemRegion *Cont); bool isOutOfRange(ProgramStateRef State, const IteratorPosition &Pos); bool isZero(ProgramStateRef State, const NonLoc &Val); } // namespace @@ -536,7 +537,11 @@ void IteratorChecker::checkDeadSymbols(SymbolReaper &SR, auto ContMap = State->get<ContainerMap>(); for (const auto Cont : ContMap) { if (!SR.isLiveRegion(Cont.first)) { - State = State->remove<ContainerMap>(Cont.first); + // We must keep the container data while it has live iterators to be able + // to compare them to the begin and the end of the container. + if (!hasLiveIterators(State, Cont.first)) { + State = State->remove<ContainerMap>(Cont.first); + } } } @@ -546,6 +551,8 @@ void IteratorChecker::checkDeadSymbols(SymbolReaper &SR, State = State->remove<IteratorComparisonMap>(Comp.first); } } + + C.addTransition(State); } ProgramStateRef IteratorChecker::evalAssume(ProgramStateRef State, SVal Cond, @@ -1188,6 +1195,22 @@ ProgramStateRef relateIteratorPositions(ProgramStateRef State, return NewState; } +bool hasLiveIterators(ProgramStateRef State, const MemRegion *Cont) { + auto RegionMap = State->get<IteratorRegionMap>(); + for (const auto Reg : RegionMap) { + if (Reg.second.getContainer() == Cont) + return true; + } + + auto SymbolMap = State->get<IteratorSymbolMap>(); + for (const auto Sym : SymbolMap) { + if (Sym.second.getContainer() == Cont) + return true; + } + + return false; +} + bool isZero(ProgramStateRef State, const NonLoc &Val) { auto &BVF = State->getBasicVals(); return compare(State, Val, diff --git a/lib/StaticAnalyzer/Checkers/MallocChecker.cpp b/lib/StaticAnalyzer/Checkers/MallocChecker.cpp index 8f07f413e81f..ebaf79a780c0 100644 --- a/lib/StaticAnalyzer/Checkers/MallocChecker.cpp +++ b/lib/StaticAnalyzer/Checkers/MallocChecker.cpp @@ -179,11 +179,11 @@ public: II_strdup(nullptr), II_win_strdup(nullptr), II_kmalloc(nullptr), II_if_nameindex(nullptr), II_if_freenameindex(nullptr), II_wcsdup(nullptr), II_win_wcsdup(nullptr), II_g_malloc(nullptr), - II_g_malloc0(nullptr), II_g_realloc(nullptr), II_g_try_malloc(nullptr), - II_g_try_malloc0(nullptr), II_g_try_realloc(nullptr), - II_g_free(nullptr), II_g_memdup(nullptr), II_g_malloc_n(nullptr), - II_g_malloc0_n(nullptr), II_g_realloc_n(nullptr), - II_g_try_malloc_n(nullptr), II_g_try_malloc0_n(nullptr), + II_g_malloc0(nullptr), II_g_realloc(nullptr), II_g_try_malloc(nullptr), + II_g_try_malloc0(nullptr), II_g_try_realloc(nullptr), + II_g_free(nullptr), II_g_memdup(nullptr), II_g_malloc_n(nullptr), + II_g_malloc0_n(nullptr), II_g_realloc_n(nullptr), + II_g_try_malloc_n(nullptr), II_g_try_malloc0_n(nullptr), II_g_try_realloc_n(nullptr) {} /// In pessimistic mode, the checker assumes that it does not know which @@ -248,11 +248,11 @@ private: *II_realloc, *II_calloc, *II_valloc, *II_reallocf, *II_strndup, *II_strdup, *II_win_strdup, *II_kmalloc, *II_if_nameindex, *II_if_freenameindex, *II_wcsdup, - *II_win_wcsdup, *II_g_malloc, *II_g_malloc0, - *II_g_realloc, *II_g_try_malloc, *II_g_try_malloc0, - *II_g_try_realloc, *II_g_free, *II_g_memdup, - *II_g_malloc_n, *II_g_malloc0_n, *II_g_realloc_n, - *II_g_try_malloc_n, *II_g_try_malloc0_n, + *II_win_wcsdup, *II_g_malloc, *II_g_malloc0, + *II_g_realloc, *II_g_try_malloc, *II_g_try_malloc0, + *II_g_try_realloc, *II_g_free, *II_g_memdup, + *II_g_malloc_n, *II_g_malloc0_n, *II_g_realloc_n, + *II_g_try_malloc_n, *II_g_try_malloc0_n, *II_g_try_realloc_n; mutable Optional<uint64_t> KernelZeroFlagVal; @@ -346,7 +346,7 @@ private: ProgramStateRef ReallocMemAux(CheckerContext &C, const CallExpr *CE, bool FreesMemOnFailure, - ProgramStateRef State, + ProgramStateRef State, bool SuffixWithN = false) const; static SVal evalMulForBufferSize(CheckerContext &C, const Expr *Blocks, const Expr *BlockBytes); @@ -652,7 +652,7 @@ bool MallocChecker::isCMemFunction(const FunctionDecl *FD, initIdentifierInfo(C); if (Family == AF_Malloc && CheckFree) { - if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf || + if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf || FunI == II_g_free) return true; } @@ -662,12 +662,12 @@ bool MallocChecker::isCMemFunction(const FunctionDecl *FD, FunI == II_calloc || FunI == II_valloc || FunI == II_strdup || FunI == II_win_strdup || FunI == II_strndup || FunI == II_wcsdup || FunI == II_win_wcsdup || FunI == II_kmalloc || - FunI == II_g_malloc || FunI == II_g_malloc0 || - FunI == II_g_realloc || FunI == II_g_try_malloc || + FunI == II_g_malloc || FunI == II_g_malloc0 || + FunI == II_g_realloc || FunI == II_g_try_malloc || FunI == II_g_try_malloc0 || FunI == II_g_try_realloc || - FunI == II_g_memdup || FunI == II_g_malloc_n || - FunI == II_g_malloc0_n || FunI == II_g_realloc_n || - FunI == II_g_try_malloc_n || FunI == II_g_try_malloc0_n || + FunI == II_g_memdup || FunI == II_g_malloc_n || + FunI == II_g_malloc0_n || FunI == II_g_realloc_n || + FunI == II_g_try_malloc_n || FunI == II_g_try_malloc0_n || FunI == II_g_try_realloc_n) return true; } @@ -873,7 +873,7 @@ void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const { return; State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State); State = ProcessZeroAllocation(C, CE, 0, State); - } else if (FunI == II_realloc || FunI == II_g_realloc || + } else if (FunI == II_realloc || FunI == II_g_realloc || FunI == II_g_try_realloc) { State = ReallocMemAux(C, CE, false, State); State = ProcessZeroAllocation(C, CE, 1, State); @@ -936,7 +936,7 @@ void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const { return; State = MallocMemAux(C, CE, CE->getArg(1), UndefinedVal(), State); State = ProcessZeroAllocation(C, CE, 1, State); - } else if (FunI == II_g_malloc_n || FunI == II_g_try_malloc_n || + } else if (FunI == II_g_malloc_n || FunI == II_g_try_malloc_n || FunI == II_g_malloc0_n || FunI == II_g_try_malloc0_n) { if (CE->getNumArgs() < 2) return; @@ -2930,6 +2930,11 @@ std::shared_ptr<PathDiagnosticPiece> MallocChecker::MallocBugVisitor::VisitNode( OS << MemCallE->getMethodDecl()->getNameAsString(); } else if (const auto *OpCallE = dyn_cast<CXXOperatorCallExpr>(S)) { OS << OpCallE->getDirectCallee()->getNameAsString(); + } else if (const auto *CallE = dyn_cast<CallExpr>(S)) { + auto &CEMgr = BRC.getStateManager().getCallEventManager(); + CallEventRef<> Call = CEMgr.getSimpleCall(CallE, state, CurrentLC); + const auto *D = dyn_cast_or_null<NamedDecl>(Call->getDecl()); + OS << (D ? D->getNameAsString() : "unknown"); } OS << "'"; } diff --git a/lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp b/lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp index 2c1e139330d6..9c85c0983723 100644 --- a/lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp +++ b/lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp @@ -4000,7 +4000,7 @@ void RetainCountChecker::checkEndFunction(const ReturnStmt *RS, // Don't process anything within synthesized bodies. const LocationContext *LCtx = Pred->getLocationContext(); if (LCtx->getAnalysisDeclContext()->isBodyAutosynthesized()) { - assert(!LCtx->inTopFrame()); + assert(!LCtx->inTopFrame()); return; } diff --git a/lib/StaticAnalyzer/Checkers/RunLoopAutoreleaseLeakChecker.cpp b/lib/StaticAnalyzer/Checkers/RunLoopAutoreleaseLeakChecker.cpp index 64b61a0213d2..55516a34d1a7 100644 --- a/lib/StaticAnalyzer/Checkers/RunLoopAutoreleaseLeakChecker.cpp +++ b/lib/StaticAnalyzer/Checkers/RunLoopAutoreleaseLeakChecker.cpp @@ -45,9 +45,9 @@ const char * RunLoopBind = "NSRunLoopM"; const char * RunLoopRunBind = "RunLoopRunM"; const char * OtherMsgBind = "OtherMessageSentM"; const char * AutoreleasePoolBind = "AutoreleasePoolM"; +const char * OtherStmtAutoreleasePoolBind = "OtherAutoreleasePoolM"; -class RunLoopAutoreleaseLeakChecker : public Checker< - check::ASTCodeBody> { +class RunLoopAutoreleaseLeakChecker : public Checker<check::ASTCodeBody> { public: void checkASTCodeBody(const Decl *D, @@ -66,6 +66,8 @@ static TriBoolTy seenBeforeRec(const Stmt *Parent, const Stmt *A, const Stmt *B, MemoizationMapTy &Memoization) { for (const Stmt *C : Parent->children()) { + if (!C) continue; + if (C == A) return true; @@ -110,17 +112,20 @@ static void emitDiagnostics(BoundNodes &Match, const auto *AP = Match.getNodeAs<ObjCAutoreleasePoolStmt>(AutoreleasePoolBind); + const auto *OAP = + Match.getNodeAs<ObjCAutoreleasePoolStmt>(OtherStmtAutoreleasePoolBind); bool HasAutoreleasePool = (AP != nullptr); const auto *RL = Match.getNodeAs<ObjCMessageExpr>(RunLoopBind); const auto *RLR = Match.getNodeAs<Stmt>(RunLoopRunBind); assert(RLR && "Run loop launch not found"); - assert(ME != RLR); - if (HasAutoreleasePool && seenBefore(AP, RLR, ME)) + + // Launch of run loop occurs before the message-sent expression is seen. + if (seenBefore(DeclBody, RLR, ME)) return; - if (!HasAutoreleasePool && seenBefore(DeclBody, RLR, ME)) + if (HasAutoreleasePool && (OAP != AP)) return; PathDiagnosticLocation Location = PathDiagnosticLocation::createBegin( @@ -169,7 +174,8 @@ static void checkTempObjectsInSamePool(const Decl *D, AnalysisManager &AM, BugReporter &BR, const RunLoopAutoreleaseLeakChecker *Chkr) { StatementMatcher RunLoopRunM = getRunLoopRunM(); - StatementMatcher OtherMessageSentM = getOtherMessageSentM(); + StatementMatcher OtherMessageSentM = getOtherMessageSentM( + hasAncestor(autoreleasePoolStmt().bind(OtherStmtAutoreleasePoolBind))); StatementMatcher RunLoopInAutorelease = autoreleasePoolStmt( diff --git a/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp b/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp index feae9e59b343..e7a20fa03a4a 100644 --- a/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp +++ b/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp @@ -129,7 +129,7 @@ bool StackAddrEscapeChecker::isSemaphoreCaptured(const BlockDecl &B) const { for (const auto &C : B.captures()) { const auto *T = C.getVariable()->getType()->getAs<TypedefType>(); if (T && T->getDecl()->getIdentifier() == dispatch_semaphore_tII) - return true; + return true; } return false; } @@ -175,9 +175,9 @@ void StackAddrEscapeChecker::checkAsyncExecutedBlockCaptures( // There is a not-too-uncommon idiom // where a block passed to dispatch_async captures a semaphore // and then the thread (which called dispatch_async) is blocked on waiting - // for the completion of the execution of the block - // via dispatch_semaphore_wait. To avoid false-positives (for now) - // we ignore all the blocks which have captured + // for the completion of the execution of the block + // via dispatch_semaphore_wait. To avoid false-positives (for now) + // we ignore all the blocks which have captured // a variable of the type "dispatch_semaphore_t". if (isSemaphoreCaptured(*B.getDecl())) return; @@ -263,7 +263,7 @@ void StackAddrEscapeChecker::checkPreStmt(const ReturnStmt *RS, if (const BlockDataRegion *B = dyn_cast<BlockDataRegion>(R)) checkReturnedBlockCaptures(*B, C); - if (!isa<StackSpaceRegion>(R->getMemorySpace()) || + if (!isa<StackSpaceRegion>(R->getMemorySpace()) || isNotInCurrentFrame(R, C) || isArcManagedBlock(R, C)) return; diff --git a/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp b/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp index c87bc685d8b9..d4d33c1746ce 100644 --- a/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp +++ b/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp @@ -269,6 +269,8 @@ namespace { /// pointer dereference outside. class NoStoreFuncVisitor final : public BugReporterVisitor { const SubRegion *RegionOfInterest; + const SourceManager &SM; + const PrintingPolicy &PP; static constexpr const char *DiagnosticsMsg = "Returning without writing to '"; @@ -284,7 +286,10 @@ class NoStoreFuncVisitor final : public BugReporterVisitor { llvm::SmallPtrSet<const StackFrameContext *, 32> FramesModifyingCalculated; public: - NoStoreFuncVisitor(const SubRegion *R) : RegionOfInterest(R) {} + NoStoreFuncVisitor(const SubRegion *R) + : RegionOfInterest(R), + SM(R->getMemRegionManager()->getContext().getSourceManager()), + PP(R->getMemRegionManager()->getContext().getPrintingPolicy()) {} void Profile(llvm::FoldingSetNodeID &ID) const override { static int Tag = 0; @@ -307,8 +312,6 @@ public: CallEventRef<> Call = BRC.getStateManager().getCallEventManager().getCaller(SCtx, State); - const PrintingPolicy &PP = BRC.getASTContext().getPrintingPolicy(); - const SourceManager &SM = BRC.getSourceManager(); // Region of interest corresponds to an IVar, exiting a method // which could have written into that IVar, but did not. @@ -318,16 +321,14 @@ public: IvarR->getDecl()) && !isRegionOfInterestModifiedInFrame(N)) return notModifiedMemberDiagnostics( - Ctx, SM, PP, *CallExitLoc, Call, - MC->getReceiverSVal().getAsRegion()); + Ctx, *CallExitLoc, Call, MC->getReceiverSVal().getAsRegion()); if (const auto *CCall = dyn_cast<CXXConstructorCall>(Call)) { - const MemRegion *ThisRegion = CCall->getCXXThisVal().getAsRegion(); - if (RegionOfInterest->isSubRegionOf(ThisRegion) + const MemRegion *ThisR = CCall->getCXXThisVal().getAsRegion(); + if (RegionOfInterest->isSubRegionOf(ThisR) && !CCall->getDecl()->isImplicit() && !isRegionOfInterestModifiedInFrame(N)) - return notModifiedMemberDiagnostics(Ctx, SM, PP, *CallExitLoc, - CCall, ThisRegion); + return notModifiedMemberDiagnostics(Ctx, *CallExitLoc, Call, ThisR); } ArrayRef<ParmVarDecl *> parameters = getCallParameters(Call); @@ -344,7 +345,7 @@ public: return nullptr; return notModifiedParameterDiagnostics( - Ctx, SM, PP, *CallExitLoc, Call, PVD, R, IndirectionLevel); + Ctx, *CallExitLoc, Call, PVD, R, IndirectionLevel); } QualType PT = T->getPointeeType(); if (PT.isNull() || PT->isVoidType()) break; @@ -446,8 +447,6 @@ private: /// in a given function. std::shared_ptr<PathDiagnosticPiece> notModifiedMemberDiagnostics( const LocationContext *Ctx, - const SourceManager &SM, - const PrintingPolicy &PP, CallExitBegin &CallExitLoc, CallEventRef<> Call, const MemRegion *ArgRegion) { @@ -474,8 +473,6 @@ private: /// before we get to the super region of \c RegionOfInterest std::shared_ptr<PathDiagnosticPiece> notModifiedParameterDiagnostics(const LocationContext *Ctx, - const SourceManager &SM, - const PrintingPolicy &PP, CallExitBegin &CallExitLoc, CallEventRef<> Call, const ParmVarDecl *PVD, @@ -612,8 +609,7 @@ public: const ExplodedNode *N, const MemRegion *R, bool EnableNullFPSuppression, BugReport &BR, const SVal V) { - AnalyzerOptions &Options = N->getState()->getStateManager() - .getOwningEngine()->getAnalysisManager().options; + AnalyzerOptions &Options = N->getState()->getAnalysisManager().options; if (EnableNullFPSuppression && Options.shouldSuppressNullReturnPaths() && V.getAs<Loc>()) BR.addVisitor(llvm::make_unique<MacroNullReturnSuppressionVisitor>( @@ -740,9 +736,7 @@ public: RetVal = State->getSVal(*LValue); // See if the return value is NULL. If so, suppress the report. - SubEngine *Eng = State->getStateManager().getOwningEngine(); - assert(Eng && "Cannot file a bug report without an owning engine"); - AnalyzerOptions &Options = Eng->getAnalysisManager().options; + AnalyzerOptions &Options = State->getAnalysisManager().options; bool EnableNullFPSuppression = false; if (InEnableNullFPSuppression && Options.shouldSuppressNullReturnPaths()) @@ -1321,9 +1315,7 @@ SuppressInlineDefensiveChecksVisitor:: SuppressInlineDefensiveChecksVisitor(DefinedSVal Value, const ExplodedNode *N) : V(Value) { // Check if the visitor is disabled. - SubEngine *Eng = N->getState()->getStateManager().getOwningEngine(); - assert(Eng && "Cannot file a bug report without an owning engine"); - AnalyzerOptions &Options = Eng->getAnalysisManager().options; + AnalyzerOptions &Options = N->getState()->getAnalysisManager().options; if (!Options.shouldSuppressInlinedDefensiveChecks()) IsSatisfied = true; @@ -1603,6 +1595,7 @@ bool bugreporter::trackNullOrUndefValue(const ExplodedNode *N, LVNode->getSVal(Inner).getAsRegion(); if (R) { + // Mark both the variable region and its contents as interesting. SVal V = LVState->getRawSVal(loc::MemRegionVal(R)); report.addVisitor( diff --git a/lib/StaticAnalyzer/Core/CallEvent.cpp b/lib/StaticAnalyzer/Core/CallEvent.cpp index 8db7b06f186d..fe9260e32dd8 100644 --- a/lib/StaticAnalyzer/Core/CallEvent.cpp +++ b/lib/StaticAnalyzer/Core/CallEvent.cpp @@ -27,6 +27,7 @@ #include "clang/AST/Type.h" #include "clang/Analysis/AnalysisDeclContext.h" #include "clang/Analysis/CFG.h" +#include "clang/Analysis/CFGStmtMap.h" #include "clang/Analysis/ProgramPoint.h" #include "clang/CrossTU/CrossTranslationUnit.h" #include "clang/Basic/IdentifierTable.h" @@ -166,6 +167,68 @@ bool CallEvent::isGlobalCFunction(StringRef FunctionName) const { return CheckerContext::isCLibraryFunction(FD, FunctionName); } +AnalysisDeclContext *CallEvent::getCalleeAnalysisDeclContext() const { + const Decl *D = getDecl(); + + // If the callee is completely unknown, we cannot construct the stack frame. + if (!D) + return nullptr; + + // FIXME: Skip virtual functions for now. There's no easy procedure to foresee + // the exact decl that should be used, especially when it's not a definition. + if (const Decl *RD = getRuntimeDefinition().getDecl()) + if (RD != D) + return nullptr; + + return LCtx->getAnalysisDeclContext()->getManager()->getContext(D); +} + +const StackFrameContext *CallEvent::getCalleeStackFrame() const { + AnalysisDeclContext *ADC = getCalleeAnalysisDeclContext(); + if (!ADC) + return nullptr; + + const Expr *E = getOriginExpr(); + if (!E) + return nullptr; + + // Recover CFG block via reverse lookup. + // TODO: If we were to keep CFG element information as part of the CallEvent + // instead of doing this reverse lookup, we would be able to build the stack + // frame for non-expression-based calls, and also we wouldn't need the reverse + // lookup. + CFGStmtMap *Map = LCtx->getAnalysisDeclContext()->getCFGStmtMap(); + const CFGBlock *B = Map->getBlock(E); + assert(B); + + // Also recover CFG index by scanning the CFG block. + unsigned Idx = 0, Sz = B->size(); + for (; Idx < Sz; ++Idx) + if (auto StmtElem = (*B)[Idx].getAs<CFGStmt>()) + if (StmtElem->getStmt() == E) + break; + assert(Idx < Sz); + + return ADC->getManager()->getStackFrame(ADC, LCtx, E, B, Idx); +} + +const VarRegion *CallEvent::getParameterLocation(unsigned Index) const { + const StackFrameContext *SFC = getCalleeStackFrame(); + // We cannot construct a VarRegion without a stack frame. + if (!SFC) + return nullptr; + + const ParmVarDecl *PVD = parameters()[Index]; + const VarRegion *VR = + State->getStateManager().getRegionManager().getVarRegion(PVD, SFC); + + // This sanity check would fail if our parameter declaration doesn't + // correspond to the stack frame's function declaration. + assert(VR->getStackFrame() == SFC); + + return VR; +} + /// Returns true if a type is a pointer-to-const or reference-to-const /// with no further indirection. static bool isPointerToConst(QualType Ty) { diff --git a/lib/StaticAnalyzer/Core/ExprEngine.cpp b/lib/StaticAnalyzer/Core/ExprEngine.cpp index 188316c096e3..2b4bdd754fdb 100644 --- a/lib/StaticAnalyzer/Core/ExprEngine.cpp +++ b/lib/StaticAnalyzer/Core/ExprEngine.cpp @@ -117,56 +117,42 @@ STATISTIC(NumTimesRetriedWithoutInlining, /// the construction context was present and contained references to these /// AST nodes. class ConstructedObjectKey { - typedef std::pair< - llvm::PointerUnion<const Stmt *, const CXXCtorInitializer *>, - const LocationContext *> ConstructedObjectKeyImpl; + typedef std::pair<ConstructionContextItem, const LocationContext *> + ConstructedObjectKeyImpl; - ConstructedObjectKeyImpl Impl; + const ConstructedObjectKeyImpl Impl; const void *getAnyASTNodePtr() const { - if (const Stmt *S = getStmt()) + if (const Stmt *S = getItem().getStmtOrNull()) return S; else - return getCXXCtorInitializer(); + return getItem().getCXXCtorInitializer(); } public: - ConstructedObjectKey( - llvm::PointerUnion<const Stmt *, const CXXCtorInitializer *> P, - const LocationContext *LC) - : Impl(P, LC) { - // This is the full list of statements that require additional actions when - // encountered. This list may be expanded when new actions are implemented. - assert(getCXXCtorInitializer() || isa<DeclStmt>(getStmt()) || - isa<CXXNewExpr>(getStmt()) || isa<CXXBindTemporaryExpr>(getStmt()) || - isa<MaterializeTemporaryExpr>(getStmt()) || - isa<CXXConstructExpr>(getStmt())); - } - - const Stmt *getStmt() const { - return Impl.first.dyn_cast<const Stmt *>(); - } + explicit ConstructedObjectKey(const ConstructionContextItem &Item, + const LocationContext *LC) + : Impl(Item, LC) {} - const CXXCtorInitializer *getCXXCtorInitializer() const { - return Impl.first.dyn_cast<const CXXCtorInitializer *>(); - } - - const LocationContext *getLocationContext() const { - return Impl.second; - } + const ConstructionContextItem &getItem() const { return Impl.first; } + const LocationContext *getLocationContext() const { return Impl.second; } void print(llvm::raw_ostream &OS, PrinterHelper *Helper, PrintingPolicy &PP) { - OS << '(' << getLocationContext() << ',' << getAnyASTNodePtr() << ") "; - if (const Stmt *S = getStmt()) { + OS << '(' << getLocationContext() << ',' << getAnyASTNodePtr() << ',' + << getItem().getKindAsString(); + if (getItem().getKind() == ConstructionContextItem::ArgumentKind) + OS << " #" << getItem().getIndex(); + OS << ") "; + if (const Stmt *S = getItem().getStmtOrNull()) { S->printPretty(OS, Helper, PP); } else { - const CXXCtorInitializer *I = getCXXCtorInitializer(); + const CXXCtorInitializer *I = getItem().getCXXCtorInitializer(); OS << I->getAnyMember()->getNameAsString(); } } void Profile(llvm::FoldingSetNodeID &ID) const { - ID.AddPointer(Impl.first.getOpaqueValue()); + ID.Add(Impl.first); ID.AddPointer(Impl.second); } @@ -184,15 +170,6 @@ typedef llvm::ImmutableMap<ConstructedObjectKey, SVal> REGISTER_TRAIT_WITH_PROGRAMSTATE(ObjectsUnderConstruction, ObjectsUnderConstructionMap) -// Additionally, track a set of destructors that correspond to elided -// constructors when copy elision occurs. -typedef std::pair<const CXXBindTemporaryExpr *, const LocationContext *> - ElidedDestructorItem; -typedef llvm::ImmutableSet<ElidedDestructorItem> - ElidedDestructorSet; -REGISTER_TRAIT_WITH_PROGRAMSTATE(ElidedDestructors, - ElidedDestructorSet) - //===----------------------------------------------------------------------===// // Engine construction and deletion. //===----------------------------------------------------------------------===// @@ -449,31 +426,32 @@ ExprEngine::createTemporaryRegionIfNeeded(ProgramStateRef State, return State; } -ProgramStateRef ExprEngine::addObjectUnderConstruction( - ProgramStateRef State, - llvm::PointerUnion<const Stmt *, const CXXCtorInitializer *> P, - const LocationContext *LC, SVal V) { - ConstructedObjectKey Key(P, LC->getStackFrame()); +ProgramStateRef +ExprEngine::addObjectUnderConstruction(ProgramStateRef State, + const ConstructionContextItem &Item, + const LocationContext *LC, SVal V) { + ConstructedObjectKey Key(Item, LC->getStackFrame()); // FIXME: Currently the state might already contain the marker due to // incorrect handling of temporaries bound to default parameters. assert(!State->get<ObjectsUnderConstruction>(Key) || - isa<CXXBindTemporaryExpr>(Key.getStmt())); + Key.getItem().getKind() == + ConstructionContextItem::TemporaryDestructorKind); return State->set<ObjectsUnderConstruction>(Key, V); } -Optional<SVal> ExprEngine::getObjectUnderConstruction( - ProgramStateRef State, - llvm::PointerUnion<const Stmt *, const CXXCtorInitializer *> P, - const LocationContext *LC) { - ConstructedObjectKey Key(P, LC->getStackFrame()); +Optional<SVal> +ExprEngine::getObjectUnderConstruction(ProgramStateRef State, + const ConstructionContextItem &Item, + const LocationContext *LC) { + ConstructedObjectKey Key(Item, LC->getStackFrame()); return Optional<SVal>::create(State->get<ObjectsUnderConstruction>(Key)); } -ProgramStateRef ExprEngine::finishObjectConstruction( - ProgramStateRef State, - llvm::PointerUnion<const Stmt *, const CXXCtorInitializer *> P, - const LocationContext *LC) { - ConstructedObjectKey Key(P, LC->getStackFrame()); +ProgramStateRef +ExprEngine::finishObjectConstruction(ProgramStateRef State, + const ConstructionContextItem &Item, + const LocationContext *LC) { + ConstructedObjectKey Key(Item, LC->getStackFrame()); assert(State->contains<ObjectsUnderConstruction>(Key)); return State->remove<ObjectsUnderConstruction>(Key); } @@ -481,25 +459,26 @@ ProgramStateRef ExprEngine::finishObjectConstruction( ProgramStateRef ExprEngine::elideDestructor(ProgramStateRef State, const CXXBindTemporaryExpr *BTE, const LocationContext *LC) { - ElidedDestructorItem I(BTE, LC); - assert(!State->contains<ElidedDestructors>(I)); - return State->add<ElidedDestructors>(I); + ConstructedObjectKey Key({BTE, /*IsElided=*/true}, LC); + // FIXME: Currently the state might already contain the marker due to + // incorrect handling of temporaries bound to default parameters. + return State->set<ObjectsUnderConstruction>(Key, UnknownVal()); } ProgramStateRef ExprEngine::cleanupElidedDestructor(ProgramStateRef State, const CXXBindTemporaryExpr *BTE, const LocationContext *LC) { - ElidedDestructorItem I(BTE, LC); - assert(State->contains<ElidedDestructors>(I)); - return State->remove<ElidedDestructors>(I); + ConstructedObjectKey Key({BTE, /*IsElided=*/true}, LC); + assert(State->contains<ObjectsUnderConstruction>(Key)); + return State->remove<ObjectsUnderConstruction>(Key); } bool ExprEngine::isDestructorElided(ProgramStateRef State, const CXXBindTemporaryExpr *BTE, const LocationContext *LC) { - ElidedDestructorItem I(BTE, LC); - return State->contains<ElidedDestructors>(I); + ConstructedObjectKey Key({BTE, /*IsElided=*/true}, LC); + return State->contains<ObjectsUnderConstruction>(Key); } bool ExprEngine::areAllObjectsFullyConstructed(ProgramStateRef State, @@ -512,10 +491,6 @@ bool ExprEngine::areAllObjectsFullyConstructed(ProgramStateRef State, if (I.first.getLocationContext() == LC) return false; - for (auto I: State->get<ElidedDestructors>()) - if (I.second == LC) - return false; - LC = LC->getParent(); } return true; @@ -560,14 +535,6 @@ static void printObjectsUnderConstructionForContext(raw_ostream &Out, Key.print(Out, nullptr, PP); Out << " : " << Value << NL; } - - for (auto I : State->get<ElidedDestructors>()) { - if (I.second != LC) - continue; - Out << '(' << I.second << ',' << (const void *)I.first << ") "; - I.first->printPretty(Out, nullptr, PP); - Out << " : (constructor elided)" << NL; - } } void ExprEngine::printState(raw_ostream &Out, ProgramStateRef State, @@ -2252,25 +2219,14 @@ void ExprEngine::processEndOfFunction(NodeBuilderContext& BC, for (auto I : State->get<ObjectsUnderConstruction>()) if (I.first.getLocationContext() == LC) { // The comment above only pardons us for not cleaning up a - // CXXBindTemporaryExpr. If any other statements are found here, + // temporary destructor. If any other statements are found here, // it must be a separate problem. - assert(isa<CXXBindTemporaryExpr>(I.first.getStmt())); + assert(I.first.getItem().getKind() == + ConstructionContextItem::TemporaryDestructorKind || + I.first.getItem().getKind() == + ConstructionContextItem::ElidedDestructorKind); State = State->remove<ObjectsUnderConstruction>(I.first); - // Also cleanup the elided destructor info. - ElidedDestructorItem Item( - cast<CXXBindTemporaryExpr>(I.first.getStmt()), - I.first.getLocationContext()); - State = State->remove<ElidedDestructors>(Item); } - - // Also suppress the assertion for elided destructors when temporary - // destructors are not provided at all by the CFG, because there's no - // good place to clean them up. - if (!AMgr.getAnalyzerOptions().includeTemporaryDtorsInCFG()) - for (auto I : State->get<ElidedDestructors>()) - if (I.second == LC) - State = State->remove<ElidedDestructors>(I); - LC = LC->getParent(); } if (State != Pred->getState()) { @@ -2338,7 +2294,7 @@ void ExprEngine::processSwitch(SwitchNodeBuilder& builder) { // Evaluate the LHS of the case value. llvm::APSInt V1 = Case->getLHS()->EvaluateKnownConstInt(getContext()); assert(V1.getBitWidth() == getContext().getIntWidth(CondE->getType())); - + // Get the RHS of the case, if it exists. llvm::APSInt V2; if (const Expr *E = Case->getRHS()) @@ -2538,12 +2494,12 @@ void ExprEngine::VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred, ExplodedNodeSet CheckedSet; getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, M, *this); - ExplodedNodeSet EvalSet; - ValueDecl *Member = M->getMemberDecl(); + ExplodedNodeSet EvalSet; + ValueDecl *Member = M->getMemberDecl(); // Handle static member variables and enum constants accessed via // member syntax. - if (isa<VarDecl>(Member) || isa<EnumConstantDecl>(Member)) { + if (isa<VarDecl>(Member) || isa<EnumConstantDecl>(Member)) { for (const auto I : CheckedSet) VisitCommonDeclRefExpr(M, Member, I, EvalSet); } else { diff --git a/lib/StaticAnalyzer/Core/ExprEngineC.cpp b/lib/StaticAnalyzer/Core/ExprEngineC.cpp index c7b1a9ac82f0..61b7a290e42a 100644 --- a/lib/StaticAnalyzer/Core/ExprEngineC.cpp +++ b/lib/StaticAnalyzer/Core/ExprEngineC.cpp @@ -684,7 +684,7 @@ void ExprEngine::VisitLogicalExpr(const BinaryOperator* B, ExplodedNode *Pred, // known to be false, 1 if the value is known to be true and a new symbol // when the assumption is unknown. nonloc::ConcreteInt Zero(getBasicVals().getValue(0, B->getType())); - X = evalBinOp(N->getState(), BO_NE, + X = evalBinOp(N->getState(), BO_NE, svalBuilder.evalCast(RHSVal, B->getType(), RHS->getType()), Zero, B->getType()); } diff --git a/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp b/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp index dc124fc3ff2d..4f1766a813c6 100644 --- a/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp +++ b/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp @@ -221,25 +221,42 @@ std::pair<ProgramStateRef, SVal> ExprEngine::prepareForObjectConstruction( // and construct directly into the final object. This call // also sets the CallOpts flags for us. SVal V; + // If the elided copy/move constructor is not supported, there's still + // benefit in trying to model the non-elided constructor. + // Stash our state before trying to elide, as it'll get overwritten. + ProgramStateRef PreElideState = State; + EvalCallOptions PreElideCallOpts = CallOpts; + std::tie(State, V) = prepareForObjectConstruction( CE, State, LCtx, TCC->getConstructionContextAfterElision(), CallOpts); - // Remember that we've elided the constructor. - State = addObjectUnderConstruction(State, CE, LCtx, V); + // FIXME: This definition of "copy elision has not failed" is unreliable. + // It doesn't indicate that the constructor will actually be inlined + // later; it is still up to evalCall() to decide. + if (!CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion) { + // Remember that we've elided the constructor. + State = addObjectUnderConstruction(State, CE, LCtx, V); - // Remember that we've elided the destructor. - if (BTE) - State = elideDestructor(State, BTE, LCtx); + // Remember that we've elided the destructor. + if (BTE) + State = elideDestructor(State, BTE, LCtx); - // Instead of materialization, shamelessly return - // the final object destination. - if (MTE) - State = addObjectUnderConstruction(State, MTE, LCtx, V); + // Instead of materialization, shamelessly return + // the final object destination. + if (MTE) + State = addObjectUnderConstruction(State, MTE, LCtx, V); - return std::make_pair(State, V); + return std::make_pair(State, V); + } else { + // Copy elision failed. Revert the changes and proceed as if we have + // a simple temporary. + State = PreElideState; + CallOpts = PreElideCallOpts; + } + LLVM_FALLTHROUGH; } case ConstructionContext::SimpleTemporaryObjectKind: { - const auto *TCC = cast<SimpleTemporaryObjectConstructionContext>(CC); + const auto *TCC = cast<TemporaryObjectConstructionContext>(CC); const CXXBindTemporaryExpr *BTE = TCC->getCXXBindTemporaryExpr(); const MaterializeTemporaryExpr *MTE = TCC->getMaterializedTemporaryExpr(); SVal V = UnknownVal(); @@ -274,6 +291,10 @@ std::pair<ProgramStateRef, SVal> ExprEngine::prepareForObjectConstruction( CallOpts.IsTemporaryCtorOrDtor = true; return std::make_pair(State, V); } + case ConstructionContext::ArgumentKind: { + // Function argument constructors. Not implemented yet. + break; + } } } // If we couldn't find an existing region to construct into, assume we're diff --git a/lib/StaticAnalyzer/Core/IssueHash.cpp b/lib/StaticAnalyzer/Core/IssueHash.cpp index 274ebe7a941b..6c55c61dd399 100644 --- a/lib/StaticAnalyzer/Core/IssueHash.cpp +++ b/lib/StaticAnalyzer/Core/IssueHash.cpp @@ -26,7 +26,7 @@ using namespace clang; -// Get a string representation of the parts of the signature that can be +// Get a string representation of the parts of the signature that can be // overloaded on. static std::string GetSignature(const FunctionDecl *Target) { if (!Target) diff --git a/lib/StaticAnalyzer/Core/ProgramState.cpp b/lib/StaticAnalyzer/Core/ProgramState.cpp index 2b401607293b..94e2e00d8bbc 100644 --- a/lib/StaticAnalyzer/Core/ProgramState.cpp +++ b/lib/StaticAnalyzer/Core/ProgramState.cpp @@ -11,6 +11,7 @@ // //===----------------------------------------------------------------------===// +#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h" #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h" #include "clang/Analysis/CFG.h" #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" @@ -494,6 +495,10 @@ void ProgramState::dumpTaint() const { printTaint(llvm::errs()); } +AnalysisManager& ProgramState::getAnalysisManager() const { + return stateMgr->getOwningEngine()->getAnalysisManager(); +} + //===----------------------------------------------------------------------===// // Generic Data Map. //===----------------------------------------------------------------------===// diff --git a/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp b/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp index beae0dfae289..62c54fc956a9 100644 --- a/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp +++ b/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp @@ -440,7 +440,7 @@ static bool shouldRearrange(ProgramStateRef State, BinaryOperator::Opcode Op, SymbolRef Sym, llvm::APSInt Int, QualType Ty) { return Sym->getType() == Ty && (!BinaryOperator::isComparisonOp(Op) || - (isWithinConstantOverflowBounds(Sym, State) && + (isWithinConstantOverflowBounds(Sym, State) && isWithinConstantOverflowBounds(Int))); } @@ -1236,11 +1236,21 @@ SVal SimpleSValBuilder::simplifySVal(ProgramStateRef State, SVal V) { return Sym == Val.getAsSymbol(); } + SVal cache(SymbolRef Sym, SVal V) { + Cached[Sym] = V; + return V; + } + + SVal skip(SymbolRef Sym) { + return cache(Sym, SVB.makeSymbolVal(Sym)); + } + public: Simplifier(ProgramStateRef State) : State(State), SVB(State->getStateManager().getSValBuilder()) {} SVal VisitSymbolData(const SymbolData *S) { + // No cache here. if (const llvm::APSInt *I = SVB.getKnownValue(State, SVB.makeSymbolVal(S))) return Loc::isLocType(S->getType()) ? (SVal)SVB.makeIntLocVal(*I) @@ -1257,11 +1267,9 @@ SVal SimpleSValBuilder::simplifySVal(ProgramStateRef State, SVal V) { return I->second; SVal LHS = Visit(S->getLHS()); - if (isUnchanged(S->getLHS(), LHS)) { - SVal V = SVB.makeSymbolVal(S); - Cached[S] = V; - return V; - } + if (isUnchanged(S->getLHS(), LHS)) + return skip(S); + SVal RHS; // By looking at the APSInt in the right-hand side of S, we cannot // figure out if it should be treated as a Loc or as a NonLoc. @@ -1281,9 +1289,8 @@ SVal SimpleSValBuilder::simplifySVal(ProgramStateRef State, SVal V) { RHS = SVB.makeIntVal(S->getRHS()); } - SVal V = SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType()); - Cached[S] = V; - return V; + return cache( + S, SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType())); } SVal VisitSymSymExpr(const SymSymExpr *S) { @@ -1291,16 +1298,21 @@ SVal SimpleSValBuilder::simplifySVal(ProgramStateRef State, SVal V) { if (I != Cached.end()) return I->second; + // For now don't try to simplify mixed Loc/NonLoc expressions + // because they often appear from LocAsInteger operations + // and we don't know how to combine a LocAsInteger + // with a concrete value. + if (Loc::isLocType(S->getLHS()->getType()) != + Loc::isLocType(S->getRHS()->getType())) + return skip(S); + SVal LHS = Visit(S->getLHS()); SVal RHS = Visit(S->getRHS()); - if (isUnchanged(S->getLHS(), LHS) && isUnchanged(S->getRHS(), RHS)) { - SVal V = SVB.makeSymbolVal(S); - Cached[S] = V; - return V; - } - SVal V = SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType()); - Cached[S] = V; - return V; + if (isUnchanged(S->getLHS(), LHS) && isUnchanged(S->getRHS(), RHS)) + return skip(S); + + return cache( + S, SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType())); } SVal VisitSymExpr(SymbolRef S) { return nonloc::SymbolVal(S); } diff --git a/lib/StaticAnalyzer/Core/Store.cpp b/lib/StaticAnalyzer/Core/Store.cpp index 5ab5c082269b..94188a9ef698 100644 --- a/lib/StaticAnalyzer/Core/Store.cpp +++ b/lib/StaticAnalyzer/Core/Store.cpp @@ -448,10 +448,10 @@ SVal StoreManager::getLValueElement(QualType elementType, NonLoc Offset, // value. See also the similar FIXME in getLValueFieldOrIvar(). if (Base.isUnknownOrUndef() || Base.getAs<loc::ConcreteInt>()) return Base; - + if (Base.getAs<loc::GotoLabel>()) return UnknownVal(); - + const SubRegion *BaseRegion = Base.castAs<loc::MemRegionVal>().getRegionAs<SubRegion>(); diff --git a/test/Analysis/Checkers/RunLoopAutoreleaseLeakChecker.m b/test/Analysis/Checkers/RunLoopAutoreleaseLeakChecker.m index 4dde40e210a0..b00d71b1a4d0 100644 --- a/test/Analysis/Checkers/RunLoopAutoreleaseLeakChecker.m +++ b/test/Analysis/Checkers/RunLoopAutoreleaseLeakChecker.m @@ -29,6 +29,17 @@ void runloop_init_before() { // Warning: object created before the loop. } } +void runloop_init_before_separate_pool() { // No warning: separate autorelease pool. + @autoreleasepool { + NSObject *object; + @autoreleasepool { + object = [[NSObject alloc] init]; // no-warning + } + (void) object; + [[NSRunLoop mainRunLoop] run]; + } +} + void xpcmain_init_before() { // Warning: object created before the loop. @autoreleasepool { NSObject *object = [[NSObject alloc] init]; // expected-warning{{Temporary objects allocated in the autorelease pool followed by the launch of xpc_main may never get released; consider moving them to a separate autorelease pool}} @@ -43,7 +54,7 @@ void runloop_init_before_two_objects() { // Warning: object created before the l NSObject *object2 = [[NSObject alloc] init]; // no-warning, warning on the first one is enough. (void) object; (void) object2; - [[NSRunLoop mainRunLoop] run]; + [[NSRunLoop mainRunLoop] run]; } } @@ -61,6 +72,15 @@ void runloop_init_after() { // No warning: objects created after the loop } } +void no_crash_on_empty_children() { + @autoreleasepool { + for (;;) {} + NSObject *object = [[NSObject alloc] init]; // expected-warning{{Temporary objects allocated in the autorelease pool followed by the launch of main run loop may never get released; consider moving them to a separate autorelease pool}} + [[NSRunLoop mainRunLoop] run]; + (void) object; + } +} + #endif #ifdef AP1 diff --git a/test/Analysis/casts.c b/test/Analysis/casts.c index eccb67812a02..86fb7da58ec2 100644 --- a/test/Analysis/casts.c +++ b/test/Analysis/casts.c @@ -175,3 +175,10 @@ void testCastVoidPtrToIntPtrThroughUIntTypedAssignment() { void testLocNonLocSymbolAssume(int a, int *b) { if ((int)b < a) {} // no-crash } + +void testLocNonLocSymbolRemainder(int a, int *b) { + int c = ((int)b) % a; + if (a == 1) { + c += 1; + } +} diff --git a/test/Analysis/cfg-rich-constructors.cpp b/test/Analysis/cfg-rich-constructors.cpp index 6780cf1a7be9..88b03788da43 100644 --- a/test/Analysis/cfg-rich-constructors.cpp +++ b/test/Analysis/cfg-rich-constructors.cpp @@ -817,25 +817,58 @@ public: ~D(); }; +class E { +public: + E(D d); +}; + void useC(C c); void useCByReference(const C &c); void useD(D d); void useDByReference(const D &d); +void useCAndD(C c, D d); -// FIXME: Find construction context for the argument. // CHECK: void passArgument() // CHECK: 1: useC // CHECK-NEXT: 2: [B1.1] (ImplicitCastExpr, FunctionToPointerDecay, void (*)(class C)) -// CXX11-NEXT: 3: C() (CXXConstructExpr, [B1.4], class C) +// CXX11-ELIDE-NEXT: 3: C() (CXXConstructExpr, [B1.4], [B1.5], class C) +// CXX11-NOELIDE-NEXT: 3: C() (CXXConstructExpr, [B1.4], class C) // CXX11-NEXT: 4: [B1.3] -// CXX11-NEXT: 5: [B1.4] (CXXConstructExpr, class C) +// CXX11-NEXT: 5: [B1.4] (CXXConstructExpr, [B1.6]+0, class C) // CXX11-NEXT: 6: [B1.2]([B1.5]) -// CXX17-NEXT: 3: C() (CXXConstructExpr, class C) +// CXX17-NEXT: 3: C() (CXXConstructExpr, [B1.4]+0, class C) // CXX17-NEXT: 4: [B1.2]([B1.3]) void passArgument() { useC(C()); } +// CHECK: void passTwoArguments() +// CHECK: [B1] +// CHECK-NEXT: 1: useCAndD +// CHECK-NEXT: 2: [B1.1] (ImplicitCastExpr, FunctionToPointerDecay, void (*)(class C, class argument_constructors::D)) +// CXX11-ELIDE-NEXT: 3: C() (CXXConstructExpr, [B1.4], [B1.5], class C) +// CXX11-NOELIDE-NEXT: 3: C() (CXXConstructExpr, [B1.4], class C) +// CXX11-NEXT: 4: [B1.3] +// CXX11-NEXT: 5: [B1.4] (CXXConstructExpr, [B1.12]+0, class C) +// CXX11-ELIDE-NEXT: 6: argument_constructors::D() (CXXConstructExpr, [B1.7], [B1.9], [B1.10], class argument_constructors::D) +// CXX11-NOELIDE-NEXT: 6: argument_constructors::D() (CXXConstructExpr, [B1.7], [B1.9], class argument_constructors::D) +// CXX11-NEXT: 7: [B1.6] (BindTemporary) +// CXX11-NEXT: 8: [B1.7] (ImplicitCastExpr, NoOp, const class argument_constructors::D) +// CXX11-NEXT: 9: [B1.8] +// CXX11-NEXT: 10: [B1.9] (CXXConstructExpr, [B1.11], [B1.12]+1, class argument_constructors::D) +// CXX11-NEXT: 11: [B1.10] (BindTemporary) +// CXX11-NEXT: 12: [B1.2]([B1.5], [B1.11]) +// CXX11-NEXT: 13: ~argument_constructors::D() (Temporary object destructor) +// CXX11-NEXT: 14: ~argument_constructors::D() (Temporary object destructor) +// CXX17-NEXT: 3: C() (CXXConstructExpr, [B1.6]+0, class C) +// CXX17-NEXT: 4: argument_constructors::D() (CXXConstructExpr, [B1.5], [B1.6]+1, class argument_co +// CXX17-NEXT: 5: [B1.4] (BindTemporary) +// CXX17-NEXT: 6: [B1.2]([B1.3], [B1.5]) +// CXX17-NEXT: 7: ~argument_constructors::D() (Temporary object destructor) +void passTwoArguments() { + useCAndD(C(), D()); +} + // CHECK: void passArgumentByReference() // CHECK: 1: useCByReference // CHECK-NEXT: 2: [B1.1] (ImplicitCastExpr, FunctionToPointerDecay, void (*)(const class C &)) @@ -847,20 +880,20 @@ void passArgumentByReference() { useCByReference(C()); } -// FIXME: Find construction context for the argument. // CHECK: void passArgumentWithDestructor() // CHECK: 1: useD // CHECK-NEXT: 2: [B1.1] (ImplicitCastExpr, FunctionToPointerDecay, void (*)(class argument_constructors::D)) -// CXX11-NEXT: 3: argument_constructors::D() (CXXConstructExpr, [B1.4], [B1.6], class argument_constructors::D) +// CXX11-ELIDE-NEXT: 3: argument_constructors::D() (CXXConstructExpr, [B1.4], [B1.6], [B1.7], class argument_constructors::D) +// CXX11-NOELIDE-NEXT: 3: argument_constructors::D() (CXXConstructExpr, [B1.4], [B1.6], class argument_constructors::D) // CXX11-NEXT: 4: [B1.3] (BindTemporary) // CXX11-NEXT: 5: [B1.4] (ImplicitCastExpr, NoOp, const class argument_constructors::D) // CXX11-NEXT: 6: [B1.5] -// CXX11-NEXT: 7: [B1.6] (CXXConstructExpr, class argument_constructors::D) +// CXX11-NEXT: 7: [B1.6] (CXXConstructExpr, [B1.8], [B1.9]+0, class argument_constructors::D) // CXX11-NEXT: 8: [B1.7] (BindTemporary) // CXX11-NEXT: 9: [B1.2]([B1.8]) // CXX11-NEXT: 10: ~argument_constructors::D() (Temporary object destructor) // CXX11-NEXT: 11: ~argument_constructors::D() (Temporary object destructor) -// CXX17-NEXT: 3: argument_constructors::D() (CXXConstructExpr, class argument_constructors::D) +// CXX17-NEXT: 3: argument_constructors::D() (CXXConstructExpr, [B1.4], [B1.5]+0, class argument_constructors::D) // CXX17-NEXT: 4: [B1.3] (BindTemporary) // CXX17-NEXT: 5: [B1.2]([B1.4]) // CXX17-NEXT: 6: ~argument_constructors::D() (Temporary object destructor) @@ -880,6 +913,32 @@ void passArgumentWithDestructor() { void passArgumentWithDestructorByReference() { useDByReference(D()); } + +// CHECK: void passArgumentIntoAnotherConstructor() +// CXX11-ELIDE: 1: argument_constructors::D() (CXXConstructExpr, [B1.2], [B1.4], [B1.5], class argument_constructors::D) +// CXX11-NOELIDE: 1: argument_constructors::D() (CXXConstructExpr, [B1.2], [B1.4], class argument_constructors::D) +// CXX11-NEXT: 2: [B1.1] (BindTemporary) +// CXX11-NEXT: 3: [B1.2] (ImplicitCastExpr, NoOp, const class argument_constructors::D) +// CXX11-NEXT: 4: [B1.3] +// CXX11-NEXT: 5: [B1.4] (CXXConstructExpr, [B1.6], [B1.7]+0, class argument_constructors::D) +// CXX11-NEXT: 6: [B1.5] (BindTemporary) +// CXX11-ELIDE-NEXT: 7: [B1.6] (CXXConstructExpr, [B1.9], [B1.10], class argument_constructors::E) +// CXX11-NOELIDE-NEXT: 7: [B1.6] (CXXConstructExpr, [B1.9], class argument_constructors::E) +// CXX11-NEXT: 8: argument_constructors::E([B1.7]) (CXXFunctionalCastExpr, ConstructorConversion, class argument_constructors::E) +// CXX11-NEXT: 9: [B1.8] +// CXX11-NEXT: 10: [B1.9] (CXXConstructExpr, [B1.11], class argument_constructors::E) +// CXX11-NEXT: 11: argument_constructors::E e = argument_constructors::E(argument_constructors::D()); +// CXX11-NEXT: 12: ~argument_constructors::D() (Temporary object destructor) +// CXX11-NEXT: 13: ~argument_constructors::D() (Temporary object destructor) +// CXX17: 1: argument_constructors::D() (CXXConstructExpr, [B1.2], [B1.3]+0, class argument_constructors::D) +// CXX17-NEXT: 2: [B1.1] (BindTemporary) +// CXX17-NEXT: 3: [B1.2] (CXXConstructExpr, [B1.5], class argument_constructors::E) +// CXX17-NEXT: 4: argument_constructors::E([B1.3]) (CXXFunctionalCastExpr, ConstructorConversion, class argument_constructors::E) +// CXX17-NEXT: 5: argument_constructors::E e = argument_constructors::E(argument_constructors::D()); +// CXX17-NEXT: 6: ~argument_constructors::D() (Temporary object destructor) +void passArgumentIntoAnotherConstructor() { + E e = E(D()); +} } // end namespace argument_constructors namespace copy_elision_with_extra_arguments { diff --git a/test/Analysis/cfg-rich-constructors.mm b/test/Analysis/cfg-rich-constructors.mm new file mode 100644 index 000000000000..289094293eb5 --- /dev/null +++ b/test/Analysis/cfg-rich-constructors.mm @@ -0,0 +1,66 @@ +// RUN: %clang_analyze_cc1 -analyzer-checker=debug.DumpCFG -triple x86_64-apple-darwin12 -std=c++11 -w %s > %t 2>&1 +// RUN: FileCheck --input-file=%t -check-prefixes=CHECK,CXX11,ELIDE,CXX11-ELIDE %s +// RUN: %clang_analyze_cc1 -analyzer-checker=debug.DumpCFG -triple x86_64-apple-darwin12 -std=c++17 -w %s > %t 2>&1 +// RUN: FileCheck --input-file=%t -check-prefixes=CHECK,CXX17,ELIDE,CXX17-ELIDE %s +// RUN: %clang_analyze_cc1 -analyzer-checker=debug.DumpCFG -triple x86_64-apple-darwin12 -std=c++11 -w -analyzer-config elide-constructors=false %s > %t 2>&1 +// RUN: FileCheck --input-file=%t -check-prefixes=CHECK,CXX11,NOELIDE,CXX11-NOELIDE %s +// RUN: %clang_analyze_cc1 -analyzer-checker=debug.DumpCFG -triple x86_64-apple-darwin12 -std=c++17 -w -analyzer-config elide-constructors=false %s > %t 2>&1 +// RUN: FileCheck --input-file=%t -check-prefixes=CHECK,CXX17,NOELIDE,CXX17-NOELIDE %s + +class D { +public: + D(); + ~D(); +}; + +@interface E {} +-(void) foo: (D) d; +-(D) bar; +@end + +// CHECK: void passArgumentIntoMessage(E *e) +// CHECK: 1: e +// CHECK-NEXT: 2: [B1.1] (ImplicitCastExpr, LValueToRValue, E *) +// CXX11-ELIDE-NEXT: 3: D() (CXXConstructExpr, [B1.4], [B1.6], [B1.7], class D) +// CXX11-NOELIDE-NEXT: 3: D() (CXXConstructExpr, [B1.4], [B1.6], class D) +// CXX11-NEXT: 4: [B1.3] (BindTemporary) +// CXX11-NEXT: 5: [B1.4] (ImplicitCastExpr, NoOp, const class D) +// CXX11-NEXT: 6: [B1.5] +// CXX11-NEXT: 7: [B1.6] (CXXConstructExpr, [B1.8], [B1.9]+0, class D) +// CXX11-NEXT: 8: [B1.7] (BindTemporary) +// Double brackets trigger FileCheck variables, escape. +// CXX11-NEXT: 9: {{\[}}[B1.2] foo:[B1.8]] +// CXX11-NEXT: 10: ~D() (Temporary object destructor) +// CXX11-NEXT: 11: ~D() (Temporary object destructor) +// CXX17-NEXT: 3: D() (CXXConstructExpr, [B1.4], [B1.5]+0, class D) +// CXX17-NEXT: 4: [B1.3] (BindTemporary) +// Double brackets trigger FileCheck variables, escape. +// CXX17-NEXT: 5: {{\[}}[B1.2] foo:[B1.4]] +// CXX17-NEXT: 6: ~D() (Temporary object destructor) +void passArgumentIntoMessage(E *e) { + [e foo: D()]; +} + +// CHECK: void returnObjectFromMessage(E *e) +// CHECK: [B1] +// CHECK-NEXT: 1: e +// CHECK-NEXT: 2: [B1.1] (ImplicitCastExpr, LValueToRValue, E *) +// Double brackets trigger FileCheck variables, escape. +// CXX11-ELIDE-NEXT: 3: {{\[}}[B1.2] bar] (CXXRecordTypedCall, [B1.4], [B1.6], [B1.7]) +// CXX11-NOELIDE-NEXT: 3: {{\[}}[B1.2] bar] (CXXRecordTypedCall, [B1.4], [B1.6]) +// CXX11-NEXT: 4: [B1.3] (BindTemporary) +// CXX11-NEXT: 5: [B1.4] (ImplicitCastExpr, NoOp, const class D) +// CXX11-NEXT: 6: [B1.5] +// CXX11-NEXT: 7: [B1.6] (CXXConstructExpr, [B1.8], class D) +// CXX11-NEXT: 8: D d = [e bar]; +// CXX11-NEXT: 9: ~D() (Temporary object destructor) +// CXX11-NEXT: 10: [B1.8].~D() (Implicit destructor) +// Double brackets trigger FileCheck variables, escape. +// CXX17-NEXT: 3: {{\[}}[B1.2] bar] (CXXRecordTypedCall, [B1.5], [B1.4]) +// CXX17-NEXT: 4: [B1.3] (BindTemporary) +// CXX17-NEXT: 5: D d = [e bar]; +// CXX17-NEXT: 6: ~D() (Temporary object destructor) +// CXX17-NEXT: 7: [B1.5].~D() (Implicit destructor) +void returnObjectFromMessage(E *e) { + D d = [e bar]; +} diff --git a/test/Analysis/cxx17-mandatory-elision.cpp b/test/Analysis/copy-elision.cpp index cf77912ea6c4..cf77912ea6c4 100644 --- a/test/Analysis/cxx17-mandatory-elision.cpp +++ b/test/Analysis/copy-elision.cpp diff --git a/test/Analysis/cstring-ranges.c b/test/Analysis/cstring-ranges.c new file mode 100644 index 000000000000..4fcd7eaa8bee --- /dev/null +++ b/test/Analysis/cstring-ranges.c @@ -0,0 +1,15 @@ +// RUN: %clang_analyze_cc1 -analyzer-checker=unix.cstring -analyzer-output=text %s 2>&1 | FileCheck %s + +// This test verifies argument source range highlighting. +// Otherwise we've no idea which of the arguments is null. + +char *strcpy(char *, const char *); + +void foo() { + char *a = 0, *b = 0; + strcpy(a, b); +} + +// CHECK: warning: Null pointer argument in call to string copy function +// CHECK-NEXT: strcpy(a, b); +// CHECK-NEXT: ^ ~ diff --git a/test/Analysis/inner-pointer.cpp b/test/Analysis/inner-pointer.cpp index db9bf43109b2..230e3396c59e 100644 --- a/test/Analysis/inner-pointer.cpp +++ b/test/Analysis/inner-pointer.cpp @@ -1,4 +1,4 @@ -//RUN: %clang_analyze_cc1 -analyzer-checker=alpha.cplusplus.InnerPointer %s -analyzer-output=text -verify +//RUN: %clang_analyze_cc1 -analyzer-checker=cplusplus.InnerPointer %s -analyzer-output=text -verify namespace std { @@ -38,6 +38,18 @@ typedef basic_string<wchar_t> wstring; typedef basic_string<char16_t> u16string; typedef basic_string<char32_t> u32string; +template <typename T> +void func_ref(T &a); + +template <typename T> +void func_const_ref(const T &a); + +template <typename T> +void func_value(T a); + +string my_string = "default"; +void default_arg(int a = 42, string &b = my_string); + } // end namespace std void consume(const char *) {} @@ -45,6 +57,10 @@ void consume(const wchar_t *) {} void consume(const char16_t *) {} void consume(const char32_t *) {} +//=--------------------------------------=// +// `std::string` member functions // +//=--------------------------------------=// + void deref_after_scope_char(bool cond) { const char *c, *d; { @@ -151,6 +167,19 @@ void multiple_symbols(bool cond) { } // expected-note@-1 {{Use of memory after it is freed}} } +void deref_after_scope_ok(bool cond) { + const char *c, *d; + std::string s; + { + c = s.c_str(); + d = s.data(); + } + if (cond) + consume(c); // no-warning + else + consume(d); // no-warning +} + void deref_after_equals() { const char *c; std::string s = "hello"; @@ -277,15 +306,58 @@ void deref_after_swap() { // expected-note@-1 {{Use of memory after it is freed}} } -void deref_after_scope_ok(bool cond) { - const char *c, *d; +//=---------------------------=// +// Other STL functions // +//=---------------------------=// + +void STL_func_ref() { + const char *c; std::string s; - { - c = s.c_str(); - d = s.data(); - } - if (cond) - consume(c); // no-warning - else - consume(d); // no-warning + c = s.c_str(); // expected-note {{Dangling inner pointer obtained here}} + std::func_ref(s); // expected-note {{Inner pointer invalidated by call to 'func_ref'}} + consume(c); // expected-warning {{Use of memory after it is freed}} + // expected-note@-1 {{Use of memory after it is freed}} +} + +void STL_func_const_ref() { + const char *c; + std::string s; + c = s.c_str(); + std::func_const_ref(s); + consume(c); // no-warning +} + +void STL_func_value() { + const char *c; + std::string s; + c = s.c_str(); + std::func_value(s); + consume(c); // no-warning +} + +void func_ptr_known() { + const char *c; + std::string s; + void (*func_ptr)(std::string &) = std::func_ref<std::string>; + c = s.c_str(); // expected-note {{Dangling inner pointer obtained here}} + func_ptr(s); // expected-note {{Inner pointer invalidated by call to 'func_ref'}} + consume(c); // expected-warning {{Use of memory after it is freed}} + // expected-note@-1 {{Use of memory after it is freed}} +} + +void func_ptr_unknown(void (*func_ptr)(std::string &)) { + const char *c; + std::string s; + c = s.c_str(); + func_ptr(s); + consume(c); // no-warning +} + +void func_default_arg() { + const char *c; + std::string s; + c = s.c_str(); // expected-note {{Dangling inner pointer obtained here}} + default_arg(3, s); // expected-note {{Inner pointer invalidated by call to 'default_arg'}} + consume(c); // expected-warning {{Use of memory after it is freed}} + // expected-note@-1 {{Use of memory after it is freed}} } diff --git a/test/Analysis/lifetime-extension.mm b/test/Analysis/lifetime-extension.mm new file mode 100644 index 000000000000..6fb2e04f1018 --- /dev/null +++ b/test/Analysis/lifetime-extension.mm @@ -0,0 +1,64 @@ +// RUN: %clang_analyze_cc1 -Wno-unused -std=c++11 -analyzer-checker=core,debug.ExprInspection -verify %s +// RUN: %clang_analyze_cc1 -Wno-unused -std=c++17 -analyzer-checker=core,debug.ExprInspection -verify %s +// RUN: %clang_analyze_cc1 -Wno-unused -std=c++11 -analyzer-checker=core,debug.ExprInspection -DMOVES -verify %s +// RUN: %clang_analyze_cc1 -Wno-unused -std=c++17 -analyzer-checker=core,debug.ExprInspection -DMOVES -verify %s + +void clang_analyzer_eval(bool); +void clang_analyzer_checkInlined(bool); + +template <typename T> struct AddressVector { + T *buf[10]; + int len; + + AddressVector() : len(0) {} + + void push(T *t) { + buf[len] = t; + ++len; + } +}; + +class C { + AddressVector<C> &v; + +public: + C(AddressVector<C> &v) : v(v) { v.push(this); } + ~C() { v.push(this); } + +#ifdef MOVES + C(C &&c) : v(c.v) { v.push(this); } +#endif + + // Note how return-statements prefer move-constructors when available. + C(const C &c) : v(c.v) { +#ifdef MOVES + clang_analyzer_checkInlined(false); // no-warning +#else + v.push(this); +#endif + } // no-warning +}; + +@interface NSObject {} +@end; +@interface Foo: NSObject {} + -(C) make: (AddressVector<C> &)v; +@end + +@implementation Foo +-(C) make: (AddressVector<C> &)v { + return C(v); +} +@end + +void testReturnByValueFromMessage(Foo *foo) { + AddressVector<C> v; + { + const C &c = [foo make: v]; + } + // 0. Construct the return value of -make (copy/move elided) and + // lifetime-extend it directly via reference 'c', + // 1. Destroy the temporary lifetime-extended by 'c'. + clang_analyzer_eval(v.len == 2); // expected-warning{{TRUE}} + clang_analyzer_eval(v.buf[0] == v.buf[1]); // expected-warning{{TRUE}} +} diff --git a/test/Analysis/temporaries.cpp b/test/Analysis/temporaries.cpp index de3420e70891..e760d7ea283a 100644 --- a/test/Analysis/temporaries.cpp +++ b/test/Analysis/temporaries.cpp @@ -1,7 +1,7 @@ -// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection -analyzer-config cfg-temporary-dtors=false -verify -w -std=c++03 %s -// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection -analyzer-config cfg-temporary-dtors=false -verify -w -std=c++11 %s -// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection -DTEMPORARY_DTORS -verify -w -analyzer-config cfg-temporary-dtors=true,c++-temp-dtor-inlining=true %s -std=c++11 -// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection -DTEMPORARY_DTORS -w -analyzer-config cfg-temporary-dtors=true,c++-temp-dtor-inlining=true %s -std=c++17 +// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus,debug.ExprInspection -analyzer-config cfg-temporary-dtors=false -verify -w -std=c++03 %s +// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus,debug.ExprInspection -analyzer-config cfg-temporary-dtors=false -verify -w -std=c++11 %s +// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus,debug.ExprInspection -DTEMPORARY_DTORS -verify -w -analyzer-config cfg-temporary-dtors=true,c++-temp-dtor-inlining=true %s -std=c++11 +// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus,debug.ExprInspection -DTEMPORARY_DTORS -w -analyzer-config cfg-temporary-dtors=true,c++-temp-dtor-inlining=true %s -std=c++17 // Note: The C++17 run-line doesn't -verify yet - it is a no-crash test. @@ -458,6 +458,21 @@ namespace destructors { #endif // TEMPORARY_DTORS } +namespace default_param_elided_destructors { +struct a { + ~a(); +}; +struct F { + a d; + F(char *, a = a()); +}; +void g() { + char h[1]; + for (int i = 0;;) + F j(i ? j : h); +} +} // namespace default_param_elided_destructors + void testStaticMaterializeTemporaryExpr() { static const Trivial &ref = getTrivial(); clang_analyzer_eval(ref.value == 42); // expected-warning{{TRUE}} @@ -945,3 +960,29 @@ C &&foo2(); const C &bar1() { return foo1(); } // no-crash C &&bar2() { return foo2(); } // no-crash } // end namespace pass_references_through + + +namespace ctor_argument { +// Stripped down unique_ptr<int> +struct IntPtr { + IntPtr(): i(new int) {} + IntPtr(IntPtr &&o): i(o.i) { o.i = 0; } + ~IntPtr() { delete i; } + + int *i; +}; + +struct Foo { + Foo(IntPtr); + void bar(); + + IntPtr i; +}; + +void bar() { + IntPtr ptr; + int *i = ptr.i; + Foo f(static_cast<IntPtr &&>(ptr)); + *i = 99; // no-warning +} +} // namespace ctor_argument diff --git a/test/Analysis/temporaries.mm b/test/Analysis/temporaries.mm new file mode 100644 index 000000000000..3b6166db6e30 --- /dev/null +++ b/test/Analysis/temporaries.mm @@ -0,0 +1,23 @@ +// RUN: %clang_analyze_cc1 -analyzer-checker core,cplusplus -verify %s + +// expected-no-diagnostics + +// Stripped down unique_ptr<int> +struct IntPtr { + IntPtr(): i(new int) {} + IntPtr(IntPtr &&o): i(o.i) { o.i = nullptr; } + ~IntPtr() { delete i; } + + int *i; +}; + +@interface Foo {} + -(void) foo: (IntPtr)arg; +@end + +void bar(Foo *f) { + IntPtr ptr; + int *i = ptr.i; + [f foo: static_cast<IntPtr &&>(ptr)]; + *i = 99; // no-warning +} diff --git a/test/CodeGen/aapcs-align.cc b/test/CodeGen/aapcs-align.cc new file mode 100644 index 000000000000..40fba7823524 --- /dev/null +++ b/test/CodeGen/aapcs-align.cc @@ -0,0 +1,141 @@ +// REQUIRES: arm-registered-target +// RUN: %clang_cc1 -triple arm-none-none-eabi \ +// RUN: -O2 \ +// RUN: -target-cpu cortex-a8 \ +// RUN: -emit-llvm -o - %s | FileCheck %s + +extern "C" { + +// Base case, nothing interesting. +struct S { + int x, y; +}; + +void f0(int, S); +void f0m(int, int, int, int, int, S); +void g0() { + S s = {6, 7}; + f0(1, s); + f0m(1, 2, 3, 4, 5, s); +} +// CHECK: define void @g0 +// CHECK: call void @f0(i32 1, [2 x i32] [i32 6, i32 7] +// CHECK: call void @f0m(i32 1, i32 2, i32 3, i32 4, i32 5, [2 x i32] [i32 6, i32 7] +// CHECK: declare void @f0(i32, [2 x i32]) +// CHECK: declare void @f0m(i32, i32, i32, i32, i32, [2 x i32]) + +// Aligned struct, passed according to its natural alignment. +struct __attribute__((aligned(8))) S8 { + int x, y; +} s8; + +void f1(int, S8); +void f1m(int, int, int, int, int, S8); +void g1() { + S8 s = {6, 7}; + f1(1, s); + f1m(1, 2, 3, 4, 5, s); +} +// CHECK: define void @g1 +// CHECK: call void @f1(i32 1, [2 x i32] [i32 6, i32 7] +// CHECK: call void @f1m(i32 1, i32 2, i32 3, i32 4, i32 5, [2 x i32] [i32 6, i32 7] +// CHECK: declare void @f1(i32, [2 x i32]) +// CHECK: declare void @f1m(i32, i32, i32, i32, i32, [2 x i32]) + +// Aligned struct, passed according to its natural alignment. +struct alignas(16) S16 { + int x, y; +}; + +extern "C" void f2(int, S16); +extern "C" void f2m(int, int, int, int, int, S16); + +void g2() { + S16 s = {6, 7}; + f2(1, s); + f2m(1, 2, 3, 4, 5, s); +} +// CHECK: define void @g2 +// CHECK: call void @f2(i32 1, [4 x i32] [i32 6, i32 7 +// CHECK: call void @f2m(i32 1, i32 2, i32 3, i32 4, i32 5, [4 x i32] [i32 6, i32 7 +// CHECK: declare void @f2(i32, [4 x i32]) +// CHECK: declare void @f2m(i32, i32, i32, i32, i32, [4 x i32]) + +// Increased natural alignment. +struct SF8 { + int x __attribute__((aligned(8))); + int y; +}; + +void f3(int, SF8); +void f3m(int, int, int, int, int, SF8); +void g3() { + SF8 s = {6, 7}; + f3(1, s); + f3m(1, 2, 3, 4, 5, s); +} +// CHECK: define void @g3 +// CHECK: call void @f3(i32 1, [1 x i64] [i64 30064771078] +// CHECK: call void @f3m(i32 1, i32 2, i32 3, i32 4, i32 5, [1 x i64] [i64 30064771078] +// CHECK: declare void @f3(i32, [1 x i64]) +// CHECK: declare void @f3m(i32, i32, i32, i32, i32, [1 x i64]) + +// Increased natural alignment, capped to 8 though. +struct SF16 { + int x; + int y alignas(16); + int z, a, b, c, d, e, f, g, h, i, j, k; +}; + +void f4(int, SF16); +void f4m(int, int, int, int, int, SF16); +void g4() { + SF16 s = {6, 7}; + f4(1, s); + f4m(1, 2, 3, 4, 5, s); +} +// CHECK: define void @g4 +// CHECK: call void @f4(i32 1, %struct.SF16* byval nonnull align 8 +// CHECK: call void @f4m(i32 1, i32 2, i32 3, i32 4, i32 5, %struct.SF16* byval nonnull align 8 +// CHECK: declare void @f4(i32, %struct.SF16* byval align 8) +// CHECK: declare void @f4m(i32, i32, i32, i32, i32, %struct.SF16* byval align 8) + +// Packed structure. +struct __attribute__((packed)) P { + int x; + long long u; +}; + +void f5(int, P); +void f5m(int, int, int, int, int, P); +void g5() { + P s = {6, 7}; + f5(1, s); + f5m(1, 2, 3, 4, 5, s); +} +// CHECK: define void @g5 +// CHECK: call void @f5(i32 1, [3 x i32] [i32 6, i32 7, i32 0]) +// CHECK: call void @f5m(i32 1, i32 2, i32 3, i32 4, i32 5, [3 x i32] [i32 6, i32 7, i32 0]) +// CHECK: declare void @f5(i32, [3 x i32]) +// CHECK: declare void @f5m(i32, i32, i32, i32, i32, [3 x i32]) + + +// Packed and aligned, alignement causes padding at the end. +struct __attribute__((packed, aligned(8))) P8 { + int x; + long long u; +}; + +void f6(int, P8); +void f6m(int, int, int, int, int, P8); +void g6() { + P8 s = {6, 7}; + f6(1, s); + f6m(1, 2, 3, 4, 5, s); +} +// CHECK: define void @g6 +// CHECK: call void @f6(i32 1, [4 x i32] [i32 6, i32 7, i32 0, i32 0]) +// CHECK: call void @f6m(i32 1, i32 2, i32 3, i32 4, i32 5, [4 x i32] [i32 6, i32 7, i32 0, i32 0]) +// CHECK: declare void @f6(i32, [4 x i32]) +// CHECK: declare void @f6m(i32, i32, i32, i32, i32, [4 x i32]) +} diff --git a/test/CodeGen/aapcs64-align.cc b/test/CodeGen/aapcs64-align.cc new file mode 100644 index 000000000000..1b7c99ea8719 --- /dev/null +++ b/test/CodeGen/aapcs64-align.cc @@ -0,0 +1,103 @@ +// REQUIRES: arm-registered-target +// RUN: %clang_cc1 -triple aarch64-none-none-eabi \ +// RUN: -O2 \ +// RUN: -emit-llvm -o - %s | FileCheck %s + +extern "C" { + +// Base case, nothing interesting. +struct S { + long x, y; +}; + +void f0(long, S); +void f0m(long, long, long, long, long, S); +void g0() { + S s = {6, 7}; + f0(1, s); + f0m(1, 2, 3, 4, 5, s); +} +// CHECK: define void @g0 +// CHECK: call void @f0(i64 1, [2 x i64] [i64 6, i64 7] +// CHECK: call void @f0m{{.*}}[2 x i64] [i64 6, i64 7] +// CHECK: declare void @f0(i64, [2 x i64]) +// CHECK: declare void @f0m(i64, i64, i64, i64, i64, [2 x i64]) + +// Aligned struct, passed according to its natural alignment. +struct __attribute__((aligned(16))) S16 { + long x, y; +} s16; + +void f1(long, S16); +void f1m(long, long, long, long, long, S16); +void g1() { + S16 s = {6, 7}; + f1(1, s); + f1m(1, 2, 3, 4, 5, s); +} +// CHECK: define void @g1 +// CHECK: call void @f1{{.*}}[2 x i64] [i64 6, i64 7] +// CHECK: call void @f1m{{.*}}[2 x i64] [i64 6, i64 7] +// CHECK: declare void @f1(i64, [2 x i64]) +// CHECK: declare void @f1m(i64, i64, i64, i64, i64, [2 x i64]) + +// Increased natural alignment. +struct SF16 { + long x __attribute__((aligned(16))); + long y; +}; + +void f3(long, SF16); +void f3m(long, long, long, long, long, SF16); +void g3() { + SF16 s = {6, 7}; + f3(1, s); + f3m(1, 2, 3, 4, 5, s); +} +// CHECK: define void @g3 +// CHECK: call void @f3(i64 1, i128 129127208515966861318) +// CHECK: call void @f3m(i64 1, i64 2, i64 3, i64 4, i64 5, i128 129127208515966861318) +// CHECK: declare void @f3(i64, i128) +// CHECK: declare void @f3m(i64, i64, i64, i64, i64, i128) + + +// Packed structure. +struct __attribute__((packed)) P { + int x; + long u; +}; + +void f4(int, P); +void f4m(int, int, int, int, int, P); +void g4() { + P s = {6, 7}; + f4(1, s); + f4m(1, 2, 3, 4, 5, s); +} +// CHECK: define void @g4() +// CHECK: call void @f4(i32 1, [2 x i64] [i64 30064771078, i64 0]) +// CHECK: void @f4m(i32 1, i32 2, i32 3, i32 4, i32 5, [2 x i64] [i64 30064771078, i64 0]) +// CHECK: declare void @f4(i32, [2 x i64]) +// CHECK: declare void @f4m(i32, i32, i32, i32, i32, [2 x i64]) + + +// Packed structure, overaligned, same as above. +struct __attribute__((packed, aligned(16))) P16 { + int x; + long y; +}; + +void f5(int, P16); +void f5m(int, int, int, int, int, P16); + void g5() { + P16 s = {6, 7}; + f5(1, s); + f5m(1, 2, 3, 4, 5, s); +} +// CHECK: define void @g5() +// CHECK: call void @f5(i32 1, [2 x i64] [i64 30064771078, i64 0]) +// CHECK: void @f5m(i32 1, i32 2, i32 3, i32 4, i32 5, [2 x i64] [i64 30064771078, i64 0]) +// CHECK: declare void @f5(i32, [2 x i64]) +// CHECK: declare void @f5m(i32, i32, i32, i32, i32, [2 x i64]) + +} diff --git a/test/CodeGen/arm-arguments.c b/test/CodeGen/arm-arguments.c index ef4e76054ff8..ca6b70b44621 100644 --- a/test/CodeGen/arm-arguments.c +++ b/test/CodeGen/arm-arguments.c @@ -211,10 +211,13 @@ float32x4_t f35(int i, s35_with_align s1, s35_with_align s2) { // APCS-GNU: call void @llvm.memcpy.p0i8.p0i8.i32(i8* align {{[0-9]+}} %[[b]], i8* align {{[0-9]+}} %[[c]] // APCS-GNU: %[[d:.*]] = bitcast %struct.s35* %[[a]] to <4 x float>* // APCS-GNU: load <4 x float>, <4 x float>* %[[d]], align 16 -// AAPCS-LABEL: define arm_aapcscc <4 x float> @f35(i32 %i, %struct.s35* byval align 8, %struct.s35* byval align 8) -// AAPCS: %[[a:.*]] = alloca %struct.s35, align 16 -// AAPCS: %[[b:.*]] = bitcast %struct.s35* %[[a]] to i8* -// AAPCS: %[[c:.*]] = bitcast %struct.s35* %0 to i8* -// AAPCS: call void @llvm.memcpy.p0i8.p0i8.i32(i8* align 16 %[[b]], i8* align 8 %[[c]] -// AAPCS: %[[d:.*]] = bitcast %struct.s35* %[[a]] to <4 x float>* -// AAPCS: load <4 x float>, <4 x float>* %[[d]], align 16 + +// AAPCS-LABEL: define arm_aapcscc <4 x float> @f35(i32 %i, %struct.s35* byval align 4 %s1, %struct.s35* byval align 4 %s2) +// AAPCS: %[[a_addr:.*]] = alloca <4 x float>, align 16 +// AAPCS: %[[b_addr:.*]] = alloca <4 x float>, align 16 +// AAPCS: %[[p1:.*]] = bitcast %struct.s35* %s1 to <4 x float>* +// AAPCS: %[[a:.*]] = load <4 x float>, <4 x float>* %[[p1]], align 4 +// AAPCS: %[[p2:.*]] = bitcast %struct.s35* %s2 to <4 x float>* +// AAPCS: %[[b:.*]] = load <4 x float>, <4 x float>* %[[p2]], align 4 +// AAPCS: store <4 x float> %[[a]], <4 x float>* %[[a_addr]], align 16 +// AAPCS: store <4 x float> %[[b]], <4 x float>* %[[b_addr]], align 16 diff --git a/test/CodeGen/builtin-memfns.c b/test/CodeGen/builtin-memfns.c index d93a5aadae27..48626774531d 100644 --- a/test/CodeGen/builtin-memfns.c +++ b/test/CodeGen/builtin-memfns.c @@ -1,5 +1,8 @@ // RUN: %clang_cc1 -triple i386-pc-linux-gnu -emit-llvm < %s| FileCheck %s +typedef __WCHAR_TYPE__ wchar_t; +typedef __SIZE_TYPE__ size_t; + // CHECK: @test1 // CHECK: call void @llvm.memset.p0i8.i32 // CHECK: call void @llvm.memset.p0i8.i32 @@ -83,3 +86,17 @@ void test9() { // CHECK: call void @llvm.memcpy{{.*}} align 16 {{.*}} align 16 {{.*}} 16, i1 false) __builtin_memcpy(x, y, sizeof(y)); } + +wchar_t dest; +wchar_t src; + +// CHECK-LABEL: @test10 +// FIXME: Consider lowering these to llvm.memcpy / llvm.memmove. +void test10() { + // CHECK: call i32* @wmemcpy(i32* @dest, i32* @src, i32 4) + __builtin_wmemcpy(&dest, &src, 4); + + // CHECK: call i32* @wmemmove(i32* @dest, i32* @src, i32 4) + __builtin_wmemmove(&dest, &src, 4); +} + diff --git a/test/CodeGen/catch-implicit-integer-truncations.c b/test/CodeGen/catch-implicit-integer-truncations.c new file mode 100644 index 000000000000..b09f7ddfaedf --- /dev/null +++ b/test/CodeGen/catch-implicit-integer-truncations.c @@ -0,0 +1,395 @@ +// RUN: %clang_cc1 -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck %s --check-prefix=CHECK +// RUN: %clang_cc1 -fsanitize=implicit-integer-truncation -fno-sanitize-recover=implicit-integer-truncation -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck %s --check-prefixes=CHECK,CHECK-SANITIZE,CHECK-SANITIZE-ANYRECOVER,CHECK-SANITIZE-NORECOVER +// RUN: %clang_cc1 -fsanitize=implicit-integer-truncation -fsanitize-recover=implicit-integer-truncation -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck %s --check-prefixes=CHECK,CHECK-SANITIZE,CHECK-SANITIZE-ANYRECOVER,CHECK-SANITIZE-RECOVER +// RUN: %clang_cc1 -fsanitize=implicit-integer-truncation -fsanitize-trap=implicit-integer-truncation -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck %s --check-prefixes=CHECK,CHECK-SANITIZE,CHECK-SANITIZE-TRAP + +// CHECK-SANITIZE-ANYRECOVER: @[[UNSIGNED_INT:.*]] = {{.*}} c"'unsigned int'\00" } +// CHECK-SANITIZE-ANYRECOVER: @[[UNSIGNED_CHAR:.*]] = {{.*}} c"'unsigned char'\00" } + +// CHECK-SANITIZE-ANYRECOVER: @[[LINE_100:.*]] = {{.*}}, i32 100, i32 10 }, {{.*}}* @[[UNSIGNED_INT]], {{.*}}* @[[UNSIGNED_CHAR]], i8 0 } +// CHECK-SANITIZE-ANYRECOVER: @[[SIGNED_INT:.*]] = {{.*}} c"'int'\00" } +// CHECK-SANITIZE-ANYRECOVER: @[[LINE_200:.*]] = {{.*}}, i32 200, i32 10 }, {{.*}}* @[[SIGNED_INT]], {{.*}}* @[[UNSIGNED_CHAR]], i8 0 } +// CHECK-SANITIZE-ANYRECOVER: @[[SIGNED_CHAR:.*]] = {{.*}} c"'signed char'\00" } +// CHECK-SANITIZE-ANYRECOVER: @[[LINE_300:.*]] = {{.*}}, i32 300, i32 10 }, {{.*}}* @[[UNSIGNED_INT]], {{.*}}* @[[SIGNED_CHAR]], i8 0 } +// CHECK-SANITIZE-ANYRECOVER: @[[LINE_400:.*]] = {{.*}}, i32 400, i32 10 }, {{.*}}* @[[SIGNED_INT]], {{.*}}* @[[SIGNED_CHAR]], i8 0 } + +// CHECK-SANITIZE-ANYRECOVER: @[[UINT32:.*]] = {{.*}} c"'uint32_t' (aka 'unsigned int')\00" } +// CHECK-SANITIZE-ANYRECOVER: @[[UINT8:.*]] = {{.*}} c"'uint8_t' (aka 'unsigned char')\00" } +// CHECK-SANITIZE-ANYRECOVER: @[[LINE_500:.*]] = {{.*}}, i32 500, i32 10 }, {{.*}}* @[[UINT32]], {{.*}}* @[[UINT8]], i8 0 } + +// ========================================================================== // +// The expected true-positives. These are implicit conversions, and they truncate. +// ========================================================================== // + +// CHECK-LABEL: @unsigned_int_to_unsigned_char +unsigned char unsigned_int_to_unsigned_char(unsigned int src) { + // CHECK: %[[DST:.*]] = trunc i32 %[[SRC:.*]] to i8 + // CHECK-SANITIZE-NEXT: %[[ANYEXT:.*]] = zext i8 %[[DST]] to i32, !nosanitize + // CHECK-SANITIZE-NEXT: %[[TRUNCHECK:.*]] = icmp eq i32 %[[ANYEXT]], %[[SRC]], !nosanitize + // CHECK-SANITIZE-NEXT: br i1 %[[TRUNCHECK]], label %[[CONT:.*]], label %[[HANDLER_IMPLICIT_CONVERSION:[^,]+]],{{.*}} !nosanitize + // CHECK-SANITIZE: [[HANDLER_IMPLICIT_CONVERSION]]: + // CHECK-SANITIZE-ANYRECOVER-NEXT: %[[EXTSRC:.*]] = zext i32 %[[SRC]] to i64, !nosanitize + // CHECK-SANITIZE-ANYRECOVER-NEXT: %[[EXTDST:.*]] = zext i8 %[[DST]] to i64, !nosanitize + // CHECK-SANITIZE-NORECOVER-NEXT: call void @__ubsan_handle_implicit_conversion_abort(i8* bitcast ({ {{{.*}}}, {{{.*}}}*, {{{.*}}}*, i8 }* @[[LINE_100]] to i8*), i64 %[[EXTSRC]], i64 %[[EXTDST]]){{.*}}, !nosanitize + // CHECK-SANITIZE-RECOVER-NEXT: call void @__ubsan_handle_implicit_conversion(i8* bitcast ({ {{{.*}}}, {{{.*}}}*, {{{.*}}}*, i8 }* @[[LINE_100]] to i8*), i64 %[[EXTSRC]], i64 %[[EXTDST]]){{.*}}, !nosanitize + // CHECK-SANITIZE-TRAP-NEXT: call void @llvm.trap(){{.*}}, !nosanitize + // CHECK-SANITIZE-TRAP-NEXT: unreachable, !nosanitize + // CHECK-SANITIZE: [[CONT]]: + // CHECK: ret i8 %[[DST]] +#line 100 + return src; +} + +// CHECK-LABEL: @signed_int_to_unsigned_char +unsigned char signed_int_to_unsigned_char(signed int src) { + // CHECK: %[[DST:.*]] = trunc i32 %[[SRC:.*]] to i8 + // CHECK-SANITIZE-NEXT: %[[ANYEXT:.*]] = zext i8 %[[DST]] to i32, !nosanitize + // CHECK-SANITIZE-NEXT: %[[TRUNCHECK:.*]] = icmp eq i32 %[[ANYEXT]], %[[SRC]], !nosanitize + // CHECK-SANITIZE-NEXT: br i1 %[[TRUNCHECK]], label %[[CONT:.*]], label %[[HANDLER_IMPLICIT_CONVERSION:[^,]+]],{{.*}} !nosanitize + // CHECK-SANITIZE: [[HANDLER_IMPLICIT_CONVERSION]]: + // CHECK-SANITIZE-ANYRECOVER-NEXT: %[[EXTSRC:.*]] = zext i32 %[[SRC]] to i64, !nosanitize + // CHECK-SANITIZE-ANYRECOVER-NEXT: %[[EXTDST:.*]] = zext i8 %[[DST]] to i64, !nosanitize + // CHECK-SANITIZE-NORECOVER-NEXT: call void @__ubsan_handle_implicit_conversion_abort(i8* bitcast ({ {{{.*}}}, {{{.*}}}*, {{{.*}}}*, i8 }* @[[LINE_200]] to i8*), i64 %[[EXTSRC]], i64 %[[EXTDST]]){{.*}}, !nosanitize + // CHECK-SANITIZE-RECOVER-NEXT: call void @__ubsan_handle_implicit_conversion(i8* bitcast ({ {{{.*}}}, {{{.*}}}*, {{{.*}}}*, i8 }* @[[LINE_200]] to i8*), i64 %[[EXTSRC]], i64 %[[EXTDST]]){{.*}}, !nosanitize + // CHECK-SANITIZE-TRAP-NEXT: call void @llvm.trap(){{.*}}, !nosanitize + // CHECK-SANITIZE-TRAP-NEXT: unreachable, !nosanitize + // CHECK-SANITIZE: [[CONT]]: + // CHECK: ret i8 %[[DST]] +#line 200 + return src; +} + +// CHECK-LABEL: @unsigned_int_to_signed_char +signed char unsigned_int_to_signed_char(unsigned int src) { + // CHECK: %[[DST:.*]] = trunc i32 %[[SRC:.*]] to i8 + // CHECK-SANITIZE-NEXT: %[[ANYEXT:.*]] = sext i8 %[[DST]] to i32, !nosanitize + // CHECK-SANITIZE-NEXT: %[[TRUNCHECK:.*]] = icmp eq i32 %[[ANYEXT]], %[[SRC]], !nosanitize + // CHECK-SANITIZE-NEXT: br i1 %[[TRUNCHECK]], label %[[CONT:.*]], label %[[HANDLER_IMPLICIT_CONVERSION:[^,]+]],{{.*}} !nosanitize + // CHECK-SANITIZE: [[HANDLER_IMPLICIT_CONVERSION]]: + // CHECK-SANITIZE-ANYRECOVER-NEXT: %[[EXTSRC:.*]] = zext i32 %[[SRC]] to i64, !nosanitize + // CHECK-SANITIZE-ANYRECOVER-NEXT: %[[EXTDST:.*]] = zext i8 %[[DST]] to i64, !nosanitize + // CHECK-SANITIZE-NORECOVER-NEXT: call void @__ubsan_handle_implicit_conversion_abort(i8* bitcast ({ {{{.*}}}, {{{.*}}}*, {{{.*}}}*, i8 }* @[[LINE_300]] to i8*), i64 %[[EXTSRC]], i64 %[[EXTDST]]){{.*}}, !nosanitize + // CHECK-SANITIZE-RECOVER-NEXT: call void @__ubsan_handle_implicit_conversion(i8* bitcast ({ {{{.*}}}, {{{.*}}}*, {{{.*}}}*, i8 }* @[[LINE_300]] to i8*), i64 %[[EXTSRC]], i64 %[[EXTDST]]){{.*}}, !nosanitize + // CHECK-SANITIZE-TRAP-NEXT: call void @llvm.trap(){{.*}}, !nosanitize + // CHECK-SANITIZE-TRAP-NEXT: unreachable, !nosanitize + // CHECK-SANITIZE: [[CONT]]: + // CHECK: ret i8 %[[DST]] +#line 300 + return src; +} + +// CHECK-LABEL: @signed_int_to_signed_char +signed char signed_int_to_signed_char(signed int src) { + // CHECK: %[[DST:.*]] = trunc i32 %[[SRC:.*]] to i8 + // CHECK-SANITIZE-NEXT: %[[ANYEXT:.*]] = sext i8 %[[DST]] to i32, !nosanitize + // CHECK-SANITIZE-NEXT: %[[TRUNCHECK:.*]] = icmp eq i32 %[[ANYEXT]], %[[SRC]], !nosanitize + // CHECK-SANITIZE-NEXT: br i1 %[[TRUNCHECK]], label %[[CONT:.*]], label %[[HANDLER_IMPLICIT_CONVERSION:[^,]+]],{{.*}} !nosanitize + // CHECK-SANITIZE: [[HANDLER_IMPLICIT_CONVERSION]]: + // CHECK-SANITIZE-ANYRECOVER-NEXT: %[[EXTSRC:.*]] = zext i32 %[[SRC]] to i64, !nosanitize + // CHECK-SANITIZE-ANYRECOVER-NEXT: %[[EXTDST:.*]] = zext i8 %[[DST]] to i64, !nosanitize + // CHECK-SANITIZE-NORECOVER-NEXT: call void @__ubsan_handle_implicit_conversion_abort(i8* bitcast ({ {{{.*}}}, {{{.*}}}*, {{{.*}}}*, i8 }* @[[LINE_400]] to i8*), i64 %[[EXTSRC]], i64 %[[EXTDST]]){{.*}}, !nosanitize + // CHECK-SANITIZE-RECOVER-NEXT: call void @__ubsan_handle_implicit_conversion(i8* bitcast ({ {{{.*}}}, {{{.*}}}*, {{{.*}}}*, i8 }* @[[LINE_400]] to i8*), i64 %[[EXTSRC]], i64 %[[EXTDST]]){{.*}}, !nosanitize + // CHECK-SANITIZE-TRAP-NEXT: call void @llvm.trap(){{.*}}, !nosanitize + // CHECK-SANITIZE-TRAP-NEXT: unreachable, !nosanitize + // CHECK-SANITIZE: [[CONT]]: + // CHECK: ret i8 %[[DST]] +#line 400 + return src; +} + +// ========================================================================== // +// Check canonical type stuff +// ========================================================================== // + +typedef unsigned int uint32_t; +typedef unsigned char uint8_t; + +// CHECK-LABEL: @uint32_to_uint8 +uint8_t uint32_to_uint8(uint32_t src) { + // CHECK: %[[DST:.*]] = trunc i32 %[[SRC:.*]] to i8 + // CHECK-SANITIZE-NEXT: %[[ANYEXT:.*]] = zext i8 %[[DST]] to i32, !nosanitize + // CHECK-SANITIZE-NEXT: %[[TRUNCHECK:.*]] = icmp eq i32 %[[ANYEXT]], %[[SRC]], !nosanitize + // CHECK-SANITIZE-NEXT: br i1 %[[TRUNCHECK]], label %[[CONT:.*]], label %[[HANDLER_IMPLICIT_CONVERSION:[^,]+]],{{.*}} !nosanitize + // CHECK-SANITIZE: [[HANDLER_IMPLICIT_CONVERSION]]: + // CHECK-SANITIZE-ANYRECOVER-NEXT: %[[EXTSRC:.*]] = zext i32 %[[SRC]] to i64, !nosanitize + // CHECK-SANITIZE-ANYRECOVER-NEXT: %[[EXTDST:.*]] = zext i8 %[[DST]] to i64, !nosanitize + // CHECK-SANITIZE-NORECOVER-NEXT: call void @__ubsan_handle_implicit_conversion_abort(i8* bitcast ({ {{{.*}}}, {{{.*}}}*, {{{.*}}}*, i8 }* @[[LINE_500]] to i8*), i64 %[[EXTSRC]], i64 %[[EXTDST]]){{.*}}, !nosanitize + // CHECK-SANITIZE-RECOVER-NEXT: call void @__ubsan_handle_implicit_conversion(i8* bitcast ({ {{{.*}}}, {{{.*}}}*, {{{.*}}}*, i8 }* @[[LINE_500]] to i8*), i64 %[[EXTSRC]], i64 %[[EXTDST]]){{.*}}, !nosanitize + // CHECK-SANITIZE-TRAP-NEXT: call void @llvm.trap(){{.*}}, !nosanitize + // CHECK-SANITIZE-TRAP-NEXT: unreachable, !nosanitize + // CHECK-SANITIZE: [[CONT]]: + // CHECK: ret i8 %[[DST]] +#line 500 + return src; +} + +// ========================================================================== // +// Check that explicit conversion does not interfere with implicit conversion +// ========================================================================== // +// These contain one implicit truncating conversion, and one explicit truncating conversion. +// We want to make sure that we still diagnose the implicit conversion. + +// Implicit truncation after explicit truncation. +// CHECK-LABEL: @explicit_conversion_interference0 +unsigned char explicit_conversion_interference0(unsigned int c) { + // CHECK-SANITIZE: %[[ANYEXT:.*]] = zext i8 %[[DST:.*]] to i16, !nosanitize + // CHECK-SANITIZE: call + // CHECK-SANITIZE-NOT: call + // CHECK: } + return (unsigned short)c; +} + +// Implicit truncation before explicit truncation. +// CHECK-LABEL: @explicit_conversion_interference1 +unsigned char explicit_conversion_interference1(unsigned int c) { + // CHECK-SANITIZE: %[[ANYEXT:.*]] = zext i16 %[[DST:.*]] to i32, !nosanitize + // CHECK-SANITIZE: call + // CHECK-SANITIZE-NOT: call + // CHECK: } + unsigned short b; + return (unsigned char)(b = c); +} + +// ========================================================================== // +// The expected true-negatives. +// ========================================================================== // + +// Sanitization is explicitly disabled. +// ========================================================================== // + +// CHECK-LABEL: @blacklist_0 +__attribute__((no_sanitize("undefined"))) unsigned char blacklist_0(unsigned int src) { + // We are not in "undefined" group, so that doesn't work. + // CHECK-SANITIZE: call + // CHECK: } + return src; +} + +// CHECK-LABEL: @blacklist_1 +__attribute__((no_sanitize("implicit-conversion"))) unsigned char blacklist_1(unsigned int src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return src; +} + +// CHECK-LABEL: @blacklist_2 +__attribute__((no_sanitize("implicit-integer-truncation"))) unsigned char blacklist_2(unsigned int src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return src; +} + +// Explicit truncating conversions. +// ========================================================================== // + +// CHECK-LABEL: @explicit_unsigned_int_to_unsigned_char +unsigned char explicit_unsigned_int_to_unsigned_char(unsigned int src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return (unsigned char)src; +} + +// CHECK-LABEL: @explicit_signed_int_to_unsigned_char +unsigned char explicit_signed_int_to_unsigned_char(signed int src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return (unsigned char)src; +} + +// CHECK-LABEL: @explicit_unsigned_int_to_signed_char +signed char explicit_unsigned_int_to_signed_char(unsigned int src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return (signed char)src; +} + +// CHECK-LABEL: @explicit_signed_int_to_signed_char +signed char explicit_signed_int_to_signed_char(signed int src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return (signed char)src; +} + +// Explicit NOP conversions. +// ========================================================================== // + +// CHECK-LABEL: @explicit_unsigned_int_to_unsigned_int +unsigned int explicit_unsigned_int_to_unsigned_int(unsigned int src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return (unsigned int)src; +} + +// CHECK-LABEL: @explicit_signed_int_to_signed_int +signed int explicit_signed_int_to_signed_int(signed int src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return (signed int)src; +} + +// CHECK-LABEL: @explicit_unsigned_char_to_signed_char +unsigned char explicit_unsigned_char_to_signed_char(unsigned char src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return (unsigned char)src; +} + +// CHECK-LABEL: @explicit_signed_char_to_signed_char +signed char explicit_signed_char_to_signed_char(signed char src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return (signed char)src; +} + +// upcasts. +// ========================================================================== // + +// CHECK-LABEL: @unsigned_char_to_unsigned_int +unsigned int unsigned_char_to_unsigned_int(unsigned char src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return src; +} + +// CHECK-LABEL: @signed_char_to_unsigned_int +unsigned int signed_char_to_unsigned_int(signed char src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return src; +} + +// CHECK-LABEL: @unsigned_char_to_signed_int +signed int unsigned_char_to_signed_int(unsigned char src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return src; +} + +// CHECK-LABEL: @signed_char_to_signed_int +signed int signed_char_to_signed_int(signed char src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return src; +} + +// Explicit upcasts. +// ========================================================================== // + +// CHECK-LABEL: @explicit_unsigned_char_to_unsigned_int +unsigned int explicit_unsigned_char_to_unsigned_int(unsigned char src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return (unsigned int)src; +} + +// CHECK-LABEL: @explicit_signed_char_to_unsigned_int +unsigned int explicit_signed_char_to_unsigned_int(signed char src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return (unsigned int)src; +} + +// CHECK-LABEL: @explicit_unsigned_char_to_signed_int +signed int explicit_unsigned_char_to_signed_int(unsigned char src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return (signed int)src; +} + +// CHECK-LABEL: @explicit_signed_char_to_signed_int +signed int explicit_signed_char_to_signed_int(signed char src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return (signed int)src; +} + +// conversions to to boolean type are not counted as truncation. +// ========================================================================== // + +// CHECK-LABEL: @unsigned_int_to_bool +_Bool unsigned_int_to_bool(unsigned int src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return src; +} + +// CHECK-LABEL: @signed_int_to_bool +_Bool signed_int_to_bool(signed int src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return src; +} + +// CHECK-LABEL: @explicit_unsigned_int_to_bool +_Bool explicit_unsigned_int_to_bool(unsigned int src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return (_Bool)src; +} + +// CHECK-LABEL: @explicit_signed_int_to_bool +_Bool explicit_signed_int_to_bool(signed int src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return (_Bool)src; +} + +// Explicit truncating conversions from pointer to a much-smaller integer. +// Can not have an implicit conversion from pointer to an integer. +// Can not have an implicit conversion between two enums. +// ========================================================================== // + +// CHECK-LABEL: @explicit_voidptr_to_unsigned_char +unsigned char explicit_voidptr_to_unsigned_char(void *src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return (unsigned char)src; +} + +// CHECK-LABEL: @explicit_voidptr_to_signed_char +signed char explicit_voidptr_to_signed_char(void *src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return (signed char)src; +} + +// Implicit truncating conversions from floating-point may result in precision loss. +// ========================================================================== // + +// CHECK-LABEL: @float_to_unsigned_int +unsigned int float_to_unsigned_int(float src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return src; +} + +// CHECK-LABEL: @float_to_signed_int +signed int float_to_signed_int(float src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return src; +} + +// CHECK-LABEL: @double_to_unsigned_int +unsigned int double_to_unsigned_int(double src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return src; +} + +// CHECK-LABEL: @double_to_signed_int +signed int double_to_signed_int(double src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return src; +} + +// Implicit truncating conversions between fp may result in precision loss. +// ========================================================================== // + +// CHECK-LABEL: @double_to_float +float double_to_float(double src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return src; +} diff --git a/test/CodeGen/exceptions-seh-finally.c b/test/CodeGen/exceptions-seh-finally.c index d863eb1bb47e..655f0a782f54 100644 --- a/test/CodeGen/exceptions-seh-finally.c +++ b/test/CodeGen/exceptions-seh-finally.c @@ -1,5 +1,6 @@ // RUN: %clang_cc1 %s -triple x86_64-pc-win32 -fms-extensions -emit-llvm -o - | FileCheck %s // RUN: %clang_cc1 %s -triple i686-pc-win32 -fms-extensions -emit-llvm -o - | FileCheck %s +// RUN: %clang_cc1 %s -triple aarch64-windows -fms-extensions -emit-llvm -o - | FileCheck %s void abort(void) __attribute__((noreturn)); void might_crash(void); diff --git a/test/CodeGen/exceptions-seh.c b/test/CodeGen/exceptions-seh.c index b38c7a2490c0..1e3e2236ac6d 100644 --- a/test/CodeGen/exceptions-seh.c +++ b/test/CodeGen/exceptions-seh.c @@ -2,6 +2,8 @@ // RUN: | FileCheck %s --check-prefix=CHECK --check-prefix=X64 // RUN: %clang_cc1 %s -triple i686-pc-win32 -fms-extensions -emit-llvm -o - \ // RUN: | FileCheck %s --check-prefix=CHECK --check-prefix=X86 +// RUN: %clang_cc1 %s -triple aarch64-windows -fms-extensions -emit-llvm -o - \ +// RUN: | FileCheck %s --check-prefixes=CHECK,ARM64 // RUN: %clang_cc1 %s -triple i686-pc-windows-gnu -fms-extensions -emit-llvm -o - \ // RUN: | FileCheck %s --check-prefix=X86-GNU // RUN: %clang_cc1 %s -triple x86_64-pc-windows-gnu -fms-extensions -emit-llvm -o - \ @@ -29,12 +31,14 @@ int safe_div(int numerator, int denominator, int *res) { // CHECK-LABEL: define dso_local i32 @safe_div(i32 %numerator, i32 %denominator, i32* %res) // X64-SAME: personality i8* bitcast (i32 (...)* @__C_specific_handler to i8*) +// ARM64-SAME: personality i8* bitcast (i32 (...)* @__C_specific_handler to i8*) // X86-SAME: personality i8* bitcast (i32 (...)* @_except_handler3 to i8*) // CHECK: invoke void @try_body(i32 %{{.*}}, i32 %{{.*}}, i32* %{{.*}}) #[[NOINLINE:[0-9]+]] // CHECK: to label %{{.*}} unwind label %[[catchpad:[^ ]*]] // // CHECK: [[catchpad]] // X64: %[[padtoken:[^ ]*]] = catchpad within %{{[^ ]*}} [i8* null] +// ARM64: %[[padtoken:[^ ]*]] = catchpad within %{{[^ ]*}} [i8* null] // X86: %[[padtoken:[^ ]*]] = catchpad within %{{[^ ]*}} [i8* bitcast (i32 ()* @"?filt$0@0@safe_div@@" to i8*)] // CHECK-NEXT: catchret from %[[padtoken]] to label %[[except:[^ ]*]] // @@ -76,8 +80,10 @@ int filter_expr_capture(void) { // CHECK-LABEL: define dso_local i32 @filter_expr_capture() // X64-SAME: personality i8* bitcast (i32 (...)* @__C_specific_handler to i8*) +// ARM64-SAME: personality i8* bitcast (i32 (...)* @__C_specific_handler to i8*) // X86-SAME: personality i8* bitcast (i32 (...)* @_except_handler3 to i8*) // X64: call void (...) @llvm.localescape(i32* %[[r:[^ ,]*]]) +// ARM64: call void (...) @llvm.localescape(i32* %[[r:[^ ,]*]]) // X86: call void (...) @llvm.localescape(i32* %[[r:[^ ,]*]], i32* %[[code:[^ ,]*]]) // CHECK: store i32 42, i32* %[[r]] // CHECK: invoke void @j() #[[NOINLINE]] @@ -92,6 +98,10 @@ int filter_expr_capture(void) { // X64: %[[fp:[^ ]*]] = call i8* @llvm.x86.seh.recoverfp(i8* bitcast (i32 ()* @filter_expr_capture to i8*), i8* %frame_pointer) // X64: call i8* @llvm.localrecover(i8* bitcast (i32 ()* @filter_expr_capture to i8*), i8* %[[fp]], i32 0) // +// ARM64-LABEL: define internal i32 @"?filt$0@0@filter_expr_capture@@"(i8* %exception_pointers, i8* %frame_pointer) +// ARM64: %[[fp:[^ ]*]] = call i8* @llvm.x86.seh.recoverfp(i8* bitcast (i32 ()* @filter_expr_capture to i8*), i8* %frame_pointer) +// ARM64: call i8* @llvm.localrecover(i8* bitcast (i32 ()* @filter_expr_capture to i8*), i8* %[[fp]], i32 0) +// // X86-LABEL: define internal i32 @"?filt$0@0@filter_expr_capture@@"() // X86: %[[ebp:[^ ]*]] = call i8* @llvm.frameaddress(i32 1) // X86: %[[fp:[^ ]*]] = call i8* @llvm.x86.seh.recoverfp(i8* bitcast (i32 ()* @filter_expr_capture to i8*), i8* %[[ebp]]) @@ -116,6 +126,7 @@ int nested_try(void) { } // CHECK-LABEL: define dso_local i32 @nested_try() // X64-SAME: personality i8* bitcast (i32 (...)* @__C_specific_handler to i8*) +// ARM64-SAME: personality i8* bitcast (i32 (...)* @__C_specific_handler to i8*) // X86-SAME: personality i8* bitcast (i32 (...)* @_except_handler3 to i8*) // CHECK: store i32 42, i32* %[[r:[^ ,]*]] // CHECK: invoke void @j() #[[NOINLINE]] @@ -176,6 +187,7 @@ int basic_finally(int g) { } // CHECK-LABEL: define dso_local i32 @basic_finally(i32 %g) // X64-SAME: personality i8* bitcast (i32 (...)* @__C_specific_handler to i8*) +// ARM64-SAME: personality i8* bitcast (i32 (...)* @__C_specific_handler to i8*) // X86-SAME: personality i8* bitcast (i32 (...)* @_except_handler3 to i8*) // CHECK: %[[g_addr:[^ ]*]] = alloca i32, align 4 // CHECK: call void (...) @llvm.localescape(i32* %[[g_addr]]) @@ -275,6 +287,8 @@ int exception_code_in_except(void) { // CHECK: catchret from %[[pad]] // X64: %[[code:[^ ]*]] = call i32 @llvm.eh.exceptioncode(token %[[pad]]) // X64: store i32 %[[code]], i32* %[[code_slot]] +// ARM64: %[[code:[^ ]*]] = call i32 @llvm.eh.exceptioncode(token %[[pad]]) +// ARM64: store i32 %[[code]], i32* %[[code_slot]] // CHECK: %[[ret1:[^ ]*]] = load i32, i32* %[[code_slot]] // CHECK: store i32 %[[ret1]], i32* %[[ret_slot]] // CHECK: %[[ret2:[^ ]*]] = load i32, i32* %[[ret_slot]] diff --git a/test/CodeGen/mips-unsigned-ext-var.c b/test/CodeGen/mips-unsigned-ext-var.c index 2e04792cf375..a4dae53c184b 100644 --- a/test/CodeGen/mips-unsigned-ext-var.c +++ b/test/CodeGen/mips-unsigned-ext-var.c @@ -17,6 +17,6 @@ void foo1() { foo(1,f); } -//N64: call i32 (i32, ...) @foo(i32 signext undef, i32 signext -32) -//N32: call i32 (i32, ...) @foo(i32 signext undef, i32 signext -32) -//O32: call i32 (i32, ...) @foo(i32 signext undef, i32 signext -32)
\ No newline at end of file +//N64: call signext i32 (i32, ...) @foo(i32 signext undef, i32 signext -32) +//N32: call signext i32 (i32, ...) @foo(i32 signext undef, i32 signext -32) +//O32: call i32 (i32, ...) @foo(i32 signext undef, i32 signext -32) diff --git a/test/CodeGen/mips-varargs.c b/test/CodeGen/mips-varargs.c index 343914ad8df1..8f1a633b7df8 100644 --- a/test/CodeGen/mips-varargs.c +++ b/test/CodeGen/mips-varargs.c @@ -19,7 +19,9 @@ int test_i32(char *fmt, ...) { return v; } -// ALL-LABEL: define i32 @test_i32(i8*{{.*}} %fmt, ...) +// O32-LABEL: define i32 @test_i32(i8*{{.*}} %fmt, ...) +// N32-LABEL: define signext i32 @test_i32(i8*{{.*}} %fmt, ...) +// N64-LABEL: define signext i32 @test_i32(i8*{{.*}} %fmt, ...) // // O32: %va = alloca i8*, align [[$PTRALIGN:4]] // N32: %va = alloca i8*, align [[$PTRALIGN:4]] @@ -133,7 +135,9 @@ int test_v4i32(char *fmt, ...) { return v[0]; } -// ALL-LABEL: define i32 @test_v4i32(i8*{{.*}} %fmt, ...) +// O32-LABEL: define i32 @test_v4i32(i8*{{.*}} %fmt, ...) +// N32-LABEL: define signext i32 @test_v4i32(i8*{{.*}} %fmt, ...) +// N64-LABEL: define signext i32 @test_v4i32(i8*{{.*}} %fmt, ...) // // ALL: %va = alloca i8*, align [[$PTRALIGN]] // ALL: [[V:%.+]] = alloca <4 x i32>, align 16 diff --git a/test/CodeGen/mips-vector-arg.c b/test/CodeGen/mips-vector-arg.c index 1b9d7abe4d58..c9eafc958b1b 100644 --- a/test/CodeGen/mips-vector-arg.c +++ b/test/CodeGen/mips-vector-arg.c @@ -11,7 +11,7 @@ typedef int v4i32 __attribute__ ((__vector_size__ (16))); // O32: define void @test_v4sf(i32 inreg %a1.coerce0, i32 inreg %a1.coerce1, i32 inreg %a1.coerce2, i32 inreg %a1.coerce3, i32 signext %a2, i32, i32 inreg %a3.coerce0, i32 inreg %a3.coerce1, i32 inreg %a3.coerce2, i32 inreg %a3.coerce3) local_unnamed_addr [[NUW:#[0-9]+]] // O32: declare i32 @test_v4sf_2(i32 inreg, i32 inreg, i32 inreg, i32 inreg, i32 signext, i32, i32 inreg, i32 inreg, i32 inreg, i32 inreg) // N64: define void @test_v4sf(i64 inreg %a1.coerce0, i64 inreg %a1.coerce1, i32 signext %a2, i64, i64 inreg %a3.coerce0, i64 inreg %a3.coerce1) local_unnamed_addr [[NUW:#[0-9]+]] -// N64: declare i32 @test_v4sf_2(i64 inreg, i64 inreg, i32 signext, i64, i64 inreg, i64 inreg) +// N64: declare signext i32 @test_v4sf_2(i64 inreg, i64 inreg, i32 signext, i64, i64 inreg, i64 inreg) extern test_v4sf_2(v4sf, int, v4sf); void test_v4sf(v4sf a1, int a2, v4sf a3) { test_v4sf_2(a3, a2, a1); @@ -20,7 +20,7 @@ void test_v4sf(v4sf a1, int a2, v4sf a3) { // O32: define void @test_v4i32(i32 inreg %a1.coerce0, i32 inreg %a1.coerce1, i32 inreg %a1.coerce2, i32 inreg %a1.coerce3, i32 signext %a2, i32, i32 inreg %a3.coerce0, i32 inreg %a3.coerce1, i32 inreg %a3.coerce2, i32 inreg %a3.coerce3) local_unnamed_addr [[NUW]] // O32: declare i32 @test_v4i32_2(i32 inreg, i32 inreg, i32 inreg, i32 inreg, i32 signext, i32, i32 inreg, i32 inreg, i32 inreg, i32 inreg) // N64: define void @test_v4i32(i64 inreg %a1.coerce0, i64 inreg %a1.coerce1, i32 signext %a2, i64, i64 inreg %a3.coerce0, i64 inreg %a3.coerce1) local_unnamed_addr [[NUW]] -// N64: declare i32 @test_v4i32_2(i64 inreg, i64 inreg, i32 signext, i64, i64 inreg, i64 inreg) +// N64: declare signext i32 @test_v4i32_2(i64 inreg, i64 inreg, i32 signext, i64, i64 inreg, i64 inreg) extern test_v4i32_2(v4i32, int, v4i32); void test_v4i32(v4i32 a1, int a2, v4i32 a3) { test_v4i32_2(a3, a2, a1); diff --git a/test/CodeGenCUDA/device-var-init.cu b/test/CodeGenCUDA/device-var-init.cu index 9f788b764fbc..f96e42d9711c 100644 --- a/test/CodeGenCUDA/device-var-init.cu +++ b/test/CodeGenCUDA/device-var-init.cu @@ -112,6 +112,9 @@ __constant__ EC_I_EC c_ec_i_ec; // CHECK: @_ZZ2dfvE4s_ec = internal addrspace(3) global %struct.EC undef // CHECK: @_ZZ2dfvE5s_etc = internal addrspace(3) global %struct.ETC undef +// CHECK: @_ZZ2dfvE11const_array = internal addrspace(4) constant [5 x i32] [i32 1, i32 2, i32 3, i32 4, i32 5] +// CHECK: @_ZZ2dfvE9const_int = internal addrspace(4) constant i32 123 + // We should not emit global initializers for device-side variables. // CHECK-NOT: @__cxx_global_var_init @@ -234,6 +237,9 @@ __device__ void df() { static __shared__ ETC s_etc; // CHECK-NOT: call void @_ZN3ETCC1IJEEEDpT_(%struct.ETC* addrspacecast (%struct.ETC addrspace(3)* @_ZZ2dfvE5s_etc to %struct.ETC*)) + static const int const_array[] = {1, 2, 3, 4, 5}; + static const int const_int = 123; + // anchor point separating constructors and destructors df(); // CHECK: call void @_Z2dfv() diff --git a/test/CodeGenCXX/Inputs/override-layout-nameless-struct-union.layout b/test/CodeGenCXX/Inputs/override-layout-nameless-struct-union.layout new file mode 100644 index 000000000000..9eb4d244bd70 --- /dev/null +++ b/test/CodeGenCXX/Inputs/override-layout-nameless-struct-union.layout @@ -0,0 +1,16 @@ + +*** Dumping AST Record Layout +Type: struct S + +Layout: <ASTRecordLayout + Size:64 + Alignment:32 + FieldOffsets: [0, 32, 32]> + +*** Dumping AST Record Layout +Type: union U + +Layout: <ASTRecordLayout + Size:96 + Alignment:32 + FieldOffsets: [0, 0, 32, 64, 68, 73]> diff --git a/test/CodeGenCXX/Inputs/override-layout-packed-base.layout b/test/CodeGenCXX/Inputs/override-layout-packed-base.layout new file mode 100644 index 000000000000..949215ab849d --- /dev/null +++ b/test/CodeGenCXX/Inputs/override-layout-packed-base.layout @@ -0,0 +1,18 @@ + +*** Dumping AST Record Layout +Type: class B<0> + +Layout: <ASTRecordLayout + FieldOffsets: [0, 32]> + +*** Dumping AST Record Layout +Type: class B<1> + +Layout: <ASTRecordLayout + FieldOffsets: [0, 32]> + +*** Dumping AST Record Layout +Type: class C + +Layout: <ASTRecordLayout + FieldOffsets: [80]> diff --git a/test/CodeGenCXX/castexpr-basepathsize-threshold.cpp b/test/CodeGenCXX/castexpr-basepathsize-threshold.cpp new file mode 100644 index 000000000000..d5c1f603ff3f --- /dev/null +++ b/test/CodeGenCXX/castexpr-basepathsize-threshold.cpp @@ -0,0 +1,27 @@ +// RUN: %clang_cc1 %s -emit-llvm -o - + +// https://bugs.llvm.org/show_bug.cgi?id=38356 +// We only check that we do not crash. + +template <typename a, a b(unsigned), int c, unsigned...> +struct d : d<a, b, c - 1> {}; +template <typename a, a b(unsigned), unsigned... e> +struct d<a, b, 0, e...> { + a f[0]; +}; +struct g { + static g h(unsigned); +}; +struct i { + void j() const; + // Current maximum depth of recursive template instantiation is 1024, + // thus, this \/ threshold value is used here. BasePathSize in CastExpr might + // not fit it, so we are testing that we do fit it. + // If -ftemplate-depth= is provided, larger values (4096 and up) cause crashes + // elsewhere. + d<g, g::h, (1U << 10U) - 2U> f; +}; +void i::j() const { + const void *k{f.f}; + (void)k; +} diff --git a/test/CodeGenCXX/catch-implicit-integer-truncations.cpp b/test/CodeGenCXX/catch-implicit-integer-truncations.cpp new file mode 100644 index 000000000000..ba7676a3504a --- /dev/null +++ b/test/CodeGenCXX/catch-implicit-integer-truncations.cpp @@ -0,0 +1,256 @@ +// RUN: %clang_cc1 -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck %s --check-prefix=CHECK +// RUN: %clang_cc1 -fsanitize=implicit-integer-truncation -fno-sanitize-recover=implicit-integer-truncation -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck %s --check-prefixes=CHECK,CHECK-SANITIZE,CHECK-SANITIZE-ANYRECOVER,CHECK-SANITIZE-NORECOVER +// RUN: %clang_cc1 -fsanitize=implicit-integer-truncation -fsanitize-recover=implicit-integer-truncation -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck %s --check-prefixes=CHECK,CHECK-SANITIZE,CHECK-SANITIZE-ANYRECOVER,CHECK-SANITIZE-RECOVER +// RUN: %clang_cc1 -fsanitize=implicit-integer-truncation -fsanitize-trap=implicit-integer-truncation -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck %s --check-prefixes=CHECK,CHECK-SANITIZE,CHECK-SANITIZE-TRAP + +extern "C" { // Disable name mangling. + +// ========================================================================== // +// Check that explicit cast does not interfere with implicit conversion +// ========================================================================== // +// These contain one implicit truncating conversion, and one explicit truncating cast. +// We want to make sure that we still diagnose the implicit conversion. + +// Implicit truncation after explicit truncation. +// CHECK-LABEL: @explicit_cast_interference0 +unsigned char explicit_cast_interference0(unsigned int c) { + // CHECK-SANITIZE: %[[ANYEXT:.*]] = zext i8 %[[DST:.*]] to i16, !nosanitize + // CHECK-SANITIZE: call + // CHECK-SANITIZE-NOT: call + // CHECK: } + return (unsigned short)c; +} + +// Implicit truncation before explicit truncation. +// CHECK-LABEL: @explicit_cast_interference1 +unsigned char explicit_cast_interference1(unsigned int c) { + // CHECK-SANITIZE: %[[ANYEXT:.*]] = zext i16 %[[DST:.*]] to i32, !nosanitize + // CHECK-SANITIZE: call + // CHECK-SANITIZE-NOT: call + // CHECK: } + unsigned short b; + return (unsigned char)(b = c); +} + +// ========================================================================== // +// The expected true-negatives. +// ========================================================================== // + +// Explicit truncating casts. +// ========================================================================== // + +// CHECK-LABEL: @explicit_unsigned_int_to_unsigned_char +unsigned char explicit_unsigned_int_to_unsigned_char(unsigned int src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return (unsigned char)src; +} + +// CHECK-LABEL: @explicit_signed_int_to_unsigned_char +unsigned char explicit_signed_int_to_unsigned_char(signed int src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return (unsigned char)src; +} + +// CHECK-LABEL: @explicit_unsigned_int_to_signed_char +signed char explicit_unsigned_int_to_signed_char(unsigned int src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return (signed char)src; +} + +// CHECK-LABEL: @explicit_signed_int_to_signed_char +signed char explicit_signed_int_to_signed_char(signed int src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return (signed char)src; +} + +// Explicit NOP casts. +// ========================================================================== // + +// CHECK-LABEL: @explicit_unsigned_int_to_unsigned_int +unsigned int explicit_unsigned_int_to_unsigned_int(unsigned int src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return (unsigned int)src; +} + +// CHECK-LABEL: @explicit_signed_int_to_signed_int +signed int explicit_signed_int_to_signed_int(signed int src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return (signed int)src; +} + +// CHECK-LABEL: @explicit_unsigned_char_to_signed_char +unsigned char explicit_unsigned_char_to_signed_char(unsigned char src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return (unsigned char)src; +} + +// CHECK-LABEL: @explicit_signed_char_to_signed_char +signed char explicit_signed_char_to_signed_char(signed char src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return (signed char)src; +} + +// Explicit functional truncating casts. +// ========================================================================== // + +using UnsignedChar = unsigned char; +using SignedChar = signed char; +using UnsignedInt = unsigned int; +using SignedInt = signed int; + +// CHECK-LABEL: @explicit_functional_unsigned_int_to_unsigned_char +unsigned char explicit_functional_unsigned_int_to_unsigned_char(unsigned int src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return UnsignedChar(src); +} + +// CHECK-LABEL: @explicit_functional_signed_int_to_unsigned_char +unsigned char explicit_functional_signed_int_to_unsigned_char(signed int src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return UnsignedChar(src); +} + +// CHECK-LABEL: @explicit_functional_unsigned_int_to_signed_char +signed char explicit_functional_unsigned_int_to_signed_char(unsigned int src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return SignedChar(src); +} + +// CHECK-LABEL: @explicit_functional_signed_int_to_signed_char +signed char explicit_functional_signed_int_to_signed_char(signed int src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return SignedChar(src); +} + +// Explicit functional NOP casts. +// ========================================================================== // + +// CHECK-LABEL: @explicit_functional_unsigned_int_to_unsigned_int +unsigned int explicit_functional_unsigned_int_to_unsigned_int(unsigned int src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return UnsignedInt(src); +} + +// CHECK-LABEL: @explicit_functional_signed_int_to_signed_int +signed int explicit_functional_signed_int_to_signed_int(signed int src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return SignedInt(src); +} + +// CHECK-LABEL: @explicit_functional_unsigned_char_to_signed_char +unsigned char explicit_functional_unsigned_char_to_signed_char(unsigned char src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return UnsignedChar(src); +} + +// CHECK-LABEL: @explicit_functional_signed_char_to_signed_char +signed char explicit_functional_signed_char_to_signed_char(signed char src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return SignedChar(src); +} + +// Explicit C++-style casts truncating casts. +// ========================================================================== // + +// CHECK-LABEL: @explicit_cppstyleunsigned_int_to_unsigned_char +unsigned char explicit_cppstyleunsigned_int_to_unsigned_char(unsigned int src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return static_cast<unsigned char>(src); +} + +// CHECK-LABEL: @explicit_cppstylesigned_int_to_unsigned_char +unsigned char explicit_cppstylesigned_int_to_unsigned_char(signed int src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return static_cast<unsigned char>(src); +} + +// CHECK-LABEL: @explicit_cppstyleunsigned_int_to_signed_char +signed char explicit_cppstyleunsigned_int_to_signed_char(unsigned int src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return static_cast<signed char>(src); +} + +// CHECK-LABEL: @explicit_cppstylesigned_int_to_signed_char +signed char explicit_cppstylesigned_int_to_signed_char(signed int src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return static_cast<signed char>(src); +} + +// Explicit C++-style casts NOP casts. +// ========================================================================== // + +// CHECK-LABEL: @explicit_cppstyleunsigned_int_to_unsigned_int +unsigned int explicit_cppstyleunsigned_int_to_unsigned_int(unsigned int src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return static_cast<unsigned int>(src); +} + +// CHECK-LABEL: @explicit_cppstylesigned_int_to_signed_int +signed int explicit_cppstylesigned_int_to_signed_int(signed int src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return static_cast<signed int>(src); +} + +// CHECK-LABEL: @explicit_cppstyleunsigned_char_to_signed_char +unsigned char explicit_cppstyleunsigned_char_to_signed_char(unsigned char src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return static_cast<unsigned char>(src); +} + +// CHECK-LABEL: @explicit_cppstylesigned_char_to_signed_char +signed char explicit_cppstylesigned_char_to_signed_char(signed char src) { + // CHECK-SANITIZE-NOT: call + // CHECK: } + return static_cast<signed char>(src); +} + +} // extern "C" + +// ---------------------------------------------------------------------------// +// A problematic true-negative involving simple C++ code. +// The problem is tha the NoOp ExplicitCast is directly within MaterializeTemporaryExpr(), +// so a special care is neeeded. +// See https://reviews.llvm.org/D48958#1161345 +template <typename a> +a b(a c, const a &d) { + if (d) + ; + return c; +} + +extern "C" { // Disable name mangling. + +// CHECK-LABEL: @false_positive_with_MaterializeTemporaryExpr +int false_positive_with_MaterializeTemporaryExpr() { + // CHECK-SANITIZE-NOT: call{{.*}}ubsan + // CHECK: } + int e = b<unsigned>(4, static_cast<unsigned>(4294967296)); + return e; +} + +// ---------------------------------------------------------------------------// + +} // extern "C" diff --git a/test/CodeGenCXX/ctor-dtor-alias.cpp b/test/CodeGenCXX/ctor-dtor-alias.cpp index 4715111a1439..89244cc105b2 100644 --- a/test/CodeGenCXX/ctor-dtor-alias.cpp +++ b/test/CodeGenCXX/ctor-dtor-alias.cpp @@ -1,7 +1,5 @@ -// RUN: %clang_cc1 %s -triple i686-linux -emit-llvm -o - -mconstructor-aliases > %t -// RUN: FileCheck --check-prefix=NOOPT1 --input-file=%t %s -// RUN: FileCheck --check-prefix=NOOPT2 --input-file=%t %s -// RUN: FileCheck --check-prefix=NOOPT3 --input-file=%t %s +// RUN: %clang_cc1 %s -triple i686-linux -emit-llvm -o - -mconstructor-aliases | FileCheck --check-prefix=NOOPT %s + // RUN: %clang_cc1 %s -triple i686-linux -emit-llvm -o - -mconstructor-aliases -O1 -disable-llvm-passes > %t // RUN: FileCheck --check-prefix=CHECK1 --input-file=%t %s // RUN: FileCheck --check-prefix=CHECK2 --input-file=%t %s @@ -23,13 +21,6 @@ namespace test1 { // CHECK1: define weak_odr void @_ZN5test16foobarIvED0Ev({{.*}} comdat($_ZN5test16foobarIvED5Ev) // CHECK1-NOT: comdat -// This should happen regardless of the opt level. -// NOOPT1: @_ZN5test16foobarIvEC1Ev = weak_odr unnamed_addr alias void {{.*}} @_ZN5test16foobarIvEC2Ev -// NOOPT1: @_ZN5test16foobarIvED1Ev = weak_odr unnamed_addr alias void (%"struct.test1::foobar"*), void (%"struct.test1::foobar"*)* @_ZN5test16foobarIvED2Ev -// NOOPT1: define weak_odr void @_ZN5test16foobarIvEC2Ev({{.*}} comdat($_ZN5test16foobarIvEC5Ev) -// NOOPT1: define weak_odr void @_ZN5test16foobarIvED2Ev({{.*}} comdat($_ZN5test16foobarIvED5Ev) -// NOOPT1: define weak_odr void @_ZN5test16foobarIvED0Ev({{.*}} comdat($_ZN5test16foobarIvED5Ev) - // COFF doesn't support comdats with arbitrary names (C5/D5). // COFF: define weak_odr {{.*}} void @_ZN5test16foobarIvEC2Ev({{.*}} comdat align // COFF: define weak_odr {{.*}} void @_ZN5test16foobarIvEC1Ev({{.*}} comdat align @@ -46,17 +37,12 @@ template struct foobar<void>; } namespace test2 { -// test that when the destructor is linkonce_odr we just replace every use of +// test that when the destrucor is linkonce_odr we just replace every use of // C1 with C2. // CHECK1: define internal void @__cxx_global_var_init() // CHECK1: call void @_ZN5test26foobarIvEC2Ev // CHECK1: define linkonce_odr void @_ZN5test26foobarIvEC2Ev({{.*}} comdat align - -// At -O0, we should still emit the complete constructor. -// NOOPT1: define internal void @__cxx_global_var_init() -// NOOPT1: call void @_ZN5test26foobarIvEC1Ev -// NOOPT1: define linkonce_odr void @_ZN5test26foobarIvEC1Ev({{.*}} comdat align void g(); template <typename T> struct foobar { foobar() { g(); } @@ -71,11 +57,6 @@ namespace test3 { // CHECK1: define internal void @__cxx_global_var_init.1() // CHECK1: call i32 @__cxa_atexit{{.*}}_ZN5test312_GLOBAL__N_11AD2Ev // CHECK1: define internal void @_ZN5test312_GLOBAL__N_11AD2Ev( - -// We can use an alias for internal symbols at -O0. -// NOOPT2: _ZN5test312_GLOBAL__N_11BD1Ev = internal unnamed_addr alias void {{.*}} @_ZN5test312_GLOBAL__N_11BD2Ev -// NOOPT2: define internal void @__cxx_global_var_init.1() -// NOOPT2: call i32 @__cxa_atexit{{.*}}_ZN5test312_GLOBAL__N_11BD1Ev namespace { struct A { ~A() {} @@ -96,12 +77,11 @@ namespace test4 { // CHECK1: call i32 @__cxa_atexit{{.*}}_ZN5test41AD2Ev // CHECK1: define linkonce_odr void @_ZN5test41AD2Ev({{.*}} comdat align - // Test that we don't do this optimization at -O0 and call the complete - // destructor for B instead. This enables the debugger to see both - // destructors. - // NOOPT2: define internal void @__cxx_global_var_init.2() - // NOOPT2: call i32 @__cxa_atexit{{.*}}@_ZN5test41BD1Ev - // NOOPT2: define linkonce_odr void @_ZN5test41BD1Ev({{.*}} comdat align + // test that we don't do this optimization at -O0 so that the debugger can + // see both destructors. + // NOOPT: define internal void @__cxx_global_var_init.2() + // NOOPT: call i32 @__cxa_atexit{{.*}}@_ZN5test41BD2Ev + // NOOPT: define linkonce_odr void @_ZN5test41BD2Ev({{.*}} comdat align struct A { virtual ~A() {} }; @@ -149,11 +129,6 @@ namespace test7 { // out if we should). // pr17875. // CHECK3: define void @_ZN5test71BD2Ev - - // At -O0, we should emit both destructors, the complete can be an alias to - // the base one. - // NOOPT3: @_ZN5test71BD1Ev = unnamed_addr alias void {{.*}} @_ZN5test71BD2Ev - // NOOPT3: define void @_ZN5test71BD2Ev template <typename> struct A { ~A() {} }; diff --git a/test/CodeGenCXX/float16-declarations.cpp b/test/CodeGenCXX/float16-declarations.cpp index 1d6999fef073..e82c05ec8c81 100644 --- a/test/CodeGenCXX/float16-declarations.cpp +++ b/test/CodeGenCXX/float16-declarations.cpp @@ -103,7 +103,7 @@ int main(void) { C1 c1(f1l); // CHECK-DAG: [[F1L:%[a-z0-9]+]] = load half, half* %{{.*}}, align 2 -// CHECK-DAG: call void @_ZN2C1C1EDF16_(%class.C1* %{{.*}}, half %{{.*}}) +// CHECK-DAG: call void @_ZN2C1C2EDF16_(%class.C1* %{{.*}}, half %{{.*}}) S1<_Float16> s1 = { 132.f16 }; // CHECK-DAG: @_ZZ4mainE2s1 = private unnamed_addr constant %struct.S1 { half 0xH5820 }, align 2 diff --git a/test/CodeGenCXX/override-layout-nameless-struct-union.cpp b/test/CodeGenCXX/override-layout-nameless-struct-union.cpp new file mode 100644 index 000000000000..acc1ff715c69 --- /dev/null +++ b/test/CodeGenCXX/override-layout-nameless-struct-union.cpp @@ -0,0 +1,33 @@ +// RUN: %clang_cc1 -w -fdump-record-layouts-simple -foverride-record-layout=%S/Inputs/override-layout-nameless-struct-union.layout %s | FileCheck %s + +// CHECK: Type: struct S +// CHECK: Size:64 +// CHECK: Alignment:32 +// CHECK: FieldOffsets: [0, 32, 32] +struct S { + short _s; +//union { + int _su0; + char _su1; +//}; +}; + +// CHECK: Type: union U +// CHECK: Size:96 +// CHECK: Alignment:32 +// CHECK: FieldOffsets: [0, 0, 32, 64, 68, 73] +union U { + short _u; +//struct { + char _us0; + int _us1; + unsigned _us20 : 4; + unsigned _us21 : 5; + unsigned _us22 : 6; +//}; +}; + +void use_structs() { + S ss[sizeof(S)]; + U us[sizeof(U)]; +} diff --git a/test/CodeGenCXX/override-layout-packed-base.cpp b/test/CodeGenCXX/override-layout-packed-base.cpp new file mode 100644 index 000000000000..26ed4b5d815a --- /dev/null +++ b/test/CodeGenCXX/override-layout-packed-base.cpp @@ -0,0 +1,26 @@ +// RUN: %clang_cc1 -w -fdump-record-layouts-simple -foverride-record-layout=%S/Inputs/override-layout-packed-base.layout %s | FileCheck %s + +// CHECK: Type: class B<0> +// CHECK: FieldOffsets: [0, 32] + +// CHECK: Type: class B<1> +// CHECK: FieldOffsets: [0, 32] + +//#pragma pack(push, 1) +template<int I> +class B { + int _b1; + char _b2; +}; +//#pragma pack(pop) + +// CHECK: Type: class C +// CHECK: FieldOffsets: [80] + +class C : B<0>, B<1> { + char _c; +}; + +void use_structs() { + C cs[sizeof(C)]; +} diff --git a/test/CodeGenCXX/ubsan-new-checks.cpp b/test/CodeGenCXX/ubsan-new-checks.cpp new file mode 100644 index 000000000000..019fcf15a2ab --- /dev/null +++ b/test/CodeGenCXX/ubsan-new-checks.cpp @@ -0,0 +1,146 @@ +// RUN: %clang_cc1 -triple x86_64-linux-gnu -std=c++11 -S -emit-llvm -fsanitize=alignment %s -o - | FileCheck %s + +struct alignas(32) S1 { + int x; + S1(); +}; + +struct alignas(32) S2 { + int x; +}; + +struct alignas(32) S3 { + int x; + S3(int *p = new int[4]); +}; + +struct S4 : public S3 { + S4() : S3() {} +}; + +typedef __attribute__((ext_vector_type(2), aligned(32))) float float32x2_t; + +struct S5 { + float32x2_t x; +}; + +void *operator new (unsigned long, void *p) { return p; } +void *operator new[] (unsigned long, void *p) { return p; } + +S1 *func_01() { + // CHECK-LABEL: define {{.*}} @_Z7func_01v + // CHECK: and i64 %{{.*}}, 31, !nosanitize + // CHECK: icmp eq i64 %{{.*}}, 0, !nosanitize + // CHECK: call void @_ZN2S1C1Ev( + // CHECK-NOT: and i64 %{{.*}}, 31 + // CHECK: ret %struct.S1* + return new S1[20]; +} + +S2 *func_02() { + // CHECK-LABEL: define {{.*}} @_Z7func_02v + // CHECK: and i64 %{{.*}}, 31, !nosanitize + // CHECK: icmp eq i64 %{{.*}}, 0, !nosanitize + // CHECK: ret %struct.S2* + return new S2; +} + +S2 *func_03() { + // CHECK-LABEL: define {{.*}} @_Z7func_03v + // CHECK: and i64 %{{.*}}, 31, !nosanitize + // CHECK: icmp eq i64 %{{.*}}, 0, !nosanitize + // CHECK-NOT: and i64 %{{.*}}, 31 + // CHECK: ret %struct.S2* + return new S2[20]; +} + +float32x2_t *func_04() { + // CHECK-LABEL: define {{.*}} @_Z7func_04v + // CHECK: and i64 %{{.*}}, 31, !nosanitize + // CHECK: icmp eq i64 %{{.*}}, 0, !nosanitize + // CHECK: ret <2 x float>* + return new float32x2_t; +} + +float32x2_t *func_05() { + // CHECK-LABEL: define {{.*}} @_Z7func_05v + // CHECK: and i64 %{{.*}}, 31, !nosanitize + // CHECK: icmp eq i64 %{{.*}}, 0, !nosanitize + // CHECK-NOT: and i64 %{{.*}}, 31 + // CHECK: ret <2 x float>* + return new float32x2_t[20]; +} + +S3 *func_07() { + // CHECK-LABEL: define {{.*}} @_Z7func_07v + // CHECK: and i64 %{{.*}}, 31, !nosanitize + // CHECK: icmp eq i64 %{{.*}}, 0, !nosanitize + // CHECK: and i64 %{{.*}}, 3, !nosanitize + // CHECK: icmp eq i64 %{{.*}}, 0, !nosanitize + // CHECK: ret %struct.S3* + return new S3; +} + +S3 *func_08() { + // CHECK-LABEL: define {{.*}} @_Z7func_08v + // CHECK: and i64 %{{.*}}, 31, !nosanitize + // CHECK: icmp eq i64 %{{.*}}, 0, !nosanitize + // CHECK: and i64 %{{.*}}, 3, !nosanitize + // CHECK: icmp eq i64 %{{.*}}, 0, !nosanitize + // CHECK: ret %struct.S3* + return new S3[10]; +} + + +S2 *func_10(void *p) { + // CHECK-LABEL: define {{.*}} @_Z7func_10Pv + // CHECK: and i64 %{{.*}}, 31, !nosanitize + // CHECK: icmp eq i64 %{{.*}}, 0, !nosanitize + // CHECK: ret %struct.S2* + return new(p) S2; +} + +S2 *func_11(void *p) { + // CHECK-LABEL: define {{.*}} @_Z7func_11Pv + // CHECK: and i64 %{{.*}}, 31, !nosanitize + // CHECK: icmp eq i64 %{{.*}}, 0, !nosanitize + // CHECK-NOT: and i64 %{{.*}}, 31, !nosanitize + // CHECK-NOT: icmp eq i64 %{{.*}}, 0, !nosanitize + // CHECK: ret %struct.S2* + return new(p) S2[10]; +} + +float32x2_t *func_12() { + // CHECK-LABEL: define {{.*}} @_Z7func_12v + // CHECK: and i64 %{{.*}}, 31, !nosanitize + // CHECK: icmp eq i64 %{{.*}}, 0, !nosanitize + // CHECK: ret <2 x float>* + return new float32x2_t; +} + +float32x2_t *func_13() { + // CHECK-LABEL: define {{.*}} @_Z7func_13v + // CHECK: and i64 %{{.*}}, 31, !nosanitize + // CHECK: icmp eq i64 %{{.*}}, 0, !nosanitize + // CHECK-NOT: and i64 %{{.*}}, 31 + // CHECK: ret <2 x float>* + return new float32x2_t[20]; +} + +S4 *func_14() { + // CHECK-LABEL: define {{.*}} @_Z7func_14v + // CHECK: and i64 %{{.*}}, 31, !nosanitize + // CHECK: icmp eq i64 %{{.*}}, 0, !nosanitize + // CHECK-NOT: and i64 %{{.*}}, 31 + // CHECK: ret %struct.S4* + return new S4; +} + +S5 *func_15(const S5 *ptr) { + // CHECK-LABEL: define {{.*}} @_Z7func_15PK2S5 + // CHECK: and i64 %{{.*}}, 31, !nosanitize + // CHECK: icmp eq i64 %{{.*}}, 0, !nosanitize + // CHECK-NOT: and i64 + // CHECK: ret %struct.S5* + return new S5(*ptr); +} diff --git a/test/CodeGenOpenCL/blocks.cl b/test/CodeGenOpenCL/blocks.cl index 0e125fd703f5..80ac5727b094 100644 --- a/test/CodeGenOpenCL/blocks.cl +++ b/test/CodeGenOpenCL/blocks.cl @@ -1,5 +1,5 @@ -// RUN: %clang_cc1 %s -cl-std=CL2.0 -emit-llvm -o - -O0 -triple spir-unknown-unknown | FileCheck -check-prefixes=COMMON,SPIR %s -// RUN: %clang_cc1 %s -cl-std=CL2.0 -emit-llvm -o - -O0 -triple amdgcn-amd-amdhsa | FileCheck -check-prefixes=COMMON,AMDGCN %s +// RUN: %clang_cc1 %s -cl-std=CL2.0 -emit-llvm -o - -O0 -debug-info-kind=limited -triple spir-unknown-unknown | FileCheck -check-prefixes=COMMON,SPIR %s +// RUN: %clang_cc1 %s -cl-std=CL2.0 -emit-llvm -o - -O0 -debug-info-kind=limited -triple amdgcn-amd-amdhsa | FileCheck -check-prefixes=COMMON,AMDGCN %s // COMMON: @__block_literal_global = internal addrspace(1) constant { i32, i32 } { i32 8, i32 4 } // COMMON-NOT: .str @@ -60,3 +60,11 @@ void foo(){ // AMDGCN: %[[block_capture:.*]] = load i32, i32* %[[block_capture_addr]] // COMMON-NOT: define{{.*}}@__foo_block_invoke_kernel + +// COMMON: !DIDerivedType(tag: DW_TAG_member, name: "__size" +// COMMON: !DIDerivedType(tag: DW_TAG_member, name: "__align" + +// COMMON-NOT: !DIDerivedType(tag: DW_TAG_member, name: "__isa" +// COMMON-NOT: !DIDerivedType(tag: DW_TAG_member, name: "__flags" +// COMMON-NOT: !DIDerivedType(tag: DW_TAG_member, name: "__reserved" +// COMMON-NOT: !DIDerivedType(tag: DW_TAG_member, name: "__FuncPtr" diff --git a/test/CodeGenOpenCL/builtins-amdgcn-dl-insts-err-clamp.cl b/test/CodeGenOpenCL/builtins-amdgcn-dl-insts-err-clamp.cl new file mode 100644 index 000000000000..f8356feb5112 --- /dev/null +++ b/test/CodeGenOpenCL/builtins-amdgcn-dl-insts-err-clamp.cl @@ -0,0 +1,25 @@ +// REQUIRES: amdgpu-registered-target + +// RUN: %clang_cc1 -triple amdgcn-unknown-unknown -target-cpu gfx906 -verify -S -emit-llvm -o - %s + +typedef unsigned int uint; +typedef half __attribute__((ext_vector_type(2))) half2; +typedef short __attribute__((ext_vector_type(2))) short2; +typedef unsigned short __attribute__((ext_vector_type(2))) ushort2; + +kernel void builtins_amdgcn_dl_insts_err( + global float *fOut, global int *siOut, global uint *uiOut, + half2 v2hA, half2 v2hB, float fC, + short2 v2ssA, short2 v2ssB, int siA, int siB, int siC, + ushort2 v2usA, ushort2 v2usB, uint uiA, uint uiB, uint uiC, uint isClamp) { + fOut[0] = __builtin_amdgcn_fdot2(v2hA, v2hB, fC, isClamp == 0 ? false : true); // expected-error {{'__builtin_amdgcn_fdot2' must be a constant integer}} + + siOut[0] = __builtin_amdgcn_sdot2(v2ssA, v2ssB, siC, isClamp == 0 ? false : true); // expected-error {{'__builtin_amdgcn_sdot2' must be a constant integer}} + uiOut[0] = __builtin_amdgcn_udot2(v2usA, v2usB, uiC, isClamp == 0 ? false : true); // expected-error {{'__builtin_amdgcn_udot2' must be a constant integer}} + + siOut[1] = __builtin_amdgcn_sdot4(siA, siB, siC, isClamp == 0 ? false : true); // expected-error {{'__builtin_amdgcn_sdot4' must be a constant integer}} + uiOut[1] = __builtin_amdgcn_udot4(uiA, uiB, uiC, isClamp == 0 ? false : true); // expected-error {{'__builtin_amdgcn_udot4' must be a constant integer}} + + siOut[2] = __builtin_amdgcn_sdot8(siA, siB, siC, isClamp == 0 ? false : true); // expected-error {{'__builtin_amdgcn_sdot8' must be a constant integer}} + uiOut[2] = __builtin_amdgcn_udot8(uiA, uiB, uiC, isClamp == 0 ? false : true); // expected-error {{'__builtin_amdgcn_udot8' must be a constant integer}} +} diff --git a/test/CodeGenOpenCL/builtins-amdgcn-dl-insts-err.cl b/test/CodeGenOpenCL/builtins-amdgcn-dl-insts-err.cl index bfc811e29556..ca3f4006e300 100644 --- a/test/CodeGenOpenCL/builtins-amdgcn-dl-insts-err.cl +++ b/test/CodeGenOpenCL/builtins-amdgcn-dl-insts-err.cl @@ -12,14 +12,24 @@ kernel void builtins_amdgcn_dl_insts_err( half2 v2hA, half2 v2hB, float fC, short2 v2ssA, short2 v2ssB, int siA, int siB, int siC, ushort2 v2usA, ushort2 v2usB, uint uiA, uint uiB, uint uiC) { - fOut[0] = __builtin_amdgcn_fdot2(v2hA, v2hB, fC); // expected-error {{'__builtin_amdgcn_fdot2' needs target feature dl-insts}} + fOut[0] = __builtin_amdgcn_fdot2(v2hA, v2hB, fC, false); // expected-error {{'__builtin_amdgcn_fdot2' needs target feature dl-insts}} + fOut[1] = __builtin_amdgcn_fdot2(v2hA, v2hB, fC, true); // expected-error {{'__builtin_amdgcn_fdot2' needs target feature dl-insts}} - siOut[0] = __builtin_amdgcn_sdot2(v2ssA, v2ssB, siC); // expected-error {{'__builtin_amdgcn_sdot2' needs target feature dl-insts}} - uiOut[0] = __builtin_amdgcn_udot2(v2usA, v2usB, uiC); // expected-error {{'__builtin_amdgcn_udot2' needs target feature dl-insts}} + siOut[0] = __builtin_amdgcn_sdot2(v2ssA, v2ssB, siC, false); // expected-error {{'__builtin_amdgcn_sdot2' needs target feature dl-insts}} + siOut[1] = __builtin_amdgcn_sdot2(v2ssA, v2ssB, siC, true); // expected-error {{'__builtin_amdgcn_sdot2' needs target feature dl-insts}} - siOut[1] = __builtin_amdgcn_sdot4(siA, siB, siC); // expected-error {{'__builtin_amdgcn_sdot4' needs target feature dl-insts}} - uiOut[1] = __builtin_amdgcn_udot4(uiA, uiB, uiC); // expected-error {{'__builtin_amdgcn_udot4' needs target feature dl-insts}} + uiOut[0] = __builtin_amdgcn_udot2(v2usA, v2usB, uiC, false); // expected-error {{'__builtin_amdgcn_udot2' needs target feature dl-insts}} + uiOut[1] = __builtin_amdgcn_udot2(v2usA, v2usB, uiC, true); // expected-error {{'__builtin_amdgcn_udot2' needs target feature dl-insts}} - siOut[2] = __builtin_amdgcn_sdot8(siA, siB, siC); // expected-error {{'__builtin_amdgcn_sdot8' needs target feature dl-insts}} - uiOut[2] = __builtin_amdgcn_udot8(uiA, uiB, uiC); // expected-error {{'__builtin_amdgcn_udot8' needs target feature dl-insts}} + siOut[2] = __builtin_amdgcn_sdot4(siA, siB, siC, false); // expected-error {{'__builtin_amdgcn_sdot4' needs target feature dl-insts}} + siOut[3] = __builtin_amdgcn_sdot4(siA, siB, siC, true); // expected-error {{'__builtin_amdgcn_sdot4' needs target feature dl-insts}} + + uiOut[2] = __builtin_amdgcn_udot4(uiA, uiB, uiC, false); // expected-error {{'__builtin_amdgcn_udot4' needs target feature dl-insts}} + uiOut[3] = __builtin_amdgcn_udot4(uiA, uiB, uiC, true); // expected-error {{'__builtin_amdgcn_udot4' needs target feature dl-insts}} + + siOut[4] = __builtin_amdgcn_sdot8(siA, siB, siC, false); // expected-error {{'__builtin_amdgcn_sdot8' needs target feature dl-insts}} + siOut[5] = __builtin_amdgcn_sdot8(siA, siB, siC, true); // expected-error {{'__builtin_amdgcn_sdot8' needs target feature dl-insts}} + + uiOut[4] = __builtin_amdgcn_udot8(uiA, uiB, uiC, false); // expected-error {{'__builtin_amdgcn_udot8' needs target feature dl-insts}} + uiOut[5] = __builtin_amdgcn_udot8(uiA, uiB, uiC, true); // expected-error {{'__builtin_amdgcn_udot8' needs target feature dl-insts}} } diff --git a/test/CodeGenOpenCL/builtins-amdgcn-dl-insts.cl b/test/CodeGenOpenCL/builtins-amdgcn-dl-insts.cl index c407bd6fe155..e5633fb8f400 100644 --- a/test/CodeGenOpenCL/builtins-amdgcn-dl-insts.cl +++ b/test/CodeGenOpenCL/builtins-amdgcn-dl-insts.cl @@ -8,29 +8,49 @@ typedef short __attribute__((ext_vector_type(2))) short2; typedef unsigned short __attribute__((ext_vector_type(2))) ushort2; // CHECK-LABEL: @builtins_amdgcn_dl_insts -// CHECK: call float @llvm.amdgcn.fdot2 +// CHECK: call float @llvm.amdgcn.fdot2(<2 x half> %v2hA, <2 x half> %v2hB, float %fC, i1 false) +// CHECK: call float @llvm.amdgcn.fdot2(<2 x half> %v2hA, <2 x half> %v2hB, float %fC, i1 true) -// CHECK: call i32 @llvm.amdgcn.sdot2 -// CHECK: call i32 @llvm.amdgcn.udot2 +// CHECK: call i32 @llvm.amdgcn.sdot2(<2 x i16> %v2ssA, <2 x i16> %v2ssB, i32 %siC, i1 false) +// CHECK: call i32 @llvm.amdgcn.sdot2(<2 x i16> %v2ssA, <2 x i16> %v2ssB, i32 %siC, i1 true) -// CHECK: call i32 @llvm.amdgcn.sdot4 -// CHECK: call i32 @llvm.amdgcn.udot4 +// CHECK: call i32 @llvm.amdgcn.udot2(<2 x i16> %v2usA, <2 x i16> %v2usB, i32 %uiC, i1 false) +// CHECK: call i32 @llvm.amdgcn.udot2(<2 x i16> %v2usA, <2 x i16> %v2usB, i32 %uiC, i1 true) -// CHECK: call i32 @llvm.amdgcn.sdot8 -// CHECK: call i32 @llvm.amdgcn.udot8 +// CHECK: call i32 @llvm.amdgcn.sdot4(i32 %siA, i32 %siB, i32 %siC, i1 false) +// CHECK: call i32 @llvm.amdgcn.sdot4(i32 %siA, i32 %siB, i32 %siC, i1 true) + +// CHECK: call i32 @llvm.amdgcn.udot4(i32 %uiA, i32 %uiB, i32 %uiC, i1 false) +// CHECK: call i32 @llvm.amdgcn.udot4(i32 %uiA, i32 %uiB, i32 %uiC, i1 true) + +// CHECK: call i32 @llvm.amdgcn.sdot8(i32 %siA, i32 %siB, i32 %siC, i1 false) +// CHECK: call i32 @llvm.amdgcn.sdot8(i32 %siA, i32 %siB, i32 %siC, i1 true) + +// CHECK: call i32 @llvm.amdgcn.udot8(i32 %uiA, i32 %uiB, i32 %uiC, i1 false) +// CHECK: call i32 @llvm.amdgcn.udot8(i32 %uiA, i32 %uiB, i32 %uiC, i1 true) kernel void builtins_amdgcn_dl_insts( global float *fOut, global int *siOut, global uint *uiOut, half2 v2hA, half2 v2hB, float fC, short2 v2ssA, short2 v2ssB, int siA, int siB, int siC, ushort2 v2usA, ushort2 v2usB, uint uiA, uint uiB, uint uiC) { - fOut[0] = __builtin_amdgcn_fdot2(v2hA, v2hB, fC); + fOut[0] = __builtin_amdgcn_fdot2(v2hA, v2hB, fC, false); + fOut[1] = __builtin_amdgcn_fdot2(v2hA, v2hB, fC, true); + + siOut[0] = __builtin_amdgcn_sdot2(v2ssA, v2ssB, siC, false); + siOut[1] = __builtin_amdgcn_sdot2(v2ssA, v2ssB, siC, true); + + uiOut[0] = __builtin_amdgcn_udot2(v2usA, v2usB, uiC, false); + uiOut[1] = __builtin_amdgcn_udot2(v2usA, v2usB, uiC, true); + + siOut[2] = __builtin_amdgcn_sdot4(siA, siB, siC, false); + siOut[3] = __builtin_amdgcn_sdot4(siA, siB, siC, true); - siOut[0] = __builtin_amdgcn_sdot2(v2ssA, v2ssB, siC); - uiOut[0] = __builtin_amdgcn_udot2(v2usA, v2usB, uiC); + uiOut[2] = __builtin_amdgcn_udot4(uiA, uiB, uiC, false); + uiOut[3] = __builtin_amdgcn_udot4(uiA, uiB, uiC, true); - siOut[1] = __builtin_amdgcn_sdot4(siA, siB, siC); - uiOut[1] = __builtin_amdgcn_udot4(uiA, uiB, uiC); + siOut[4] = __builtin_amdgcn_sdot8(siA, siB, siC, false); + siOut[5] = __builtin_amdgcn_sdot8(siA, siB, siC, true); - siOut[2] = __builtin_amdgcn_sdot8(siA, siB, siC); - uiOut[2] = __builtin_amdgcn_udot8(uiA, uiB, uiC); + uiOut[4] = __builtin_amdgcn_udot8(uiA, uiB, uiC, false); + uiOut[5] = __builtin_amdgcn_udot8(uiA, uiB, uiC, true); } diff --git a/test/Driver/Inputs/basic_riscv32_tree/bin/riscv32-unknown-elf-ld b/test/Driver/Inputs/basic_riscv32_tree/bin/riscv32-unknown-elf-ld new file mode 100755 index 000000000000..b23e55619b2f --- /dev/null +++ b/test/Driver/Inputs/basic_riscv32_tree/bin/riscv32-unknown-elf-ld @@ -0,0 +1 @@ +#!/bin/true diff --git a/test/Driver/Inputs/resource_dir/lib/darwin/libclang_rt.asan_ios_dynamic.dylib b/test/Driver/Inputs/basic_riscv32_tree/lib/gcc/riscv32-unknown-elf/8.0.1/crtbegin.o index e69de29bb2d1..e69de29bb2d1 100644 --- a/test/Driver/Inputs/resource_dir/lib/darwin/libclang_rt.asan_ios_dynamic.dylib +++ b/test/Driver/Inputs/basic_riscv32_tree/lib/gcc/riscv32-unknown-elf/8.0.1/crtbegin.o diff --git a/test/Driver/Inputs/resource_dir/lib/darwin/libclang_rt.asan_iossim_dynamic.dylib b/test/Driver/Inputs/basic_riscv32_tree/lib/gcc/riscv32-unknown-elf/8.0.1/crtend.o index e69de29bb2d1..e69de29bb2d1 100644 --- a/test/Driver/Inputs/resource_dir/lib/darwin/libclang_rt.asan_iossim_dynamic.dylib +++ b/test/Driver/Inputs/basic_riscv32_tree/lib/gcc/riscv32-unknown-elf/8.0.1/crtend.o diff --git a/test/Driver/Inputs/resource_dir/lib/darwin/libclang_rt.asan_osx_dynamic.dylib b/test/Driver/Inputs/basic_riscv32_tree/riscv32-unknown-elf/include/c++/8.0.1/.keep index e69de29bb2d1..e69de29bb2d1 100644 --- a/test/Driver/Inputs/resource_dir/lib/darwin/libclang_rt.asan_osx_dynamic.dylib +++ b/test/Driver/Inputs/basic_riscv32_tree/riscv32-unknown-elf/include/c++/8.0.1/.keep diff --git a/test/Driver/Inputs/resource_dir/lib/darwin/libclang_rt.asan_tvos_dynamic.dylib b/test/Driver/Inputs/basic_riscv32_tree/riscv32-unknown-elf/lib/crt0.o index e69de29bb2d1..e69de29bb2d1 100644 --- a/test/Driver/Inputs/resource_dir/lib/darwin/libclang_rt.asan_tvos_dynamic.dylib +++ b/test/Driver/Inputs/basic_riscv32_tree/riscv32-unknown-elf/lib/crt0.o diff --git a/test/Driver/Inputs/resource_dir/lib/darwin/libclang_rt.asan_tvossim_dynamic.dylib b/test/Driver/Inputs/openembedded_aarch64_linux_tree/usr/include/c++/6.3.0/backward/.keep index e69de29bb2d1..e69de29bb2d1 100644 --- a/test/Driver/Inputs/resource_dir/lib/darwin/libclang_rt.asan_tvossim_dynamic.dylib +++ b/test/Driver/Inputs/openembedded_aarch64_linux_tree/usr/include/c++/6.3.0/backward/.keep diff --git a/test/Driver/Inputs/resource_dir/lib/darwin/libclang_rt.asan_watchos_dynamic.dylib b/test/Driver/Inputs/openembedded_aarch64_linux_tree/usr/lib64/aarch64-oe-linux/6.3.0/crtbegin.o index e69de29bb2d1..e69de29bb2d1 100644 --- a/test/Driver/Inputs/resource_dir/lib/darwin/libclang_rt.asan_watchos_dynamic.dylib +++ b/test/Driver/Inputs/openembedded_aarch64_linux_tree/usr/lib64/aarch64-oe-linux/6.3.0/crtbegin.o diff --git a/test/Driver/Inputs/resource_dir/lib/darwin/libclang_rt.asan_watchossim_dynamic.dylib b/test/Driver/Inputs/openembedded_aarch64_linux_tree/usr/lib64/aarch64-oe-linux/6.3.0/crtend.o index e69de29bb2d1..e69de29bb2d1 100644 --- a/test/Driver/Inputs/resource_dir/lib/darwin/libclang_rt.asan_watchossim_dynamic.dylib +++ b/test/Driver/Inputs/openembedded_aarch64_linux_tree/usr/lib64/aarch64-oe-linux/6.3.0/crtend.o diff --git a/test/Driver/Inputs/resource_dir/lib/darwin/libclang_rt.fuzzer_osx.a b/test/Driver/Inputs/openembedded_aarch64_linux_tree/usr/lib64/crt1.o index e69de29bb2d1..e69de29bb2d1 100644 --- a/test/Driver/Inputs/resource_dir/lib/darwin/libclang_rt.fuzzer_osx.a +++ b/test/Driver/Inputs/openembedded_aarch64_linux_tree/usr/lib64/crt1.o diff --git a/test/Driver/Inputs/resource_dir/lib/darwin/libclang_rt.lsan_ios_dynamic.dylib b/test/Driver/Inputs/openembedded_aarch64_linux_tree/usr/lib64/crti.o index e69de29bb2d1..e69de29bb2d1 100644 --- a/test/Driver/Inputs/resource_dir/lib/darwin/libclang_rt.lsan_ios_dynamic.dylib +++ b/test/Driver/Inputs/openembedded_aarch64_linux_tree/usr/lib64/crti.o diff --git a/test/Driver/Inputs/resource_dir/lib/darwin/libclang_rt.lsan_iossim_dynamic.dylib b/test/Driver/Inputs/openembedded_aarch64_linux_tree/usr/lib64/crtn.o index e69de29bb2d1..e69de29bb2d1 100644 --- a/test/Driver/Inputs/resource_dir/lib/darwin/libclang_rt.lsan_iossim_dynamic.dylib +++ b/test/Driver/Inputs/openembedded_aarch64_linux_tree/usr/lib64/crtn.o diff --git a/test/Driver/Inputs/resource_dir/lib/darwin/libclang_rt.lsan_osx_dynamic.dylib b/test/Driver/Inputs/openembedded_arm_linux_tree/usr/include/c++/6.3.0/backward/.keep index e69de29bb2d1..e69de29bb2d1 100644 --- a/test/Driver/Inputs/resource_dir/lib/darwin/libclang_rt.lsan_osx_dynamic.dylib +++ b/test/Driver/Inputs/openembedded_arm_linux_tree/usr/include/c++/6.3.0/backward/.keep diff --git a/test/Driver/Inputs/resource_dir/lib/darwin/libclang_rt.lsan_tvossim_dynamic.dylib b/test/Driver/Inputs/openembedded_arm_linux_tree/usr/lib/arm-oe-linux-gnueabi/6.3.0/crtbegin.o index e69de29bb2d1..e69de29bb2d1 100644 --- a/test/Driver/Inputs/resource_dir/lib/darwin/libclang_rt.lsan_tvossim_dynamic.dylib +++ b/test/Driver/Inputs/openembedded_arm_linux_tree/usr/lib/arm-oe-linux-gnueabi/6.3.0/crtbegin.o diff --git a/test/Driver/Inputs/resource_dir/lib/darwin/libclang_rt.tsan_iossim_dynamic.dylib b/test/Driver/Inputs/openembedded_arm_linux_tree/usr/lib/arm-oe-linux-gnueabi/6.3.0/crtend.o index e69de29bb2d1..e69de29bb2d1 100644 --- a/test/Driver/Inputs/resource_dir/lib/darwin/libclang_rt.tsan_iossim_dynamic.dylib +++ b/test/Driver/Inputs/openembedded_arm_linux_tree/usr/lib/arm-oe-linux-gnueabi/6.3.0/crtend.o diff --git a/test/Driver/Inputs/resource_dir/lib/darwin/libclang_rt.tsan_osx_dynamic.dylib b/test/Driver/Inputs/openembedded_arm_linux_tree/usr/lib/crt1.o index e69de29bb2d1..e69de29bb2d1 100644 --- a/test/Driver/Inputs/resource_dir/lib/darwin/libclang_rt.tsan_osx_dynamic.dylib +++ b/test/Driver/Inputs/openembedded_arm_linux_tree/usr/lib/crt1.o diff --git a/test/Driver/Inputs/resource_dir/lib/darwin/libclang_rt.tsan_tvossim_dynamic.dylib b/test/Driver/Inputs/openembedded_arm_linux_tree/usr/lib/crti.o index e69de29bb2d1..e69de29bb2d1 100644 --- a/test/Driver/Inputs/resource_dir/lib/darwin/libclang_rt.tsan_tvossim_dynamic.dylib +++ b/test/Driver/Inputs/openembedded_arm_linux_tree/usr/lib/crti.o diff --git a/test/Driver/Inputs/openembedded_arm_linux_tree/usr/lib/crtn.o b/test/Driver/Inputs/openembedded_arm_linux_tree/usr/lib/crtn.o new file mode 100644 index 000000000000..e69de29bb2d1 --- /dev/null +++ b/test/Driver/Inputs/openembedded_arm_linux_tree/usr/lib/crtn.o diff --git a/test/Driver/aarch64-cpus.c b/test/Driver/aarch64-cpus.c index 330af351182d..d3cb35fa1030 100644 --- a/test/Driver/aarch64-cpus.c +++ b/test/Driver/aarch64-cpus.c @@ -388,6 +388,14 @@ // RUN: %clang -target aarch64_be -mlittle-endian -march=armv8.2-a -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV82A %s // GENERICV82A: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-cpu" "generic" "-target-feature" "+neon" "-target-feature" "+v8.2a" +// RUN: %clang -target aarch64_be -march=armv8.2a -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV82A-BE %s +// RUN: %clang -target aarch64_be -march=armv8.2-a -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV82A-BE %s +// RUN: %clang -target aarch64 -mbig-endian -march=armv8.2a -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV82A-BE %s +// RUN: %clang -target aarch64 -mbig-endian -march=armv8.2-a -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV82A-BE %s +// RUN: %clang -target aarch64_be -mbig-endian -march=armv8.2a -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV82A-BE %s +// RUN: %clang -target aarch64_be -mbig-endian -march=armv8.2-a -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV82A-BE %s +// GENERICV82A-BE: "-cc1"{{.*}} "-triple" "aarch64_be{{.*}}" "-target-cpu" "generic" "-target-feature" "+neon" "-target-feature" "+v8.2a" + // RUN: %clang -target aarch64 -march=armv8.2-a+fp16 -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV82A-FP16 %s // GENERICV82A-FP16: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-cpu" "generic" "-target-feature" "+neon" "-target-feature" "+v8.2a" "-target-feature" "+fullfp16" @@ -397,6 +405,71 @@ // RUN: %clang -target aarch64 -march=armv8.2-a+fp16+profile -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV82A-FP16-SPE %s // GENERICV82A-FP16-SPE: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-cpu" "generic" "-target-feature" "+neon" "-target-feature" "+v8.2a" "-target-feature" "+fullfp16" "-target-feature" "+spe" +// RUN: %clang -target aarch64 -march=armv8.3a -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV83A %s +// RUN: %clang -target aarch64 -march=armv8.3-a -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV83A %s +// RUN: %clang -target aarch64 -mlittle-endian -march=armv8.3a -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV83A %s +// RUN: %clang -target aarch64 -mlittle-endian -march=armv8.3-a -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV83A %s +// RUN: %clang -target aarch64_be -mlittle-endian -march=armv8.3a -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV83A %s +// RUN: %clang -target aarch64_be -mlittle-endian -march=armv8.3-a -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV83A %s +// GENERICV83A: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-cpu" "generic" "-target-feature" "+neon" "-target-feature" "+v8.3a" + +// RUN: %clang -target aarch64_be -march=armv8.3a -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV83A-BE %s +// RUN: %clang -target aarch64_be -march=armv8.3-a -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV83A-BE %s +// RUN: %clang -target aarch64 -mbig-endian -march=armv8.3a -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV83A-BE %s +// RUN: %clang -target aarch64 -mbig-endian -march=armv8.3-a -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV83A-BE %s +// RUN: %clang -target aarch64_be -mbig-endian -march=armv8.3a -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV83A-BE %s +// RUN: %clang -target aarch64_be -mbig-endian -march=armv8.3-a -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV83A-BE %s +// GENERICV83A-BE: "-cc1"{{.*}} "-triple" "aarch64_be{{.*}}" "-target-cpu" "generic" "-target-feature" "+neon" "-target-feature" "+v8.3a" + +// RUN: %clang -target aarch64 -march=armv8.3-a+fp16 -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV83A-FP16 %s +// GENERICV83A-FP16: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-cpu" "generic" "-target-feature" "+neon" "-target-feature" "+v8.3a" "-target-feature" "+fullfp16" + +// RUN: %clang -target aarch64 -march=armv8.4a -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV84A %s +// RUN: %clang -target aarch64 -march=armv8.4-a -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV84A %s +// RUN: %clang -target aarch64 -mlittle-endian -march=armv8.4a -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV84A %s +// RUN: %clang -target aarch64 -mlittle-endian -march=armv8.4-a -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV84A %s +// RUN: %clang -target aarch64_be -mlittle-endian -march=armv8.4a -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV84A %s +// RUN: %clang -target aarch64_be -mlittle-endian -march=armv8.4-a -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV84A %s +// GENERICV84A: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-cpu" "generic" "-target-feature" "+neon" "-target-feature" "+v8.4a" + +// RUN: %clang -target aarch64_be -march=armv8.4a -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV84A-BE %s +// RUN: %clang -target aarch64_be -march=armv8.4-a -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV84A-BE %s +// RUN: %clang -target aarch64 -mbig-endian -march=armv8.4a -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV84A-BE %s +// RUN: %clang -target aarch64 -mbig-endian -march=armv8.4-a -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV84A-BE %s +// RUN: %clang -target aarch64_be -mbig-endian -march=armv8.4a -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV84A-BE %s +// RUN: %clang -target aarch64_be -mbig-endian -march=armv8.4-a -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV84A-BE %s +// GENERICV84A-BE: "-cc1"{{.*}} "-triple" "aarch64_be{{.*}}" "-target-cpu" "generic" "-target-feature" "+neon" "-target-feature" "+v8.4a" + +// RUN: %clang -target aarch64 -march=armv8.4-a+fp16 -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV84A-FP16 %s +// GENERICV84A-FP16: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-cpu" "generic" "-target-feature" "+neon" "-target-feature" "+v8.4a" "-target-feature" "+fullfp16" + +// fullfp16 is not specified by default for v8.2a, and can be enabled by +fp16 +// RUN: %clang -target aarch64 -march=armv8.2a -### -c %s 2>&1 | FileCheck -check-prefix=V82ANOFP16 -check-prefix=GENERICV82A %s +// RUN: %clang -target aarch64 -march=armv8.2-a -### -c %s 2>&1 | FileCheck -check-prefix=V82ANOFP16 -check-prefix=GENERICV82A %s +// V82ANOFP16-NOT: "-target-feature" "-fullfp16" +// V82ANOFP16-NOT: "-target-feature" "+fullfp16" +// RUN: %clang -target aarch64 -march=armv8.2a+fp16 -### -c %s 2>&1 | FileCheck -check-prefix=V82AFP16 -check-prefix=GENERICV82A %s +// RUN: %clang -target aarch64 -march=armv8.2-a+fp16 -### -c %s 2>&1 | FileCheck -check-prefix=V82AFP16 -check-prefix=GENERICV82A %s +// V82AFP16: "-target-feature" "+fullfp16" + +// fullfp16 is off by default for v8a, feature must not be mentioned +// RUN: %clang -target aarch64 -march=armv8a -### -c %s 2>&1 | FileCheck -check-prefix=V82ANOFP16 -check-prefix=GENERIC %s +// RUN: %clang -target aarch64 -march=armv8-a -### -c %s 2>&1 | FileCheck -check-prefix=V82ANOFP16 -check-prefix=GENERIC %s + +// RAS is on by default for v8.2a, but can be disabled by +noras +// RUN: %clang -target aarch64 -march=armv8.2a -### -c %s 2>&1 | FileCheck -check-prefix=V82ARAS -check-prefix=GENERICV82A %s +// RUN: %clang -target aarch64 -march=armv8.2-a -### -c %s 2>&1 | FileCheck -check-prefix=V82ARAS -check-prefix=GENERICV82A %s +// V82ARAS-NOT: "-target-feature" "+ras" +// V82ARAS-NOT: "-target-feature" "-ras" +// RUN: %clang -target aarch64 -march=armv8.2a+noras -### -c %s 2>&1 | FileCheck -check-prefix=V82ANORAS -check-prefix=GENERICV82A %s +// RUN: %clang -target aarch64 -march=armv8.2-a+noras -### -c %s 2>&1 | FileCheck -check-prefix=V82ANORAS -check-prefix=GENERICV82A %s +// V82ANORAS: "-target-feature" "-ras" + +// RAS is off by default for v8a, but can be enabled by +ras (this is not architecturally valid) +// RUN: %clang -target aarch64 -march=armv8a+ras -### -c %s 2>&1 | FileCheck -check-prefix=V8ARAS -check-prefix=GENERIC %s +// RUN: %clang -target aarch64 -march=armv8-a+ras -### -c %s 2>&1 | FileCheck -check-prefix=V8ARAS -check-prefix=GENERIC %s +// V8ARAS: "-target-feature" "+ras" + // ================== Check whether -march accepts mixed-case values. // RUN: %clang -target aarch64_be -march=ARMV8.1A -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV81A-BE %s // RUN: %clang -target aarch64_be -march=ARMV8.1-A -### -c %s 2>&1 | FileCheck -check-prefix=GENERICV81A-BE %s diff --git a/test/Driver/arm-cortex-cpus.c b/test/Driver/arm-cortex-cpus.c index 90542326f36c..541a1e4e4e58 100644 --- a/test/Driver/arm-cortex-cpus.c +++ b/test/Driver/arm-cortex-cpus.c @@ -287,6 +287,46 @@ // RUN: %clang -target armv8a-linux-eabi -march=armv8.2-a+fp16 -### -c %s 2>&1 | FileCheck --check-prefix CHECK-V82A-FP16 %s // CHECK-V82A-FP16: "-cc1"{{.*}} "-triple" "armv8.2{{.*}}" "-target-cpu" "generic" {{.*}}"-target-feature" "+fullfp16" +// RUN: %clang -target armv8.3a -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V83A %s +// RUN: %clang -target arm -march=armv8.3a -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V83A %s +// RUN: %clang -target arm -march=armv8.3-a -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V83A %s +// RUN: %clang -target arm -march=armv8.3a -mlittle-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V83A %s +// RUN: %clang -target armv8.3a -mlittle-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V83A %s +// RUN: %clang -target arm -march=armv8.3a -mlittle-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V83A %s +// RUN: %clang -target arm -mlittle-endian -march=armv8.3-a -mlittle-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V83A %s +// CHECK-V83A: "-cc1"{{.*}} "-triple" "armv8.3{{.*}}" "-target-cpu" "generic" + +// RUN: %clang -target armebv8.3a -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-V83A %s +// RUN: %clang -target armv8.3a -mbig-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-V83A %s +// RUN: %clang -target armeb -march=armebv8.3a -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-V83A %s +// RUN: %clang -target armeb -march=armebv8.3-a -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-V83A %s +// RUN: %clang -target arm -march=armebv8.3a -mbig-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-V83A %s +// RUN: %clang -target arm -march=armebv8.3-a -mbig-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-V83A %s +// CHECK-BE-V83A: "-cc1"{{.*}} "-triple" "armebv8.3{{.*}}" "-target-cpu" "generic" + +// RUN: %clang -target armv8a-linux-eabi -march=armv8.3-a+fp16 -### -c %s 2>&1 | FileCheck --check-prefix CHECK-V83A-FP16 %s +// CHECK-V83A-FP16: "-cc1"{{.*}} "-triple" "armv8.3{{.*}}" "-target-cpu" "generic" {{.*}}"-target-feature" "+fullfp16" + +// RUN: %clang -target armv8.4a -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V84A %s +// RUN: %clang -target arm -march=armv8.4a -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V84A %s +// RUN: %clang -target arm -march=armv8.4-a -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V84A %s +// RUN: %clang -target arm -march=armv8.4a -mlittle-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V84A %s +// RUN: %clang -target armv8.4a -mlittle-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V84A %s +// RUN: %clang -target arm -march=armv8.4a -mlittle-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V84A %s +// RUN: %clang -target arm -mlittle-endian -march=armv8.4-a -mlittle-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V84A %s +// CHECK-V84A: "-cc1"{{.*}} "-triple" "armv8.4{{.*}}" "-target-cpu" "generic" + +// RUN: %clang -target armebv8.4a -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-V84A %s +// RUN: %clang -target armv8.4a -mbig-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-V84A %s +// RUN: %clang -target armeb -march=armebv8.4a -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-V84A %s +// RUN: %clang -target armeb -march=armebv8.4-a -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-V84A %s +// RUN: %clang -target arm -march=armebv8.4a -mbig-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-V84A %s +// RUN: %clang -target arm -march=armebv8.4-a -mbig-endian -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-V84A %s +// CHECK-BE-V84A: "-cc1"{{.*}} "-triple" "armebv8.4{{.*}}" "-target-cpu" "generic" + +// RUN: %clang -target armv8a-linux-eabi -march=armv8.4-a+fp16 -### -c %s 2>&1 | FileCheck --check-prefix CHECK-V84A-FP16 %s +// CHECK-V84A-FP16: "-cc1"{{.*}} "-triple" "armv8.4{{.*}}" "-target-cpu" "generic" {{.*}}"-target-feature" "+fullfp16" + // Once we have CPUs with optional v8.2-A FP16, we will need a way to turn it // on and off. Cortex-A53 is a placeholder for now. // RUN: %clang -target armv8a-linux-eabi -mcpu=cortex-a53+fp16 -### -c %s 2>&1 | FileCheck --check-prefix CHECK-CORTEX-A53-FP16 %s @@ -294,6 +334,15 @@ // CHECK-CORTEX-A53-FP16: "-cc1" {{.*}}"-target-cpu" "cortex-a53" {{.*}}"-target-feature" "+fullfp16" // CHECK-CORTEX-A53-NOFP16: "-cc1" {{.*}}"-target-cpu" "cortex-a53" {{.*}}"-target-feature" "-fullfp16" +// RAS is on by default for v8.2-a (this is handled in the backend), but can be +// optionally enabled for v8.0-a and v8.1-a. Cortex-A53 does not have RAS, but +// is used here to check that this option will work on any future CPUs that may +// have optional RAS. +// RUN: %clang -target armv8a -march=armv8-a+ras -### -c %s 2>&1 | FileCheck -check-prefix=RAS %s +// RUN: %clang -target armv8a -march=armv8.1-a+ras -### -c %s 2>&1 | FileCheck -check-prefix=RAS %s +// RUN: %clang -target armv8a -mcpu=cortex-a53+ras -### -c %s 2>&1 | FileCheck -check-prefix=RAS %s +// RAS: "-target-feature" "+ras" + // RUN: %clang -target armv8m.base %s -### -c 2>&1 | FileCheck %s --check-prefix=V8M_BASELINE // RUN: %clang -target arm -march=armv8-m.base %s -### -c 2>&1 | FileCheck %s --check-prefix=V8M_BASELINE // RUN: %clang -target arm -march=armv8m.base %s -### -c 2>&1 | FileCheck %s --check-prefix=V8M_BASELINE diff --git a/test/Driver/baremetal.cpp b/test/Driver/baremetal.cpp index a433e2df07cb..2e93734651e8 100644 --- a/test/Driver/baremetal.cpp +++ b/test/Driver/baremetal.cpp @@ -10,7 +10,7 @@ // CHECK-V6M-C-SAME: "-internal-isystem" "[[SYSROOT]]{{[/\\]+}}include{{[/\\]+}}c++{{[/\\]+}}v1" // CHECk-V6M-C-SAME: "-internal-isystem" "[[SYSROOT]]{{[/\\]+}}include" // CHECK-V6M-C-SAME: "-x" "c++" "{{.*}}baremetal.cpp" -// CHECK-V6M-C-NEXT: "{{[^"]*}}ld.lld{{(\.exe)?}}" "{{.*}}.o" "-Bstatic" +// CHECK-V6M-C-NEXT: "{{[^"]*}}ld{{(\.(lld|bfd|gold))?}}{{(\.exe)?}}" "{{.*}}.o" "-Bstatic" // CHECK-V6M-C-SAME: "-L[[RESOURCE_DIR:[^"]+]]{{[/\\]+}}lib{{[/\\]+}}baremetal" // CHECK-V6M-C-SAME: "-T" "semihosted.lds" "-Lsome{{[/\\]+}}directory{{[/\\]+}}user{{[/\\]+}}asked{{[/\\]+}}for" // CHECK-V6M-C-SAME: "-lc" "-lm" "-lclang_rt.builtins-armv6m.a" @@ -32,7 +32,7 @@ // RUN: -target armv6m-none-eabi \ // RUN: --sysroot=%S/Inputs/baremetal_arm \ // RUN: | FileCheck --check-prefix=CHECK-V6M-DEFAULTCXX %s -// CHECK-V6M-DEFAULTCXX: "{{[^"]*}}ld.lld{{(\.exe)?}}" "{{.*}}.o" "-Bstatic" +// CHECK-V6M-DEFAULTCXX: "{{[^"]*}}ld{{(\.(lld|bfd|gold))?}}{{(\.exe)?}}" "{{.*}}.o" "-Bstatic" // CHECK-V6M-DEFAULTCXX-SAME: "-L{{[^"]*}}{{[/\\]+}}lib{{(64)?}}{{[/\\]+}}clang{{[/\\]+}}{{.*}}{{[/\\]+}}lib{{[/\\]+}}baremetal" // CHECK-V6M-DEFAULTCXX-SAME: "-lc++" "-lc++abi" "-lunwind" // CHECK-V6M-DEFAULTCXX-SAME: "-lc" "-lm" "-lclang_rt.builtins-armv6m.a" @@ -45,7 +45,7 @@ // RUN: | FileCheck --check-prefix=CHECK-V6M-LIBCXX %s // CHECK-V6M-LIBCXX-NOT: "-internal-isystem" "{{[^"]+}}{{[/\\]+}}include{{[/\\]+}}c++{{[/\\]+}}{{[^v].*}}" // CHECK-V6M-LIBCXX: "-internal-isystem" "{{[^"]+}}{{[/\\]+}}include{{[/\\]+}}c++{{[/\\]+}}v1" -// CHECK-V6M-LIBCXX: "{{[^"]*}}ld.lld{{(\.exe)?}}" "{{.*}}.o" "-Bstatic" +// CHECK-V6M-LIBCXX: "{{[^"]*}}ld{{(\.(lld|bfd|gold))?}}{{(\.exe)?}}" "{{.*}}.o" "-Bstatic" // CHECK-V6M-LIBCXX-SAME: "-L{{[^"]*}}{{[/\\]+}}lib{{(64)?}}{{[/\\]+}}clang{{[/\\]+}}{{.*}}{{[/\\]+}}lib{{[/\\]+}}baremetal" // CHECK-V6M-LIBCXX-SAME: "-lc++" "-lc++abi" "-lunwind" // CHECK-V6M-LIBCXX-SAME: "-lc" "-lm" "-lclang_rt.builtins-armv6m.a" @@ -58,7 +58,7 @@ // RUN: | FileCheck --check-prefix=CHECK-V6M-LIBSTDCXX %s // CHECK-V6M-LIBSTDCXX-NOT: "-internal-isystem" "{{[^"]+}}{{[/\\]+}}include{{[/\\]+}}c++{{[/\\]+}}v1" // CHECK-V6M-LIBSTDCXX: "-internal-isystem" "{{[^"]+}}{{[/\\]+}}include{{[/\\]+}}c++{{[/\\]+}}6.0.0" -// CHECK-V6M-LIBSTDCXX: "{{[^"]*}}ld.lld{{(\.exe)?}}" "{{.*}}.o" "-Bstatic" +// CHECK-V6M-LIBSTDCXX: "{{[^"]*}}ld{{(\.(lld|bfd|gold))?}}{{(\.exe)?}}" "{{.*}}.o" "-Bstatic" // CHECK-V6M-LIBSTDCXX-SAME: "-L{{[^"]*}}{{[/\\]+}}lib{{(64)?}}{{[/\\]+}}clang{{[/\\]+}}{{.*}}{{[/\\]+}}lib{{[/\\]+}}baremetal" // CHECK-V6M-LIBSTDCXX-SAME: "-lstdc++" "-lsupc++" "-lunwind" // CHECK-V6M-LIBSTDCXX-SAME: "-lc" "-lm" "-lclang_rt.builtins-armv6m.a" @@ -69,7 +69,7 @@ // RUN: --sysroot=%S/Inputs/baremetal_arm \ // RUN: -nodefaultlibs \ // RUN: | FileCheck --check-prefix=CHECK-V6M-NDL %s -// CHECK-V6M-NDL: "{{[^"]*}}ld.lld{{(\.exe)?}}" "{{.*}}.o" "-Bstatic" +// CHECK-V6M-NDL: "{{[^"]*}}ld{{(\.(lld|bfd|gold))?}}{{(\.exe)?}}" "{{.*}}.o" "-Bstatic" // CHECK-V6M-NDL-SAME: "-L{{[^"]*}}{{[/\\]+}}lib{{(64)?}}{{[/\\]+}}clang{{[/\\]+}}{{.*}}{{[/\\]+}}lib{{[/\\]+}}baremetal" "-o" "{{.*}}.o" // RUN: %clangxx -target arm-none-eabi -v 2>&1 \ diff --git a/test/Driver/cuda-dwarf-2.cu b/test/Driver/cuda-dwarf-2.cu index b6c7f500f5ca..7956e6ddbe23 100644 --- a/test/Driver/cuda-dwarf-2.cu +++ b/test/Driver/cuda-dwarf-2.cu @@ -15,6 +15,8 @@ // RUN: %clang -### -target x86_64-linux-gnu -c --cuda-gpu-arch=sm_20 %s -gline-tables-only -O2 --cuda-noopt-device-debug 2>&1 | \ // RUN: FileCheck %s -check-prefix NO_DEBUG -check-prefix LINE_TABLE +// NO_DEBUG-NOT: warning: debug +// LINE_TABLE-NOT: warning: debug // NO_DEBUG: ptxas // NO_DEBUG-NOT: "-g" // LINE_TABLE: "-lineinfo" @@ -36,6 +38,7 @@ // RUN: %clang -### -target x86_64-linux-gnu -c --cuda-gpu-arch=sm_20 %s -ggdb3 -O3 --cuda-noopt-device-debug 2>&1 | \ // RUN: FileCheck %s -check-prefix HAS_DEBUG +// HAS_DEBUG-NOT: warning: debug // HAS_DEBUG: "-fcuda-is-device" // HAS_DEBUG-SAME: "-dwarf-version=2" // HAS_DEBUG: ptxas diff --git a/test/Driver/cuda-unsupported-debug-options.cu b/test/Driver/cuda-unsupported-debug-options.cu new file mode 100644 index 000000000000..3aa1bc0b4711 --- /dev/null +++ b/test/Driver/cuda-unsupported-debug-options.cu @@ -0,0 +1,22 @@ +// REQUIRES: clang-driver +// REQUIRES: x86-registered-target +// REQUIRES: nvptx-registered-target +// REQUIRES: zlib + +// RUN: %clang -### -target x86_64-linux-gnu -c %s -g -gz 2>&1 | FileCheck %s +// RUN: %clang -### -target x86_64-linux-gnu -c %s -gdwarf -fdebug-info-for-profiling 2>&1 | FileCheck %s +// RUN: %clang -### -target x86_64-linux-gnu -c %s -gdwarf-2 -gsplit-dwarf 2>&1 | FileCheck %s +// RUN: %clang -### -target x86_64-linux-gnu -c %s -gdwarf-3 -glldb 2>&1 | FileCheck %s +// RUN: %clang -### -target x86_64-linux-gnu -c %s -gdwarf-4 -gcodeview 2>&1 | FileCheck %s +// RUN: %clang -### -target x86_64-linux-gnu -c %s -gdwarf-5 -gmodules 2>&1 | FileCheck %s +// RUN: %clang -### -target x86_64-linux-gnu -c %s -ggdb -gembed-source -gdwarf-5 2>&1 | FileCheck %s +// RUN: %clang -### -target x86_64-linux-gnu -c %s -ggdb1 -fdebug-macro 2>&1 | FileCheck %s +// RUN: %clang -### -target x86_64-linux-gnu -c %s -ggdb2 -ggnu-pubnames 2>&1 | FileCheck %s +// RUN: %clang -### -target x86_64-linux-gnu -c %s -ggdb3 -gdwarf-aranges 2>&1 | FileCheck %s +// RUN: %clang -### -target x86_64-linux-gnu -c %s -g -gcolumn-info -fdebug-types-section 2>&1 | FileCheck %s +// CHECK: debug information option '{{-gz|-fdebug-info-for-profiling|-gsplit-dwarf|-glldb|-gcodeview|-gmodules|-gembed-source|-fdebug-macro|-ggnu-pubnames|-gdwarf-aranges|-fdebug-types-section}}' is not supported for target 'nvptx64-nvidia-cuda' [-Wunsupported-target-opt] +// CHECK-NOT: debug information option '{{.*}}' is not supported for target 'x86 +// CHECK: "-triple" "nvptx64-nvidia-cuda" +// CHECK-NOT: {{-compress-debug|-fdebug-info-for-profiling|split-dwarf|lldb|codeview|module-format|embed-source|debug-info-macro|gnu-pubnames|generate-arange-section|generate-type-units}} +// CHECK: "-triple" "x86_64 +// CHECK-SAME: {{-compress-debug|-fdebug-info-for-profiling|split-dwarf|lldb|codeview|module-format|embed-source|debug-info-macro|gnu-pubnames|generate-arange-section|generate-type-units}} diff --git a/test/Driver/darwin-asan-nofortify.c b/test/Driver/darwin-asan-nofortify.c index 7d6da6d05798..58b5be9fcbb7 100644 --- a/test/Driver/darwin-asan-nofortify.c +++ b/test/Driver/darwin-asan-nofortify.c @@ -1,5 +1,5 @@ // Make sure AddressSanitizer disables _FORTIFY_SOURCE on Darwin. -// RUN: %clang -fsanitize=address %s -E -dM -target x86_64-darwin -resource-dir %S/Inputs/resource_dir | FileCheck %s +// RUN: %clang -fsanitize=address %s -E -dM -target x86_64-darwin | FileCheck %s // CHECK: #define _FORTIFY_SOURCE 0 diff --git a/test/Driver/darwin-sanitizer-ld.c b/test/Driver/darwin-sanitizer-ld.c index f7dfb157b44e..53c7fce115e7 100644 --- a/test/Driver/darwin-sanitizer-ld.c +++ b/test/Driver/darwin-sanitizer-ld.c @@ -1,7 +1,6 @@ // Test sanitizer link flags on Darwin. // RUN: %clang -no-canonical-prefixes -### -target x86_64-darwin \ -// RUN: -resource-dir %S/Inputs/resource_dir \ // RUN: -stdlib=platform -fsanitize=address %s -o %t.o 2>&1 \ // RUN: | FileCheck --check-prefix=CHECK-ASAN %s @@ -13,14 +12,6 @@ // CHECK-ASAN: "-rpath" "{{.*}}lib{{.*}}darwin" // RUN: %clang -no-canonical-prefixes -### -target x86_64-darwin \ -// RUN: -resource-dir %S/Inputs/fake_resource_dir \ -// RUN: -stdlib=platform -fsanitize=address %s -o %t.o 2>&1 \ -// RUN: | FileCheck --check-prefix=CHECK-LOAD-FAIL %s - -// CHECK-LOAD-FAIL: error: unsupported option '-fsanitize=address' for target 'x86_64--darwin' - -// RUN: %clang -no-canonical-prefixes -### -target x86_64-darwin \ -// RUN: -resource-dir %S/Inputs/resource_dir \ // RUN: -fPIC -shared -fsanitize=address %s -o %t.so 2>&1 \ // RUN: | FileCheck --check-prefix=CHECK-DYN-ASAN %s @@ -31,7 +22,6 @@ // CHECK-DYN-ASAN: "-rpath" "{{.*}}lib{{.*}}darwin" // RUN: %clang -no-canonical-prefixes -### -target x86_64-darwin \ -// RUN: -resource-dir %S/Inputs/resource_dir \ // RUN: -stdlib=platform -fsanitize=undefined %s -o %t.o 2>&1 \ // RUN: | FileCheck --check-prefix=CHECK-UBSAN %s @@ -44,7 +34,6 @@ // RUN: %clang -no-canonical-prefixes -### -target x86_64-darwin \ // RUN: -fsanitize=bounds -fsanitize-undefined-trap-on-error \ -// RUN: -resource-dir %S/Inputs/resource_dir \ // RUN: %s -o %t.o 2>&1 \ // RUN: | FileCheck --check-prefix=CHECK-BOUNDS %s @@ -53,7 +42,6 @@ // RUN: %clang -no-canonical-prefixes -### -target x86_64-darwin \ // RUN: -fPIC -shared -fsanitize=undefined %s -o %t.so 2>&1 \ -// RUN: -resource-dir %S/Inputs/resource_dir \ // RUN: | FileCheck --check-prefix=CHECK-DYN-UBSAN %s // CHECK-DYN-UBSAN: "{{.*}}ld{{(.exe)?}}" @@ -64,7 +52,6 @@ // RUN: %clang -no-canonical-prefixes -### -target x86_64-darwin \ // RUN: -fsanitize=bounds -fsanitize-undefined-trap-on-error \ -// RUN: -resource-dir %S/Inputs/resource_dir \ // RUN: %s -o %t.so -fPIC -shared 2>&1 \ // RUN: | FileCheck --check-prefix=CHECK-DYN-BOUNDS %s @@ -73,7 +60,6 @@ // RUN: %clang -no-canonical-prefixes -### -target x86_64-darwin \ // RUN: -stdlib=platform -fsanitize=address -mios-simulator-version-min=7.0 \ -// RUN: -resource-dir %S/Inputs/resource_dir \ // RUN: %s -o %t.o 2>&1 | FileCheck --check-prefix=CHECK-ASAN-IOSSIM %s // CHECK-ASAN-IOSSIM: "{{.*}}ld{{(.exe)?}}" @@ -84,7 +70,6 @@ // CHECK-ASAN-IOSSIM: "-rpath" "{{.*}}lib{{.*}}darwin" // RUN: %clang -no-canonical-prefixes -### -target x86_64-darwin \ -// RUN: -resource-dir %S/Inputs/resource_dir \ // RUN: -stdlib=platform -fsanitize=address \ // RUN: -mtvos-simulator-version-min=8.3.0 %s -o %t.o 2>&1 \ // RUN: | FileCheck --check-prefix=CHECK-ASAN-TVOSSIM %s @@ -98,7 +83,6 @@ // RUN: %clang -no-canonical-prefixes -### -target x86_64-darwin \ // RUN: -stdlib=platform -fsanitize=address \ -// RUN: -resource-dir %S/Inputs/resource_dir \ // RUN: -mwatchos-simulator-version-min=2.0.0 %s -o %t.o 2>&1 \ // RUN: | FileCheck --check-prefix=CHECK-ASAN-WATCHOSSIM %s @@ -110,7 +94,6 @@ // CHECK-ASAN-WATCHOSSIM: "-rpath" "{{.*}}lib{{.*}}darwin" // RUN: %clang -no-canonical-prefixes -### -target armv7-apple-ios \ -// RUN: -resource-dir %S/Inputs/resource_dir \ // RUN: -stdlib=platform -fsanitize=address -miphoneos-version-min=7 \ // RUN: %s -o %t.o 2>&1 | FileCheck --check-prefix=CHECK-ASAN-IOS %s @@ -123,7 +106,6 @@ // RUN: %clang -no-canonical-prefixes -### -target arm64-apple-tvos \ // RUN: -stdlib=platform -fsanitize=address -mtvos-version-min=8.3 \ -// RUN: -resource-dir %S/Inputs/resource_dir \ // RUN: %s -o %t.o 2>&1 | FileCheck --check-prefix=CHECK-ASAN-TVOS %s // CHECK-ASAN-TVOS: "{{.*}}ld{{(.exe)?}}" @@ -135,7 +117,6 @@ // RUN: %clang -no-canonical-prefixes -### -target armv7k-apple-watchos \ // RUN: -stdlib=platform -fsanitize=address -mwatchos-version-min=2.0 \ -// RUN: -resource-dir %S/Inputs/resource_dir \ // RUN: %s -o %t.o 2>&1 | FileCheck --check-prefix=CHECK-ASAN-WATCHOS %s // CHECK-ASAN-WATCHOS: "{{.*}}ld{{(.exe)?}}" diff --git a/test/Driver/fsanitize.c b/test/Driver/fsanitize.c index e6d94649f065..304e75930245 100644 --- a/test/Driver/fsanitize.c +++ b/test/Driver/fsanitize.c @@ -29,7 +29,22 @@ // CHECK-COVERAGE-WIN64: "--dependent-lib={{[^"]*}}ubsan_standalone-x86_64.lib" // RUN: %clang -target x86_64-linux-gnu -fsanitize=integer %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-INTEGER -implicit-check-not="-fsanitize-address-use-after-scope" -// CHECK-INTEGER: "-fsanitize={{((signed-integer-overflow|unsigned-integer-overflow|integer-divide-by-zero|shift-base|shift-exponent),?){5}"}} +// CHECK-INTEGER: "-fsanitize={{((signed-integer-overflow|unsigned-integer-overflow|integer-divide-by-zero|shift-base|shift-exponent|implicit-integer-truncation),?){6}"}} + +// RUN: %clang -target x86_64-linux-gnu -fsanitize=implicit-conversion %s -### 2>&1 | FileCheck %s --check-prefixes=CHECK-implicit-conversion,CHECK-implicit-conversion-RECOVER +// RUN: %clang -target x86_64-linux-gnu -fsanitize=implicit-conversion -fsanitize-recover=implicit-conversion %s -### 2>&1 | FileCheck %s --check-prefixes=CHECK-implicit-conversion,CHECK-implicit-conversion-RECOVER +// RUN: %clang -target x86_64-linux-gnu -fsanitize=implicit-conversion -fno-sanitize-recover=implicit-conversion %s -### 2>&1 | FileCheck %s --check-prefixes=CHECK-implicit-conversion,CHECK-implicit-conversion-NORECOVER +// RUN: %clang -target x86_64-linux-gnu -fsanitize=implicit-conversion -fsanitize-trap=implicit-conversion %s -### 2>&1 | FileCheck %s --check-prefixes=CHECK-implicit-conversion,CHECK-implicit-conversion-TRAP +// CHECK-implicit-conversion: "-fsanitize={{((implicit-integer-truncation),?){1}"}} +// CHECK-implicit-conversion-RECOVER: "-fsanitize-recover={{((implicit-integer-truncation),?){1}"}} +// CHECK-implicit-conversion-RECOVER-NOT: "-fno-sanitize-recover={{((implicit-integer-truncation),?){1}"}} +// CHECK-implicit-conversion-RECOVER-NOT: "-fsanitize-trap={{((implicit-integer-truncation),?){1}"}} +// CHECK-implicit-conversion-NORECOVER-NOT: "-fno-sanitize-recover={{((implicit-integer-truncation),?){1}"}} // ??? +// CHECK-implicit-conversion-NORECOVER-NOT: "-fsanitize-recover={{((implicit-integer-truncation),?){1}"}} +// CHECK-implicit-conversion-NORECOVER-NOT: "-fsanitize-trap={{((implicit-integer-truncation),?){1}"}} +// CHECK-implicit-conversion-TRAP: "-fsanitize-trap={{((implicit-integer-truncation),?){1}"}} +// CHECK-implicit-conversion-TRAP-NOT: "-fsanitize-recover={{((implicit-integer-truncation),?){1}"}} +// CHECK-implicit-conversion-TRAP-NOT: "-fno-sanitize-recover={{((implicit-integer-truncation),?){1}"}} // RUN: %clang -fsanitize=bounds -### -fsyntax-only %s 2>&1 | FileCheck %s --check-prefix=CHECK-BOUNDS // CHECK-BOUNDS: "-fsanitize={{((array-bounds|local-bounds),?){2}"}} @@ -343,24 +358,24 @@ // RUN: %clang -target x86_64-apple-darwin10 -fsanitize=memory -fno-sanitize=memory %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-MSAN-NOMSAN-DARWIN // CHECK-MSAN-NOMSAN-DARWIN-NOT: unsupported option -// RUN: %clang -target x86_64-apple-darwin10 -fsanitize=memory -fsanitize=thread,memory -resource-dir %S/Inputs/resource_dir %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-MSAN-TSAN-MSAN-DARWIN +// RUN: %clang -target x86_64-apple-darwin10 -fsanitize=memory -fsanitize=thread,memory %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-MSAN-TSAN-MSAN-DARWIN // CHECK-MSAN-TSAN-MSAN-DARWIN: unsupported option '-fsanitize=memory' for target 'x86_64-apple-darwin10' // CHECK-MSAN-TSAN-MSAN-DARWIN-NOT: unsupported option -// RUN: %clang -target x86_64-apple-darwin10 -fsanitize=thread,memory -fsanitize=memory -resource-dir %S/Inputs/resource_dir %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-TSAN-MSAN-MSAN-DARWIN +// RUN: %clang -target x86_64-apple-darwin10 -fsanitize=thread,memory -fsanitize=memory %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-TSAN-MSAN-MSAN-DARWIN // CHECK-TSAN-MSAN-MSAN-DARWIN: unsupported option '-fsanitize=memory' for target 'x86_64-apple-darwin10' // CHECK-TSAN-MSAN-MSAN-DARWIN-NOT: unsupported option -// RUN: %clang -target x86_64-apple-darwin -fsanitize=thread -resource-dir %S/Inputs/resource_dir %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-TSAN-X86-64-DARWIN +// RUN: %clang -target x86_64-apple-darwin -fsanitize=thread %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-TSAN-X86-64-DARWIN // CHECK-TSAN-X86-64-DARWIN-NOT: unsupported option -// RUN: %clang -target x86_64-apple-iossimulator -fsanitize=thread -resource-dir %S/Inputs/resource_dir %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-TSAN-X86-64-IOSSIMULATOR +// RUN: %clang -target x86_64-apple-iossimulator -fsanitize=thread %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-TSAN-X86-64-IOSSIMULATOR // CHECK-TSAN-X86-64-IOSSIMULATOR-NOT: unsupported option -// RUN: %clang -target x86_64-apple-tvossimulator -fsanitize=thread -resource-dir %S/Inputs/resource_dir %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-TSAN-X86-64-TVOSSIMULATOR +// RUN: %clang -target x86_64-apple-tvossimulator -fsanitize=thread %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-TSAN-X86-64-TVOSSIMULATOR // CHECK-TSAN-X86-64-TVOSSIMULATOR-NOT: unsupported option -// RUN: %clang -target i386-apple-darwin -fsanitize=thread -resource-dir %S/Inputs/resource_dir %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-TSAN-I386-DARWIN +// RUN: %clang -target i386-apple-darwin -fsanitize=thread %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-TSAN-I386-DARWIN // CHECK-TSAN-I386-DARWIN: unsupported option '-fsanitize=thread' for target 'i386-apple-darwin' // RUN: %clang -target arm-apple-ios -fsanitize=thread %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-TSAN-ARM-IOS @@ -433,25 +448,25 @@ // RUN: %clang -target i386-pc-openbsd -fsanitize=efficiency-working-set %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-ESAN-OPENBSD // CHECK-ESAN-OPENBSD: error: unsupported option '-fsanitize=efficiency-{{.*}}' for target 'i386-pc-openbsd' -// RUN: %clang -target x86_64-apple-darwin -fsanitize=leak -resource-dir %S/Inputs/resource_dir %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-LSAN-X86-64-DARWIN +// RUN: %clang -target x86_64-apple-darwin -fsanitize=leak %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-LSAN-X86-64-DARWIN // CHECK-LSAN-X86-64-DARWIN-NOT: unsupported option -// RUN: %clang -target x86_64-apple-iossimulator -fsanitize=leak -resource-dir %S/Inputs/resource_dir %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-LSAN-X86-64-IOSSIMULATOR +// RUN: %clang -target x86_64-apple-iossimulator -fsanitize=leak %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-LSAN-X86-64-IOSSIMULATOR // CHECK-LSAN-X86-64-IOSSIMULATOR-NOT: unsupported option -// RUN: %clang -target x86_64-apple-tvossimulator -fsanitize=leak -resource-dir %S/Inputs/resource_dir %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-LSAN-X86-64-TVOSSIMULATOR +// RUN: %clang -target x86_64-apple-tvossimulator -fsanitize=leak %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-LSAN-X86-64-TVOSSIMULATOR // CHECK-LSAN-X86-64-TVOSSIMULATOR-NOT: unsupported option -// RUN: %clang -target i386-apple-darwin -fsanitize=leak -resource-dir %S/Inputs/resource_dir %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-LSAN-I386-DARWIN +// RUN: %clang -target i386-apple-darwin -fsanitize=leak %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-LSAN-I386-DARWIN // CHECK-LSAN-I386-DARWIN-NOT: unsupported option -// RUN: %clang -target arm-apple-ios -fsanitize=leak -resource-dir %S/Inputs/resource_dir %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-LSAN-ARM-IOS +// RUN: %clang -target arm-apple-ios -fsanitize=leak %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-LSAN-ARM-IOS // CHECK-LSAN-ARM-IOS-NOT: unsupported option -// RUN: %clang -target i386-apple-iossimulator -fsanitize=leak -resource-dir %S/Inputs/resource_dir %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-LSAN-I386-IOSSIMULATOR +// RUN: %clang -target i386-apple-iossimulator -fsanitize=leak %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-LSAN-I386-IOSSIMULATOR // CHECK-LSAN-I386-IOSSIMULATOR-NOT: unsupported option -// RUN: %clang -target i386-apple-tvossimulator -fsanitize=leak -resource-dir %S/Inputs/resource_dir %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-LSAN-I386-TVOSSIMULATOR +// RUN: %clang -target i386-apple-tvossimulator -fsanitize=leak %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-LSAN-I386-TVOSSIMULATOR // CHECK-LSAN-I386-TVOSSIMULATOR-NOT: unsupported option // RUN: %clang -target i686-linux-gnu -fsanitize=efficiency-cache-frag %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-ESAN-X86 diff --git a/test/Driver/fuzzer.c b/test/Driver/fuzzer.c index 5a371e260c60..3fdf5ab9c9b9 100644 --- a/test/Driver/fuzzer.c +++ b/test/Driver/fuzzer.c @@ -1,6 +1,6 @@ // Test flags inserted by -fsanitize=fuzzer. -// RUN: %clang -fsanitize=fuzzer %s -target x86_64-apple-darwin14 -resource-dir %S/Inputs/resource_dir -### 2>&1 | FileCheck --check-prefixes=CHECK-FUZZER-LIB,CHECK-COVERAGE-FLAGS %s +// RUN: %clang -fsanitize=fuzzer %s -target x86_64-apple-darwin14 -### 2>&1 | FileCheck --check-prefixes=CHECK-FUZZER-LIB,CHECK-COVERAGE-FLAGS %s // // CHECK-FUZZER-LIB: libclang_rt.fuzzer // CHECK-COVERAGE: -fsanitize-coverage-inline-8bit-counters @@ -8,21 +8,21 @@ // CHECK-COVERAGE-SAME: -fsanitize-coverage-trace-cmp // CHECK-COVERAGE-SAME: -fsanitize-coverage-pc-table -// RUN: %clang -fsanitize=fuzzer -target i386-unknown-linux -stdlib=platform -resource-dir %S/Inputs/resource_dir %s -### 2>&1 | FileCheck --check-prefixes=CHECK-LIBCXX-LINUX %s +// RUN: %clang -fsanitize=fuzzer -target i386-unknown-linux -stdlib=platform %s -### 2>&1 | FileCheck --check-prefixes=CHECK-LIBCXX-LINUX %s // // CHECK-LIBCXX-LINUX: -lstdc++ -// RUN: %clang -target x86_64-apple-darwin14 -fsanitize=fuzzer -resource-dir %S/Inputs/resource_dir %s -### 2>&1 | FileCheck --check-prefixes=CHECK-LIBCXX-DARWIN %s +// RUN: %clang -target x86_64-apple-darwin14 -fsanitize=fuzzer %s -### 2>&1 | FileCheck --check-prefixes=CHECK-LIBCXX-DARWIN %s // // CHECK-LIBCXX-DARWIN: -lc++ // Check that we don't link in libFuzzer.a when producing a shared object. -// RUN: %clang -fsanitize=fuzzer %s -shared -o %t.so -resource-dir %S/Inputs/resource_dir -### 2>&1 | FileCheck --check-prefixes=CHECK-NOLIB-SO %s +// RUN: %clang -fsanitize=fuzzer %s -shared -o %t.so -### 2>&1 | FileCheck --check-prefixes=CHECK-NOLIB-SO %s // CHECK-NOLIB-SO-NOT: libclang_rt.libfuzzer // Check that we don't link in libFuzzer when compiling with -fsanitize=fuzzer-no-link. -// RUN: %clang -fsanitize=fuzzer-no-link %s -target x86_64-apple-darwin14 -resource-dir %S/Inputs/resource_dir -### 2>&1 | FileCheck --check-prefixes=CHECK-NOLIB,CHECK-COV %s +// RUN: %clang -fsanitize=fuzzer-no-link %s -target x86_64-apple-darwin14 -### 2>&1 | FileCheck --check-prefixes=CHECK-NOLIB,CHECK-COV %s // CHECK-NOLIB-NOT: libclang_rt.libfuzzer // CHECK-COV: -fsanitize-coverage-inline-8bit-counters diff --git a/test/Driver/linux-header-search.cpp b/test/Driver/linux-header-search.cpp index 3f024aa49593..f545b439b4ab 100644 --- a/test/Driver/linux-header-search.cpp +++ b/test/Driver/linux-header-search.cpp @@ -493,3 +493,25 @@ // CHECK-DEBIAN-SPARC64: "-internal-externc-isystem" "[[SYSROOT]]/usr/include/sparc64-linux-gnu" // CHECK-DEBIAN-SPARC64: "-internal-externc-isystem" "[[SYSROOT]]/include" // CHECK-DEBIAN-SPARC64: "-internal-externc-isystem" "[[SYSROOT]]/usr/include" + +// Check header search on OpenEmbedded ARM. +// RUN: %clang -no-canonical-prefixes %s -### -fsyntax-only 2>&1 \ +// RUN: -target arm-oe-linux-gnueabi -stdlib=libstdc++ \ +// RUN: --sysroot=%S/Inputs/openembedded_arm_linux_tree \ +// RUN: | FileCheck --check-prefix=CHECK-OE-ARM %s + +// CHECK-OE-ARM: "{{[^"]*}}clang{{[^"]*}}" "-cc1" +// CHECK-OE-ARM: "-isysroot" "[[SYSROOT:[^"]+]]" +// CHECK-OE-ARM: "-internal-isystem" "[[SYSROOT]]/usr/lib/arm-oe-linux-gnueabi/6.3.0/../../../include/c++/6.3.0" +// CHECK-OE-ARM: "-internal-isystem" "[[SYSROOT]]/usr/lib/arm-oe-linux-gnueabi/6.3.0/../../../include/c++/6.3.0/backward" + +// Check header search on OpenEmbedded AArch64. +// RUN: %clang -no-canonical-prefixes %s -### -fsyntax-only 2>&1 \ +// RUN: -target aarch64-oe-linux -stdlib=libstdc++ \ +// RUN: --sysroot=%S/Inputs/openembedded_aarch64_linux_tree \ +// RUN: | FileCheck --check-prefix=CHECK-OE-AARCH64 %s + +// CHECK-OE-AARCH64: "{{[^"]*}}clang{{[^"]*}}" "-cc1" +// CHECK-OE-AARCH64: "-isysroot" "[[SYSROOT:[^"]+]]" +// CHECK-OE-AARCH64: "-internal-isystem" "[[SYSROOT]]/usr/lib64/aarch64-oe-linux/6.3.0/../../../include/c++/6.3.0" +// CHECK-OE-AARCH64: "-internal-isystem" "[[SYSROOT]]/usr/lib64/aarch64-oe-linux/6.3.0/../../../include/c++/6.3.0/backward" diff --git a/test/Driver/linux-ld.c b/test/Driver/linux-ld.c index 02e6618a0460..787013931a48 100644 --- a/test/Driver/linux-ld.c +++ b/test/Driver/linux-ld.c @@ -1813,4 +1813,40 @@ // CHECK-LD-AMI: "-lgcc" "--as-needed" "-lgcc_s" "--no-as-needed" // CHECK-LD-AMI: "-lc" // CHECK-LD-AMI: "-lgcc" "--as-needed" "-lgcc_s" "--no-as-needed" -// + +// Check whether the OpenEmbedded ARM libs are added correctly. +// RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \ +// RUN: --target=arm-oe-linux-gnueabi -rtlib=libgcc \ +// RUN: --sysroot=%S/Inputs/openembedded_arm_linux_tree \ +// RUN: | FileCheck --check-prefix=CHECK-OE-ARM %s + +// CHECK-OE-ARM: "-cc1" "-triple" "armv4t-oe-linux-gnueabi" +// CHECK-OE-ARM: ld{{.*}}" "--sysroot=[[SYSROOT:[^"]+]]" +// CHECK-OE-ARM: "-m" "armelf_linux_eabi" "-dynamic-linker" +// CHECK-OE-ARM: "[[SYSROOT]]/usr/lib/arm-oe-linux-gnueabi/6.3.0/../../../lib{{/|\\\\}}crt1.o" +// CHECK-OE-ARM: "[[SYSROOT]]/usr/lib/arm-oe-linux-gnueabi/6.3.0/../../../lib{{/|\\\\}}crti.o" +// CHECK-OE-ARM: "[[SYSROOT]]/usr/lib/arm-oe-linux-gnueabi/6.3.0{{/|\\\\}}crtbegin.o" +// CHECK-OE-ARM: "-L[[SYSROOT]]/usr/lib/arm-oe-linux-gnueabi/6.3.0" +// CHECK-OE-ARM: "-L[[SYSROOT]]/usr/lib/arm-oe-linux-gnueabi" +// CHECK-OE-ARM: "-L[[SYSROOT]]/usr/lib" +// CHECK-OE-ARM: "-lgcc" "--as-needed" "-lgcc_s" "--no-as-needed" "-lc" "-lgcc" "--as-needed" "-lgcc_s" "--no-as-needed" +// CHECK-OE-ARM: "[[SYSROOT]]/usr/lib/arm-oe-linux-gnueabi/6.3.0{{/|\\\\}}crtend.o" +// CHECK-OE-ARM: "[[SYSROOT]]/usr/lib/arm-oe-linux-gnueabi/6.3.0/../../../lib{{/|\\\\}}crtn.o" + +// Check whether the OpenEmbedded AArch64 libs are added correctly. +// RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \ +// RUN: --target=aarch64-oe-linux -rtlib=libgcc \ +// RUN: --sysroot=%S/Inputs/openembedded_aarch64_linux_tree \ +// RUN: | FileCheck --check-prefix=CHECK-OE-AARCH64 %s + +// CHECK-OE-AARCH64: "-cc1" "-triple" "aarch64-oe-linux" +// CHECK-OE-AARCH64: ld{{.*}}" "--sysroot=[[SYSROOT:[^"]+]]" +// CHECK-OE-AARCH64: "-m" "aarch64linux" "-dynamic-linker" +// CHECK-OE-AARCH64: "[[SYSROOT]]/usr/lib64/aarch64-oe-linux/6.3.0/../../../lib64{{/|\\\\}}crt1.o" +// CHECK-OE-AARCH64: "[[SYSROOT]]/usr/lib64/aarch64-oe-linux/6.3.0/../../../lib64{{/|\\\\}}crti.o" +// CHECK-OE-AARCH64: "[[SYSROOT]]/usr/lib64/aarch64-oe-linux/6.3.0{{/|\\\\}}crtbegin.o" +// CHECK-OE-AARCH64: "-L[[SYSROOT]]/usr/lib64/aarch64-oe-linux/6.3.0" +// CHECK-OE-AARCH64: "-L[[SYSROOT]]/usr/lib64" +// CHECK-OE-AARCH64: "-lgcc" "--as-needed" "-lgcc_s" "--no-as-needed" "-lc" "-lgcc" "--as-needed" "-lgcc_s" "--no-as-needed" +// CHECK-OE-AARCH64: "[[SYSROOT]]/usr/lib64/aarch64-oe-linux/6.3.0{{/|\\\\}}crtend.o" +// CHECK-OE-AARCH64: "[[SYSROOT]]/usr/lib64/aarch64-oe-linux/6.3.0/../../../lib64{{/|\\\\}}crtn.o" diff --git a/test/Driver/openmp-offload-gpu.c b/test/Driver/openmp-offload-gpu.c index 3d14041a13f8..ca3d9445443d 100644 --- a/test/Driver/openmp-offload-gpu.c +++ b/test/Driver/openmp-offload-gpu.c @@ -182,6 +182,8 @@ // RUN: %clang -### -no-canonical-prefixes -fopenmp=libomp -fopenmp-targets=nvptx64-nvidia-cuda -Xopenmp-target -march=sm_60 %s -ggdb1 -O2 --cuda-noopt-device-debug 2>&1 \ // RUN: | FileCheck -check-prefix=NO_DEBUG -check-prefix=LINE_TABLE %s +// LINE_TABLE-NOT: warning: debug +// NO_DEBUG-NOT: warning: debug // NO_DEBUG: ptxas // LINE_TABLE: "-lineinfo" // NO_DEBUG-NOT: "-g" @@ -203,6 +205,7 @@ // RUN: %clang -### -no-canonical-prefixes -fopenmp=libomp -fopenmp-targets=nvptx64-nvidia-cuda -Xopenmp-target -march=sm_60 %s -ggdb3 -O2 --cuda-noopt-device-debug 2>&1 \ // RUN: | FileCheck -check-prefix=HAS_DEBUG %s +// HAS_DEBUG-NOT: warning: debug // HAS_DEBUG: "-triple" "nvptx64-nvidia-cuda" // HAS_DEBUG-SAME: "-dwarf-version=2" // HAS_DEBUG-SAME: "-fopenmp-is-device" diff --git a/test/Driver/openmp-unsupported-debug-options.c b/test/Driver/openmp-unsupported-debug-options.c new file mode 100644 index 000000000000..20e0c47f7fff --- /dev/null +++ b/test/Driver/openmp-unsupported-debug-options.c @@ -0,0 +1,22 @@ +// REQUIRES: clang-driver +// REQUIRES: x86-registered-target +// REQUIRES: nvptx-registered-target +// REQUIRES: zlib + +// RUN: %clang -### -target x86_64-linux-gnu -fopenmp=libomp -fopenmp-targets=nvptx64-nvidia-cuda -c %s -g -gz 2>&1 | FileCheck %s +// RUN: %clang -### -target x86_64-linux-gnu -fopenmp=libomp -fopenmp-targets=nvptx64-nvidia-cuda -c %s -gdwarf -fdebug-info-for-profiling 2>&1 | FileCheck %s +// RUN: %clang -### -target x86_64-linux-gnu -fopenmp=libomp -fopenmp-targets=nvptx64-nvidia-cuda -c %s -gdwarf-2 -gsplit-dwarf 2>&1 | FileCheck %s +// RUN: %clang -### -target x86_64-linux-gnu -fopenmp=libomp -fopenmp-targets=nvptx64-nvidia-cuda -c %s -gdwarf-3 -glldb 2>&1 | FileCheck %s +// RUN: %clang -### -target x86_64-linux-gnu -fopenmp=libomp -fopenmp-targets=nvptx64-nvidia-cuda -c %s -gdwarf-4 -gcodeview 2>&1 | FileCheck %s +// RUN: %clang -### -target x86_64-linux-gnu -fopenmp=libomp -fopenmp-targets=nvptx64-nvidia-cuda -c %s -gdwarf-5 -gmodules 2>&1 | FileCheck %s +// RUN: %clang -### -target x86_64-linux-gnu -fopenmp=libomp -fopenmp-targets=nvptx64-nvidia-cuda -c %s -ggdb -gembed-source -gdwarf-5 2>&1 | FileCheck %s +// RUN: %clang -### -target x86_64-linux-gnu -fopenmp=libomp -fopenmp-targets=nvptx64-nvidia-cuda -c %s -ggdb1 -fdebug-macro 2>&1 | FileCheck %s +// RUN: %clang -### -target x86_64-linux-gnu -fopenmp=libomp -fopenmp-targets=nvptx64-nvidia-cuda -c %s -ggdb2 -ggnu-pubnames 2>&1 | FileCheck %s +// RUN: %clang -### -target x86_64-linux-gnu -fopenmp=libomp -fopenmp-targets=nvptx64-nvidia-cuda -c %s -ggdb3 -gdwarf-aranges 2>&1 | FileCheck %s +// RUN: %clang -### -target x86_64-linux-gnu -fopenmp=libomp -fopenmp-targets=nvptx64-nvidia-cuda -c %s -g -gcolumn-info -fdebug-types-section 2>&1 | FileCheck %s +// CHECK: debug information option '{{-gz|-fdebug-info-for-profiling|-gsplit-dwarf|-glldb|-gcodeview|-gmodules|-gembed-source|-fdebug-macro|-ggnu-pubnames|-gdwarf-aranges|-fdebug-types-section}}' is not supported for target 'nvptx64-nvidia-cuda' [-Wunsupported-target-opt] +// CHECK-NOT: debug information option '{{.*}}' is not supported for target 'x86 +// CHECK: "-triple" "nvptx64-nvidia-cuda" +// CHECK-NOT: {{-compress-debug|-fdebug-info-for-profiling|split-dwarf|lldb|codeview|module-format|embed-source|debug-info-macro|gnu-pubnames|generate-arange-section|generate-type-units}} +// CHECK: "-triple" "x86_64 +// CHECK-SAME: {{-compress-debug|-fdebug-info-for-profiling|split-dwarf|lldb|codeview|module-format|embed-source|debug-info-macro|gnu-pubnames|generate-arange-section|generate-type-units}} diff --git a/test/Driver/riscv32-toolchain.c b/test/Driver/riscv32-toolchain.c index 1e93e97c5313..1e0c750a3fa4 100644 --- a/test/Driver/riscv32-toolchain.c +++ b/test/Driver/riscv32-toolchain.c @@ -3,6 +3,36 @@ // RUN: %clang %s -### -no-canonical-prefixes -target riscv32 2>&1 | FileCheck -check-prefix=CC1 %s // CC1: clang{{.*}} "-cc1" "-triple" "riscv32" +// RUN: %clang %s -### -no-canonical-prefixes \ +// RUN: -target riscv32-unknown-elf \ +// RUN: --gcc-toolchain=%S/Inputs/basic_riscv32_tree \ +// RUN: --sysroot=%S/Inputs/basic_riscv32_tree/riscv32-unknown-elf 2>&1 \ +// RUN: | FileCheck -check-prefix=C-RV32-BAREMETAL-ILP32 %s + +// C-RV32-BAREMETAL-ILP32: "{{.*}}Inputs/basic_riscv32_tree/lib/gcc/riscv32-unknown-elf/8.0.1/../../../../bin{{/|\\\\}}riscv32-unknown-elf-ld" +// C-RV32-BAREMETAL-ILP32: "--sysroot={{.*}}/Inputs/basic_riscv32_tree/riscv32-unknown-elf" +// C-RV32-BAREMETAL-ILP32: "{{.*}}/Inputs/basic_riscv32_tree/riscv32-unknown-elf/lib{{/|\\\\}}crt0.o" +// C-RV32-BAREMETAL-ILP32: "{{.*}}/Inputs/basic_riscv32_tree/lib/gcc/riscv32-unknown-elf/8.0.1{{/|\\\\}}crtbegin.o" +// C-RV32-BAREMETAL-ILP32: "-L{{.*}}/Inputs/basic_riscv32_tree/riscv32-unknown-elf/lib" +// C-RV32-BAREMETAL-ILP32: "-L{{.*}}/Inputs/basic_riscv32_tree/lib/gcc/riscv32-unknown-elf/8.0.1" +// C-RV32-BAREMETAL-ILP32: "--start-group" "-lc" "-lgloss" "--end-group" "-lgcc" +// C-RV32-BAREMETAL-ILP32: "{{.*}}/Inputs/basic_riscv32_tree/lib/gcc/riscv32-unknown-elf/8.0.1{{/|\\\\}}crtend.o" + +// RUN: %clangxx %s -### -no-canonical-prefixes \ +// RUN: -target riscv32-unknown-elf -stdlib=libstdc++ \ +// RUN: --gcc-toolchain=%S/Inputs/basic_riscv32_tree \ +// RUN: --sysroot=%S/Inputs/basic_riscv32_tree/riscv32-unknown-elf 2>&1 \ +// RUN: | FileCheck -check-prefix=CXX-RV32-BAREMETAL-ILP32 %s + +// CXX-RV32-BAREMETAL-ILP32: "-internal-isystem" "{{.*}}Inputs/basic_riscv32_tree/lib/gcc/riscv32-unknown-elf/8.0.1/../../../../riscv32-unknown-elf/include/c++{{/|\\\\}}8.0.1" +// CXX-RV32-BAREMETAL-ILP32: "{{.*}}Inputs/basic_riscv32_tree/lib/gcc/riscv32-unknown-elf/8.0.1/../../../../bin{{/|\\\\}}riscv32-unknown-elf-ld" +// CXX-RV32-BAREMETAL-ILP32: "--sysroot={{.*}}/Inputs/basic_riscv32_tree/riscv32-unknown-elf" +// CXX-RV32-BAREMETAL-ILP32: "{{.*}}/Inputs/basic_riscv32_tree/riscv32-unknown-elf/lib{{/|\\\\}}crt0.o" +// CXX-RV32-BAREMETAL-ILP32: "{{.*}}/Inputs/basic_riscv32_tree/lib/gcc/riscv32-unknown-elf/8.0.1{{/|\\\\}}crtbegin.o" +// CXX-RV32-BAREMETAL-ILP32: "-L{{.*}}/Inputs/basic_riscv32_tree/riscv32-unknown-elf/lib" +// CXX-RV32-BAREMETAL-ILP32: "-L{{.*}}/Inputs/basic_riscv32_tree/lib/gcc/riscv32-unknown-elf/8.0.1" +// CXX-RV32-BAREMETAL-ILP32: "-lstdc++" "--start-group" "-lc" "-lgloss" "--end-group" "-lgcc" +// CXX-RV32-BAREMETAL-ILP32: "{{.*}}/Inputs/basic_riscv32_tree/lib/gcc/riscv32-unknown-elf/8.0.1{{/|\\\\}}crtend.o" // RUN: %clang %s -### -no-canonical-prefixes -fuse-ld=ld \ // RUN: -target riscv32-linux-unknown-elf \ diff --git a/test/Driver/sanitizer-ld.c b/test/Driver/sanitizer-ld.c index f07fe922ecca..483c87a6242f 100644 --- a/test/Driver/sanitizer-ld.c +++ b/test/Driver/sanitizer-ld.c @@ -530,7 +530,6 @@ // RUN: %clangxx -fsanitize=address %s -### -o %t.o 2>&1 \ // RUN: -mmacosx-version-min=10.6 \ -// RUN: -resource-dir=%S/Inputs/resource_dir \ // RUN: -target x86_64-apple-darwin13.4.0 -fuse-ld=ld -stdlib=platform \ // RUN: --sysroot=%S/Inputs/basic_linux_tree \ // RUN: | FileCheck --check-prefix=CHECK-ASAN-DARWIN106-CXX %s @@ -540,7 +539,6 @@ // RUN: %clangxx -fsanitize=leak %s -### -o %t.o 2>&1 \ // RUN: -mmacosx-version-min=10.6 \ -// RUN: -resource-dir=%S/Inputs/resource_dir \ // RUN: -target x86_64-apple-darwin13.4.0 -fuse-ld=ld -stdlib=platform \ // RUN: --sysroot=%S/Inputs/basic_linux_tree \ // RUN: | FileCheck --check-prefix=CHECK-LSAN-DARWIN106-CXX %s @@ -600,7 +598,6 @@ // RUN: %clang -fsanitize=cfi -fsanitize-stats %s -### -o %t.o 2>&1 \ // RUN: -target x86_64-apple-darwin -fuse-ld=ld \ -// RUN: -resource-dir=%S/Inputs/resource_dir \ // RUN: --sysroot=%S/Inputs/basic_linux_tree \ // RUN: | FileCheck --check-prefix=CHECK-CFI-STATS-DARWIN %s // CHECK-CFI-STATS-DARWIN: "{{.*}}ld{{(.exe)?}}" diff --git a/test/Frontend/clang-abi-compat.cpp b/test/Frontend/clang-abi-compat.cpp index 7ee94646b6d7..b7f2758a9db6 100644 --- a/test/Frontend/clang-abi-compat.cpp +++ b/test/Frontend/clang-abi-compat.cpp @@ -1,6 +1,6 @@ // RUN: not %clang_cc1 -fclang-abi-compat=banana %s -fsyntax-only 2>&1 | FileCheck --check-prefix=INVALID %s // RUN: not %clang_cc1 -fclang-abi-compat=2.9 %s -fsyntax-only 2>&1 | FileCheck --check-prefix=INVALID %s -// RUN: not %clang_cc1 -fclang-abi-compat=8 %s -fsyntax-only 2>&1 | FileCheck --check-prefix=INVALID %s +// RUN: not %clang_cc1 -fclang-abi-compat=42 %s -fsyntax-only 2>&1 | FileCheck --check-prefix=INVALID %s // RUN: not %clang_cc1 -fclang-abi-compat=3.10 %s -fsyntax-only 2>&1 | FileCheck --check-prefix=INVALID %s // RUN: not %clang_cc1 -fclang-abi-compat=4.1 %s -fsyntax-only 2>&1 | FileCheck --check-prefix=INVALID %s // RUN: not %clang_cc1 -fclang-abi-compat=04 %s -fsyntax-only 2>&1 | FileCheck --check-prefix=INVALID %s diff --git a/test/Index/complete-access-checks-crash.cpp b/test/Index/complete-access-checks-crash.cpp new file mode 100644 index 000000000000..c7ac4d656378 --- /dev/null +++ b/test/Index/complete-access-checks-crash.cpp @@ -0,0 +1,13 @@ +struct Base { +protected: + bool bar(); +}; +struct Derived : Base { +}; + +struct X { + int foo() { + Derived(). // RUN: c-index-test -code-completion-at=%s:10:15 %s | FileCheck %s + // CHECK: bar{{.*}}(inaccessible) + } +}; diff --git a/test/Modules/resolution-change.m b/test/Modules/resolution-change.m index bf95104968a3..4c8eb70db8ad 100644 --- a/test/Modules/resolution-change.m +++ b/test/Modules/resolution-change.m @@ -21,6 +21,8 @@ // RUN: not %clang_cc1 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -I %S/Inputs/modules-with-same-name/DependsOnA -I %S/Inputs/modules-with-same-name/path2/A -include-pch %t-A.pch %s -fsyntax-only 2>&1 | FileCheck -check-prefix=CHECK-WRONGA %s // CHECK-WRONGA: module 'A' was built in directory '{{.*Inputs.modules-with-same-name.path1.A}}' but now resides in directory '{{.*Inputs.modules-with-same-name.path2.A}}' +// RUN: %clang_cc1 -fno-validate-pch -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -I %S/Inputs/modules-with-same-name/DependsOnA -I %S/Inputs/modules-with-same-name/path2/A -include-pch %t-A.pch %s -fsyntax-only + #ifndef HEADER #define HEADER @import DependsOnA; diff --git a/test/OpenMP/declare_target_codegen.cpp b/test/OpenMP/declare_target_codegen.cpp index a221387c7312..96bdc874ece2 100644 --- a/test/OpenMP/declare_target_codegen.cpp +++ b/test/OpenMP/declare_target_codegen.cpp @@ -18,14 +18,15 @@ // CHECK-DAG: @d = global i32 0, // CHECK-DAG: @c = external global i32, // CHECK-DAG: @globals = global %struct.S zeroinitializer, -// CHECK-DAG: @{{.+}}stat = weak_odr global %struct.S zeroinitializer, -// CHECK-DAG: @llvm.used = appending global [2 x i8*] [i8* bitcast (void ()* @__omp_offloading__{{.+}}_globals_l[[@LINE+42]]_ctor to i8*), i8* bitcast (void ()* @__omp_offloading__{{.+}}_stat_l[[@LINE+43]]_ctor to i8*)], section "llvm.metadata" +// CHECK-DAG: [[STAT:@.+stat]] = internal global %struct.S zeroinitializer, +// CHECK-DAG: [[STAT_REF:@.+]] = internal constant %struct.S* [[STAT]] +// CHECK-DAG: @llvm.used = appending global [2 x i8*] [i8* bitcast (void ()* @__omp_offloading__{{.+}}_globals_l[[@LINE+42]]_ctor to i8*), i8* bitcast (void ()* @__omp_offloading__{{.+}}_stat_l[[@LINE+43]]_ctor to i8*)], +// CHECK-DAG: @llvm.compiler.used = appending global [1 x i8*] [i8* bitcast (%struct.S** [[STAT_REF]] to i8*)], // CHECK-DAG: define {{.*}}i32 @{{.*}}{{foo|bar|baz2|baz3|FA|f_method}}{{.*}}() // CHECK-DAG: define {{.*}}void @{{.*}}TemplateClass{{.*}}(%class.TemplateClass* %{{.*}}) // CHECK-DAG: define {{.*}}i32 @{{.*}}TemplateClass{{.*}}f_method{{.*}}(%class.TemplateClass* %{{.*}}) -// CHECK-DAG: define {{.*}}void @__omp_offloading__{{.*}}_globals_l[[@LINE+37]]_ctor() -// CHECK-DAG: define {{.*}}void @__omp_offloading__{{.*}}_stat_l[[@LINE+37]]_ctor() +// CHECK-DAG: define {{.*}}void @__omp_offloading__{{.*}}_globals_l[[@LINE+36]]_ctor() #ifndef HEADER #define HEADER diff --git a/test/OpenMP/nvptx_declare_target_var_ctor_dtor_codegen.cpp b/test/OpenMP/nvptx_declare_target_var_ctor_dtor_codegen.cpp index 3cd85eefbc2c..b9049a40281d 100644 --- a/test/OpenMP/nvptx_declare_target_var_ctor_dtor_codegen.cpp +++ b/test/OpenMP/nvptx_declare_target_var_ctor_dtor_codegen.cpp @@ -15,7 +15,7 @@ // SIMD-ONLY-NOT: {{__kmpc|__tgt}} -// DEVICE-DAG: [[C_ADDR:.+]] = weak_odr global i32 0, +// DEVICE-DAG: [[C_ADDR:.+]] = internal global i32 0, // DEVICE-DAG: [[CD_ADDR:@.+]] = global %struct.S zeroinitializer, // HOST-DAG: @[[C_ADDR:.+]] = internal global i32 0, // HOST-DAG: @[[CD_ADDR:.+]] = global %struct.S zeroinitializer, diff --git a/test/OpenMP/target_codegen.cpp b/test/OpenMP/target_codegen.cpp index 15eb469fa280..6395dd354fa2 100644 --- a/test/OpenMP/target_codegen.cpp +++ b/test/OpenMP/target_codegen.cpp @@ -85,8 +85,8 @@ // Check if offloading descriptor is created. // CHECK: [[ENTBEGIN:@.+]] = external constant [[ENTTY]] // CHECK: [[ENTEND:@.+]] = external constant [[ENTTY]] -// CHECK: [[DEVBEGIN:@.+]] = external constant i8 -// CHECK: [[DEVEND:@.+]] = external constant i8 +// CHECK: [[DEVBEGIN:@.+]] = extern_weak constant i8 +// CHECK: [[DEVEND:@.+]] = extern_weak constant i8 // CHECK: [[IMAGES:@.+]] = internal unnamed_addr constant [1 x [[DEVTY]]] [{{.+}} { i8* [[DEVBEGIN]], i8* [[DEVEND]], [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }], comdat($[[REGFN]]) // CHECK: [[DESC:@.+]] = internal constant [[DSCTY]] { i32 1, [[DEVTY]]* getelementptr inbounds ([1 x [[DEVTY]]], [1 x [[DEVTY]]]* [[IMAGES]], i32 0, i32 0), [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }, comdat($[[REGFN]]) diff --git a/test/OpenMP/target_codegen_registration.cpp b/test/OpenMP/target_codegen_registration.cpp index b98b33c9a4dd..2774de64fc7f 100644 --- a/test/OpenMP/target_codegen_registration.cpp +++ b/test/OpenMP/target_codegen_registration.cpp @@ -174,8 +174,8 @@ // CHECK: [[ENTBEGIN:@.+]] = external constant [[ENTTY]] // CHECK: [[ENTEND:@.+]] = external constant [[ENTTY]] -// CHECK: [[DEVBEGIN:@.+]] = external constant i8 -// CHECK: [[DEVEND:@.+]] = external constant i8 +// CHECK: [[DEVBEGIN:@.+]] = extern_weak constant i8 +// CHECK: [[DEVEND:@.+]] = extern_weak constant i8 // CHECK: [[IMAGES:@.+]] = internal unnamed_addr constant [1 x [[DEVTY]]] [{{.+}} { i8* [[DEVBEGIN]], i8* [[DEVEND]], [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }], comdat($[[REGFN]]) // CHECK: [[DESC:@.+]] = internal constant [[DSCTY]] { i32 1, [[DEVTY]]* getelementptr inbounds ([1 x [[DEVTY]]], [1 x [[DEVTY]]]* [[IMAGES]], i32 0, i32 0), [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }, comdat($[[REGFN]]) diff --git a/test/OpenMP/target_depend_codegen.cpp b/test/OpenMP/target_depend_codegen.cpp index bd709e1def7d..588ab9757e4a 100644 --- a/test/OpenMP/target_depend_codegen.cpp +++ b/test/OpenMP/target_depend_codegen.cpp @@ -58,8 +58,8 @@ // Check if offloading descriptor is created. // CHECK: [[ENTBEGIN:@.+]] = external constant [[ENTTY]] // CHECK: [[ENTEND:@.+]] = external constant [[ENTTY]] -// CHECK: [[DEVBEGIN:@.+]] = external constant i8 -// CHECK: [[DEVEND:@.+]] = external constant i8 +// CHECK: [[DEVBEGIN:@.+]] = extern_weak constant i8 +// CHECK: [[DEVEND:@.+]] = extern_weak constant i8 // CHECK: [[IMAGES:@.+]] = internal unnamed_addr constant [1 x [[DEVTY]]] [{{.+}} { i8* [[DEVBEGIN]], i8* [[DEVEND]], [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }], comdat($[[REGFN]]) // CHECK: [[DESC:@.+]] = internal constant [[DSCTY]] { i32 1, [[DEVTY]]* getelementptr inbounds ([1 x [[DEVTY]]], [1 x [[DEVTY]]]* [[IMAGES]], i32 0, i32 0), [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }, comdat($[[REGFN]]) diff --git a/test/OpenMP/target_parallel_codegen.cpp b/test/OpenMP/target_parallel_codegen.cpp index f1a511a6bb45..bebde4edf722 100644 --- a/test/OpenMP/target_parallel_codegen.cpp +++ b/test/OpenMP/target_parallel_codegen.cpp @@ -85,8 +85,8 @@ // Check if offloading descriptor is created. // CHECK: [[ENTBEGIN:@.+]] = external constant [[ENTTY]] // CHECK: [[ENTEND:@.+]] = external constant [[ENTTY]] -// CHECK: [[DEVBEGIN:@.+]] = external constant i8 -// CHECK: [[DEVEND:@.+]] = external constant i8 +// CHECK: [[DEVBEGIN:@.+]] = extern_weak constant i8 +// CHECK: [[DEVEND:@.+]] = extern_weak constant i8 // CHECK: [[IMAGES:@.+]] = internal unnamed_addr constant [1 x [[DEVTY]]] [{{.+}} { i8* [[DEVBEGIN]], i8* [[DEVEND]], [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }], comdat($[[REGFN]]) // CHECK: [[DESC:@.+]] = internal constant [[DSCTY]] { i32 1, [[DEVTY]]* getelementptr inbounds ([1 x [[DEVTY]]], [1 x [[DEVTY]]]* [[IMAGES]], i32 0, i32 0), [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }, comdat($[[REGFN]]) diff --git a/test/OpenMP/target_parallel_codegen_registration.cpp b/test/OpenMP/target_parallel_codegen_registration.cpp index c9892eae36d6..234c5500c1f3 100644 --- a/test/OpenMP/target_parallel_codegen_registration.cpp +++ b/test/OpenMP/target_parallel_codegen_registration.cpp @@ -174,8 +174,8 @@ // CHECK: [[ENTBEGIN:@.+]] = external constant [[ENTTY]] // CHECK: [[ENTEND:@.+]] = external constant [[ENTTY]] -// CHECK: [[DEVBEGIN:@.+]] = external constant i8 -// CHECK: [[DEVEND:@.+]] = external constant i8 +// CHECK: [[DEVBEGIN:@.+]] = extern_weak constant i8 +// CHECK: [[DEVEND:@.+]] = extern_weak constant i8 // CHECK: [[IMAGES:@.+]] = internal unnamed_addr constant [1 x [[DEVTY]]] [{{.+}} { i8* [[DEVBEGIN]], i8* [[DEVEND]], [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }], comdat($[[REGFN]]) // CHECK: [[DESC:@.+]] = internal constant [[DSCTY]] { i32 1, [[DEVTY]]* getelementptr inbounds ([1 x [[DEVTY]]], [1 x [[DEVTY]]]* [[IMAGES]], i32 0, i32 0), [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }, comdat($[[REGFN]]) diff --git a/test/OpenMP/target_parallel_depend_codegen.cpp b/test/OpenMP/target_parallel_depend_codegen.cpp index 52d13a34d85a..dc55ec15e51f 100644 --- a/test/OpenMP/target_parallel_depend_codegen.cpp +++ b/test/OpenMP/target_parallel_depend_codegen.cpp @@ -58,8 +58,8 @@ // Check if offloading descriptor is created. // CHECK: [[ENTBEGIN:@.+]] = external constant [[ENTTY]] // CHECK: [[ENTEND:@.+]] = external constant [[ENTTY]] -// CHECK: [[DEVBEGIN:@.+]] = external constant i8 -// CHECK: [[DEVEND:@.+]] = external constant i8 +// CHECK: [[DEVBEGIN:@.+]] = extern_weak constant i8 +// CHECK: [[DEVEND:@.+]] = extern_weak constant i8 // CHECK: [[IMAGES:@.+]] = internal unnamed_addr constant [1 x [[DEVTY]]] [{{.+}} { i8* [[DEVBEGIN]], i8* [[DEVEND]], [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }], comdat($[[REGFN]]) // CHECK: [[DESC:@.+]] = internal constant [[DSCTY]] { i32 1, [[DEVTY]]* getelementptr inbounds ([1 x [[DEVTY]]], [1 x [[DEVTY]]]* [[IMAGES]], i32 0, i32 0), [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }, comdat($[[REGFN]]) diff --git a/test/OpenMP/target_parallel_for_codegen.cpp b/test/OpenMP/target_parallel_for_codegen.cpp index d541d14670a5..dc6243c9df3c 100644 --- a/test/OpenMP/target_parallel_for_codegen.cpp +++ b/test/OpenMP/target_parallel_for_codegen.cpp @@ -86,8 +86,8 @@ // Check if offloading descriptor is created. // CHECK: [[ENTBEGIN:@.+]] = external constant [[ENTTY]] // CHECK: [[ENTEND:@.+]] = external constant [[ENTTY]] -// CHECK: [[DEVBEGIN:@.+]] = external constant i8 -// CHECK: [[DEVEND:@.+]] = external constant i8 +// CHECK: [[DEVBEGIN:@.+]] = extern_weak constant i8 +// CHECK: [[DEVEND:@.+]] = extern_weak constant i8 // CHECK: [[IMAGES:@.+]] = internal unnamed_addr constant [1 x [[DEVTY]]] [{{.+}} { i8* [[DEVBEGIN]], i8* [[DEVEND]], [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }], comdat($[[REGFN]]) // CHECK: [[DESC:@.+]] = internal constant [[DSCTY]] { i32 1, [[DEVTY]]* getelementptr inbounds ([1 x [[DEVTY]]], [1 x [[DEVTY]]]* [[IMAGES]], i32 0, i32 0), [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }, comdat($[[REGFN]]) diff --git a/test/OpenMP/target_parallel_for_codegen_registration.cpp b/test/OpenMP/target_parallel_for_codegen_registration.cpp index 9a69ea994efc..a23b1ace97fa 100644 --- a/test/OpenMP/target_parallel_for_codegen_registration.cpp +++ b/test/OpenMP/target_parallel_for_codegen_registration.cpp @@ -174,8 +174,8 @@ // CHECK: [[ENTBEGIN:@.+]] = external constant [[ENTTY]] // CHECK: [[ENTEND:@.+]] = external constant [[ENTTY]] -// CHECK: [[DEVBEGIN:@.+]] = external constant i8 -// CHECK: [[DEVEND:@.+]] = external constant i8 +// CHECK: [[DEVBEGIN:@.+]] = extern_weak constant i8 +// CHECK: [[DEVEND:@.+]] = extern_weak constant i8 // CHECK: [[IMAGES:@.+]] = internal unnamed_addr constant [1 x [[DEVTY]]] [{{.+}} { i8* [[DEVBEGIN]], i8* [[DEVEND]], [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }], comdat($[[REGFN]]) // CHECK: [[DESC:@.+]] = internal constant [[DSCTY]] { i32 1, [[DEVTY]]* getelementptr inbounds ([1 x [[DEVTY]]], [1 x [[DEVTY]]]* [[IMAGES]], i32 0, i32 0), [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }, comdat($[[REGFN]]) diff --git a/test/OpenMP/target_parallel_for_depend_codegen.cpp b/test/OpenMP/target_parallel_for_depend_codegen.cpp index c6e71375f18c..85ec945c4f65 100644 --- a/test/OpenMP/target_parallel_for_depend_codegen.cpp +++ b/test/OpenMP/target_parallel_for_depend_codegen.cpp @@ -58,8 +58,8 @@ // Check if offloading descriptor is created. // CHECK: [[ENTBEGIN:@.+]] = external constant [[ENTTY]] // CHECK: [[ENTEND:@.+]] = external constant [[ENTTY]] -// CHECK: [[DEVBEGIN:@.+]] = external constant i8 -// CHECK: [[DEVEND:@.+]] = external constant i8 +// CHECK: [[DEVBEGIN:@.+]] = extern_weak constant i8 +// CHECK: [[DEVEND:@.+]] = extern_weak constant i8 // CHECK: [[IMAGES:@.+]] = internal unnamed_addr constant [1 x [[DEVTY]]] [{{.+}} { i8* [[DEVBEGIN]], i8* [[DEVEND]], [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }], comdat($[[REGFN]]) // CHECK: [[DESC:@.+]] = internal constant [[DSCTY]] { i32 1, [[DEVTY]]* getelementptr inbounds ([1 x [[DEVTY]]], [1 x [[DEVTY]]]* [[IMAGES]], i32 0, i32 0), [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }, comdat($[[REGFN]]) diff --git a/test/OpenMP/target_parallel_for_simd_codegen.cpp b/test/OpenMP/target_parallel_for_simd_codegen.cpp index 012b2f86be48..75bf2d17afd6 100644 --- a/test/OpenMP/target_parallel_for_simd_codegen.cpp +++ b/test/OpenMP/target_parallel_for_simd_codegen.cpp @@ -85,8 +85,8 @@ // Check if offloading descriptor is created. // CHECK: [[ENTBEGIN:@.+]] = external constant [[ENTTY]] // CHECK: [[ENTEND:@.+]] = external constant [[ENTTY]] -// CHECK: [[DEVBEGIN:@.+]] = external constant i8 -// CHECK: [[DEVEND:@.+]] = external constant i8 +// CHECK: [[DEVBEGIN:@.+]] = extern_weak constant i8 +// CHECK: [[DEVEND:@.+]] = extern_weak constant i8 // CHECK: [[IMAGES:@.+]] = internal unnamed_addr constant [1 x [[DEVTY]]] [{{.+}} { i8* [[DEVBEGIN]], i8* [[DEVEND]], [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }], comdat($[[REGFN]]) // CHECK: [[DESC:@.+]] = internal constant [[DSCTY]] { i32 1, [[DEVTY]]* getelementptr inbounds ([1 x [[DEVTY]]], [1 x [[DEVTY]]]* [[IMAGES]], i32 0, i32 0), [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }, comdat($[[REGFN]]) diff --git a/test/OpenMP/target_parallel_for_simd_codegen_registration.cpp b/test/OpenMP/target_parallel_for_simd_codegen_registration.cpp index 5973c8d182f1..82f8cefa2c44 100644 --- a/test/OpenMP/target_parallel_for_simd_codegen_registration.cpp +++ b/test/OpenMP/target_parallel_for_simd_codegen_registration.cpp @@ -174,8 +174,8 @@ // CHECK: [[ENTBEGIN:@.+]] = external constant [[ENTTY]] // CHECK: [[ENTEND:@.+]] = external constant [[ENTTY]] -// CHECK: [[DEVBEGIN:@.+]] = external constant i8 -// CHECK: [[DEVEND:@.+]] = external constant i8 +// CHECK: [[DEVBEGIN:@.+]] = extern_weak constant i8 +// CHECK: [[DEVEND:@.+]] = extern_weak constant i8 // CHECK: [[IMAGES:@.+]] = internal unnamed_addr constant [1 x [[DEVTY]]] [{{.+}} { i8* [[DEVBEGIN]], i8* [[DEVEND]], [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }], comdat($[[REGFN]]) // CHECK: [[DESC:@.+]] = internal constant [[DSCTY]] { i32 1, [[DEVTY]]* getelementptr inbounds ([1 x [[DEVTY]]], [1 x [[DEVTY]]]* [[IMAGES]], i32 0, i32 0), [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }, comdat($[[REGFN]]) diff --git a/test/OpenMP/target_parallel_for_simd_depend_codegen.cpp b/test/OpenMP/target_parallel_for_simd_depend_codegen.cpp index 6fc71a787559..83d752d9abe7 100644 --- a/test/OpenMP/target_parallel_for_simd_depend_codegen.cpp +++ b/test/OpenMP/target_parallel_for_simd_depend_codegen.cpp @@ -58,8 +58,8 @@ // Check if offloading descriptor is created. // CHECK: [[ENTBEGIN:@.+]] = external constant [[ENTTY]] // CHECK: [[ENTEND:@.+]] = external constant [[ENTTY]] -// CHECK: [[DEVBEGIN:@.+]] = external constant i8 -// CHECK: [[DEVEND:@.+]] = external constant i8 +// CHECK: [[DEVBEGIN:@.+]] = extern_weak constant i8 +// CHECK: [[DEVEND:@.+]] = extern_weak constant i8 // CHECK: [[IMAGES:@.+]] = internal unnamed_addr constant [1 x [[DEVTY]]] [{{.+}} { i8* [[DEVBEGIN]], i8* [[DEVEND]], [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }], comdat($[[REGFN]]) // CHECK: [[DESC:@.+]] = internal constant [[DSCTY]] { i32 1, [[DEVTY]]* getelementptr inbounds ([1 x [[DEVTY]]], [1 x [[DEVTY]]]* [[IMAGES]], i32 0, i32 0), [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }, comdat($[[REGFN]]) diff --git a/test/OpenMP/target_parallel_if_codegen.cpp b/test/OpenMP/target_parallel_if_codegen.cpp index aab1a14a5eb5..264017f7c523 100644 --- a/test/OpenMP/target_parallel_if_codegen.cpp +++ b/test/OpenMP/target_parallel_if_codegen.cpp @@ -70,8 +70,8 @@ // Check if offloading descriptor is created. // CHECK: [[ENTBEGIN:@.+]] = external constant [[ENTTY]] // CHECK: [[ENTEND:@.+]] = external constant [[ENTTY]] -// CHECK: [[DEVBEGIN:@.+]] = external constant i8 -// CHECK: [[DEVEND:@.+]] = external constant i8 +// CHECK: [[DEVBEGIN:@.+]] = extern_weak constant i8 +// CHECK: [[DEVEND:@.+]] = extern_weak constant i8 // CHECK: [[IMAGES:@.+]] = internal unnamed_addr constant [1 x [[DEVTY]]] [{{.+}} { i8* [[DEVBEGIN]], i8* [[DEVEND]], [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }], comdat($[[REGFN]]) // CHECK: [[DESC:@.+]] = internal constant [[DSCTY]] { i32 1, [[DEVTY]]* getelementptr inbounds ([1 x [[DEVTY]]], [1 x [[DEVTY]]]* [[IMAGES]], i32 0, i32 0), [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }, comdat($[[REGFN]]) diff --git a/test/OpenMP/target_parallel_num_threads_codegen.cpp b/test/OpenMP/target_parallel_num_threads_codegen.cpp index e6b93113c557..e271811a4911 100644 --- a/test/OpenMP/target_parallel_num_threads_codegen.cpp +++ b/test/OpenMP/target_parallel_num_threads_codegen.cpp @@ -70,8 +70,8 @@ // Check if offloading descriptor is created. // CHECK: [[ENTBEGIN:@.+]] = external constant [[ENTTY]] // CHECK: [[ENTEND:@.+]] = external constant [[ENTTY]] -// CHECK: [[DEVBEGIN:@.+]] = external constant i8 -// CHECK: [[DEVEND:@.+]] = external constant i8 +// CHECK: [[DEVBEGIN:@.+]] = extern_weak constant i8 +// CHECK: [[DEVEND:@.+]] = extern_weak constant i8 // CHECK: [[IMAGES:@.+]] = internal unnamed_addr constant [1 x [[DEVTY]]] [{{.+}} { i8* [[DEVBEGIN]], i8* [[DEVEND]], [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }], comdat($[[REGFN]]) // CHECK: [[DESC:@.+]] = internal constant [[DSCTY]] { i32 1, [[DEVTY]]* getelementptr inbounds ([1 x [[DEVTY]]], [1 x [[DEVTY]]]* [[IMAGES]], i32 0, i32 0), [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }, comdat($[[REGFN]]) diff --git a/test/OpenMP/target_simd_codegen.cpp b/test/OpenMP/target_simd_codegen.cpp index a2ec51c4e22f..81ad4038044c 100644 --- a/test/OpenMP/target_simd_codegen.cpp +++ b/test/OpenMP/target_simd_codegen.cpp @@ -82,8 +82,8 @@ // Check if offloading descriptor is created. // CHECK: [[ENTBEGIN:@.+]] = external constant [[ENTTY]] // CHECK: [[ENTEND:@.+]] = external constant [[ENTTY]] -// CHECK: [[DEVBEGIN:@.+]] = external constant i8 -// CHECK: [[DEVEND:@.+]] = external constant i8 +// CHECK: [[DEVBEGIN:@.+]] = extern_weak constant i8 +// CHECK: [[DEVEND:@.+]] = extern_weak constant i8 // CHECK: [[IMAGES:@.+]] = internal unnamed_addr constant [1 x [[DEVTY]]] [{{.+}} { i8* [[DEVBEGIN]], i8* [[DEVEND]], [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }], comdat($[[REGFN]]) // CHECK: [[DESC:@.+]] = internal constant [[DSCTY]] { i32 1, [[DEVTY]]* getelementptr inbounds ([1 x [[DEVTY]]], [1 x [[DEVTY]]]* [[IMAGES]], i32 0, i32 0), [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }, comdat($[[REGFN]]) diff --git a/test/OpenMP/target_simd_codegen_registration.cpp b/test/OpenMP/target_simd_codegen_registration.cpp index 39e930a5d554..a888b2587405 100644 --- a/test/OpenMP/target_simd_codegen_registration.cpp +++ b/test/OpenMP/target_simd_codegen_registration.cpp @@ -174,8 +174,8 @@ // CHECK: [[ENTBEGIN:@.+]] = external constant [[ENTTY]] // CHECK: [[ENTEND:@.+]] = external constant [[ENTTY]] -// CHECK: [[DEVBEGIN:@.+]] = external constant i8 -// CHECK: [[DEVEND:@.+]] = external constant i8 +// CHECK: [[DEVBEGIN:@.+]] = extern_weak constant i8 +// CHECK: [[DEVEND:@.+]] = extern_weak constant i8 // CHECK: [[IMAGES:@.+]] = internal unnamed_addr constant [1 x [[DEVTY]]] [{{.+}} { i8* [[DEVBEGIN]], i8* [[DEVEND]], [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }], comdat($[[REGFN]]) // CHECK: [[DESC:@.+]] = internal constant [[DSCTY]] { i32 1, [[DEVTY]]* getelementptr inbounds ([1 x [[DEVTY]]], [1 x [[DEVTY]]]* [[IMAGES]], i32 0, i32 0), [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }, comdat($[[REGFN]]) diff --git a/test/OpenMP/target_simd_depend_codegen.cpp b/test/OpenMP/target_simd_depend_codegen.cpp index ed34dd12dfb6..e87b4fc8c30f 100644 --- a/test/OpenMP/target_simd_depend_codegen.cpp +++ b/test/OpenMP/target_simd_depend_codegen.cpp @@ -58,8 +58,8 @@ // Check if offloading descriptor is created. // CHECK: [[ENTBEGIN:@.+]] = external constant [[ENTTY]] // CHECK: [[ENTEND:@.+]] = external constant [[ENTTY]] -// CHECK: [[DEVBEGIN:@.+]] = external constant i8 -// CHECK: [[DEVEND:@.+]] = external constant i8 +// CHECK: [[DEVBEGIN:@.+]] = extern_weak constant i8 +// CHECK: [[DEVEND:@.+]] = extern_weak constant i8 // CHECK: [[IMAGES:@.+]] = internal unnamed_addr constant [1 x [[DEVTY]]] [{{.+}} { i8* [[DEVBEGIN]], i8* [[DEVEND]], [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }], comdat($[[REGFN]]) // CHECK: [[DESC:@.+]] = internal constant [[DSCTY]] { i32 1, [[DEVTY]]* getelementptr inbounds ([1 x [[DEVTY]]], [1 x [[DEVTY]]]* [[IMAGES]], i32 0, i32 0), [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }, comdat($[[REGFN]]) diff --git a/test/OpenMP/target_teams_codegen.cpp b/test/OpenMP/target_teams_codegen.cpp index 5c18a0cba3bb..43391fc641a6 100644 --- a/test/OpenMP/target_teams_codegen.cpp +++ b/test/OpenMP/target_teams_codegen.cpp @@ -87,8 +87,8 @@ // Check if offloading descriptor is created. // CHECK: [[ENTBEGIN:@.+]] = external constant [[ENTTY]] // CHECK: [[ENTEND:@.+]] = external constant [[ENTTY]] -// CHECK: [[DEVBEGIN:@.+]] = external constant i8 -// CHECK: [[DEVEND:@.+]] = external constant i8 +// CHECK: [[DEVBEGIN:@.+]] = extern_weak constant i8 +// CHECK: [[DEVEND:@.+]] = extern_weak constant i8 // CHECK: [[IMAGES:@.+]] = internal unnamed_addr constant [1 x [[DEVTY]]] [{{.+}} { i8* [[DEVBEGIN]], i8* [[DEVEND]], [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }], comdat($[[REGFN]]) // CHECK: [[DESC:@.+]] = internal constant [[DSCTY]] { i32 1, [[DEVTY]]* getelementptr inbounds ([1 x [[DEVTY]]], [1 x [[DEVTY]]]* [[IMAGES]], i32 0, i32 0), [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }, comdat($[[REGFN]]) diff --git a/test/OpenMP/target_teams_codegen_registration.cpp b/test/OpenMP/target_teams_codegen_registration.cpp index e62be6813460..a18e180c5c81 100644 --- a/test/OpenMP/target_teams_codegen_registration.cpp +++ b/test/OpenMP/target_teams_codegen_registration.cpp @@ -174,8 +174,8 @@ // CHECK: [[ENTBEGIN:@.+]] = external constant [[ENTTY]] // CHECK: [[ENTEND:@.+]] = external constant [[ENTTY]] -// CHECK: [[DEVBEGIN:@.+]] = external constant i8 -// CHECK: [[DEVEND:@.+]] = external constant i8 +// CHECK: [[DEVBEGIN:@.+]] = extern_weak constant i8 +// CHECK: [[DEVEND:@.+]] = extern_weak constant i8 // CHECK: [[IMAGES:@.+]] = internal unnamed_addr constant [1 x [[DEVTY]]] [{{.+}} { i8* [[DEVBEGIN]], i8* [[DEVEND]], [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }], comdat($[[REGFN]]) // CHECK: [[DESC:@.+]] = internal constant [[DSCTY]] { i32 1, [[DEVTY]]* getelementptr inbounds ([1 x [[DEVTY]]], [1 x [[DEVTY]]]* [[IMAGES]], i32 0, i32 0), [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }, comdat($[[REGFN]]) diff --git a/test/OpenMP/target_teams_depend_codegen.cpp b/test/OpenMP/target_teams_depend_codegen.cpp index a5fbc5afc163..9f9c7656eafc 100644 --- a/test/OpenMP/target_teams_depend_codegen.cpp +++ b/test/OpenMP/target_teams_depend_codegen.cpp @@ -58,8 +58,8 @@ // Check if offloading descriptor is created. // CHECK: [[ENTBEGIN:@.+]] = external constant [[ENTTY]] // CHECK: [[ENTEND:@.+]] = external constant [[ENTTY]] -// CHECK: [[DEVBEGIN:@.+]] = external constant i8 -// CHECK: [[DEVEND:@.+]] = external constant i8 +// CHECK: [[DEVBEGIN:@.+]] = extern_weak constant i8 +// CHECK: [[DEVEND:@.+]] = extern_weak constant i8 // CHECK: [[IMAGES:@.+]] = internal unnamed_addr constant [1 x [[DEVTY]]] [{{.+}} { i8* [[DEVBEGIN]], i8* [[DEVEND]], [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }], comdat($[[REGFN]]) // CHECK: [[DESC:@.+]] = internal constant [[DSCTY]] { i32 1, [[DEVTY]]* getelementptr inbounds ([1 x [[DEVTY]]], [1 x [[DEVTY]]]* [[IMAGES]], i32 0, i32 0), [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }, comdat($[[REGFN]]) diff --git a/test/OpenMP/target_teams_distribute_codegen.cpp b/test/OpenMP/target_teams_distribute_codegen.cpp index f9500a73ef79..aa1bc016da0d 100644 --- a/test/OpenMP/target_teams_distribute_codegen.cpp +++ b/test/OpenMP/target_teams_distribute_codegen.cpp @@ -88,8 +88,8 @@ // Check if offloading descriptor is created. // CHECK: [[ENTBEGIN:@.+]] = external constant [[ENTTY]] // CHECK: [[ENTEND:@.+]] = external constant [[ENTTY]] -// CHECK: [[DEVBEGIN:@.+]] = external constant i8 -// CHECK: [[DEVEND:@.+]] = external constant i8 +// CHECK: [[DEVBEGIN:@.+]] = extern_weak constant i8 +// CHECK: [[DEVEND:@.+]] = extern_weak constant i8 // CHECK: [[IMAGES:@.+]] = internal unnamed_addr constant [1 x [[DEVTY]]] [{{.+}} { i8* [[DEVBEGIN]], i8* [[DEVEND]], [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }], comdat($[[REGFN]]) // CHECK: [[DESC:@.+]] = internal constant [[DSCTY]] { i32 1, [[DEVTY]]* getelementptr inbounds ([1 x [[DEVTY]]], [1 x [[DEVTY]]]* [[IMAGES]], i32 0, i32 0), [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }, comdat($[[REGFN]]) diff --git a/test/OpenMP/target_teams_distribute_codegen_registration.cpp b/test/OpenMP/target_teams_distribute_codegen_registration.cpp index e45e040b1fcd..3213a9706f72 100644 --- a/test/OpenMP/target_teams_distribute_codegen_registration.cpp +++ b/test/OpenMP/target_teams_distribute_codegen_registration.cpp @@ -174,8 +174,8 @@ // CHECK: [[ENTBEGIN:@.+]] = external constant [[ENTTY]] // CHECK: [[ENTEND:@.+]] = external constant [[ENTTY]] -// CHECK: [[DEVBEGIN:@.+]] = external constant i8 -// CHECK: [[DEVEND:@.+]] = external constant i8 +// CHECK: [[DEVBEGIN:@.+]] = extern_weak constant i8 +// CHECK: [[DEVEND:@.+]] = extern_weak constant i8 // CHECK: [[IMAGES:@.+]] = internal unnamed_addr constant [1 x [[DEVTY]]] [{{.+}} { i8* [[DEVBEGIN]], i8* [[DEVEND]], [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }], comdat($[[REGFN]]) // CHECK: [[DESC:@.+]] = internal constant [[DSCTY]] { i32 1, [[DEVTY]]* getelementptr inbounds ([1 x [[DEVTY]]], [1 x [[DEVTY]]]* [[IMAGES]], i32 0, i32 0), [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }, comdat($[[REGFN]]) diff --git a/test/OpenMP/target_teams_distribute_depend_codegen.cpp b/test/OpenMP/target_teams_distribute_depend_codegen.cpp index f066574e8768..99b7f2c2e9c3 100644 --- a/test/OpenMP/target_teams_distribute_depend_codegen.cpp +++ b/test/OpenMP/target_teams_distribute_depend_codegen.cpp @@ -58,8 +58,8 @@ // Check if offloading descriptor is created. // CHECK: [[ENTBEGIN:@.+]] = external constant [[ENTTY]] // CHECK: [[ENTEND:@.+]] = external constant [[ENTTY]] -// CHECK: [[DEVBEGIN:@.+]] = external constant i8 -// CHECK: [[DEVEND:@.+]] = external constant i8 +// CHECK: [[DEVBEGIN:@.+]] = extern_weak constant i8 +// CHECK: [[DEVEND:@.+]] = extern_weak constant i8 // CHECK: [[IMAGES:@.+]] = internal unnamed_addr constant [1 x [[DEVTY]]] [{{.+}} { i8* [[DEVBEGIN]], i8* [[DEVEND]], [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }], comdat($[[REGFN]]) // CHECK: [[DESC:@.+]] = internal constant [[DSCTY]] { i32 1, [[DEVTY]]* getelementptr inbounds ([1 x [[DEVTY]]], [1 x [[DEVTY]]]* [[IMAGES]], i32 0, i32 0), [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }, comdat($[[REGFN]]) diff --git a/test/OpenMP/target_teams_distribute_parallel_for_depend_codegen.cpp b/test/OpenMP/target_teams_distribute_parallel_for_depend_codegen.cpp index 5cfa2cca51b5..f573c0454774 100644 --- a/test/OpenMP/target_teams_distribute_parallel_for_depend_codegen.cpp +++ b/test/OpenMP/target_teams_distribute_parallel_for_depend_codegen.cpp @@ -58,8 +58,8 @@ // Check if offloading descriptor is created. // CHECK: [[ENTBEGIN:@.+]] = external constant [[ENTTY]] // CHECK: [[ENTEND:@.+]] = external constant [[ENTTY]] -// CHECK: [[DEVBEGIN:@.+]] = external constant i8 -// CHECK: [[DEVEND:@.+]] = external constant i8 +// CHECK: [[DEVBEGIN:@.+]] = extern_weak constant i8 +// CHECK: [[DEVEND:@.+]] = extern_weak constant i8 // CHECK: [[IMAGES:@.+]] = internal unnamed_addr constant [1 x [[DEVTY]]] [{{.+}} { i8* [[DEVBEGIN]], i8* [[DEVEND]], [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }], comdat($[[REGFN]]) // CHECK: [[DESC:@.+]] = internal constant [[DSCTY]] { i32 1, [[DEVTY]]* getelementptr inbounds ([1 x [[DEVTY]]], [1 x [[DEVTY]]]* [[IMAGES]], i32 0, i32 0), [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }, comdat($[[REGFN]]) diff --git a/test/OpenMP/target_teams_distribute_parallel_for_simd_codegen_registration.cpp b/test/OpenMP/target_teams_distribute_parallel_for_simd_codegen_registration.cpp index 76a7b4d0bd86..0222bc8d908a 100644 --- a/test/OpenMP/target_teams_distribute_parallel_for_simd_codegen_registration.cpp +++ b/test/OpenMP/target_teams_distribute_parallel_for_simd_codegen_registration.cpp @@ -174,8 +174,8 @@ // CHECK: [[ENTBEGIN:@.+]] = external constant [[ENTTY]] // CHECK: [[ENTEND:@.+]] = external constant [[ENTTY]] -// CHECK: [[DEVBEGIN:@.+]] = external constant i8 -// CHECK: [[DEVEND:@.+]] = external constant i8 +// CHECK: [[DEVBEGIN:@.+]] = extern_weak constant i8 +// CHECK: [[DEVEND:@.+]] = extern_weak constant i8 // CHECK: [[IMAGES:@.+]] = internal unnamed_addr constant [1 x [[DEVTY]]] [{{.+}} { i8* [[DEVBEGIN]], i8* [[DEVEND]], [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }], comdat($[[REGFN]]) // CHECK: [[DESC:@.+]] = internal constant [[DSCTY]] { i32 1, [[DEVTY]]* getelementptr inbounds ([1 x [[DEVTY]]], [1 x [[DEVTY]]]* [[IMAGES]], i32 0, i32 0), [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }, comdat($[[REGFN]]) diff --git a/test/OpenMP/target_teams_distribute_parallel_for_simd_depend_codegen.cpp b/test/OpenMP/target_teams_distribute_parallel_for_simd_depend_codegen.cpp index 2a10ae872375..1258e685ea73 100644 --- a/test/OpenMP/target_teams_distribute_parallel_for_simd_depend_codegen.cpp +++ b/test/OpenMP/target_teams_distribute_parallel_for_simd_depend_codegen.cpp @@ -58,8 +58,8 @@ // Check if offloading descriptor is created. // CHECK: [[ENTBEGIN:@.+]] = external constant [[ENTTY]] // CHECK: [[ENTEND:@.+]] = external constant [[ENTTY]] -// CHECK: [[DEVBEGIN:@.+]] = external constant i8 -// CHECK: [[DEVEND:@.+]] = external constant i8 +// CHECK: [[DEVBEGIN:@.+]] = extern_weak constant i8 +// CHECK: [[DEVEND:@.+]] = extern_weak constant i8 // CHECK: [[IMAGES:@.+]] = internal unnamed_addr constant [1 x [[DEVTY]]] [{{.+}} { i8* [[DEVBEGIN]], i8* [[DEVEND]], [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }], comdat($[[REGFN]]) // CHECK: [[DESC:@.+]] = internal constant [[DSCTY]] { i32 1, [[DEVTY]]* getelementptr inbounds ([1 x [[DEVTY]]], [1 x [[DEVTY]]]* [[IMAGES]], i32 0, i32 0), [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }, comdat($[[REGFN]]) diff --git a/test/OpenMP/target_teams_distribute_simd_codegen.cpp b/test/OpenMP/target_teams_distribute_simd_codegen.cpp index c400e0867154..425afd262256 100644 --- a/test/OpenMP/target_teams_distribute_simd_codegen.cpp +++ b/test/OpenMP/target_teams_distribute_simd_codegen.cpp @@ -88,8 +88,8 @@ // Check if offloading descriptor is created. // CHECK: [[ENTBEGIN:@.+]] = external constant [[ENTTY]] // CHECK: [[ENTEND:@.+]] = external constant [[ENTTY]] -// CHECK: [[DEVBEGIN:@.+]] = external constant i8 -// CHECK: [[DEVEND:@.+]] = external constant i8 +// CHECK: [[DEVBEGIN:@.+]] = extern_weak constant i8 +// CHECK: [[DEVEND:@.+]] = extern_weak constant i8 // CHECK: [[IMAGES:@.+]] = internal unnamed_addr constant [1 x [[DEVTY]]] [{{.+}} { i8* [[DEVBEGIN]], i8* [[DEVEND]], [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }], comdat($[[REGFN]]) // CHECK: [[DESC:@.+]] = internal constant [[DSCTY]] { i32 1, [[DEVTY]]* getelementptr inbounds ([1 x [[DEVTY]]], [1 x [[DEVTY]]]* [[IMAGES]], i32 0, i32 0), [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }, comdat($[[REGFN]]) diff --git a/test/OpenMP/target_teams_distribute_simd_codegen_registration.cpp b/test/OpenMP/target_teams_distribute_simd_codegen_registration.cpp index 5020bcc87aaf..606919740da2 100644 --- a/test/OpenMP/target_teams_distribute_simd_codegen_registration.cpp +++ b/test/OpenMP/target_teams_distribute_simd_codegen_registration.cpp @@ -174,8 +174,8 @@ // CHECK: [[ENTBEGIN:@.+]] = external constant [[ENTTY]] // CHECK: [[ENTEND:@.+]] = external constant [[ENTTY]] -// CHECK: [[DEVBEGIN:@.+]] = external constant i8 -// CHECK: [[DEVEND:@.+]] = external constant i8 +// CHECK: [[DEVBEGIN:@.+]] = extern_weak constant i8 +// CHECK: [[DEVEND:@.+]] = extern_weak constant i8 // CHECK: [[IMAGES:@.+]] = internal unnamed_addr constant [1 x [[DEVTY]]] [{{.+}} { i8* [[DEVBEGIN]], i8* [[DEVEND]], [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }], comdat($[[REGFN]]) // CHECK: [[DESC:@.+]] = internal constant [[DSCTY]] { i32 1, [[DEVTY]]* getelementptr inbounds ([1 x [[DEVTY]]], [1 x [[DEVTY]]]* [[IMAGES]], i32 0, i32 0), [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }, comdat($[[REGFN]]) diff --git a/test/OpenMP/target_teams_distribute_simd_depend_codegen.cpp b/test/OpenMP/target_teams_distribute_simd_depend_codegen.cpp index 0c1c13e1e908..1eb732322ce6 100644 --- a/test/OpenMP/target_teams_distribute_simd_depend_codegen.cpp +++ b/test/OpenMP/target_teams_distribute_simd_depend_codegen.cpp @@ -58,8 +58,8 @@ // Check if offloading descriptor is created. // CHECK: [[ENTBEGIN:@.+]] = external constant [[ENTTY]] // CHECK: [[ENTEND:@.+]] = external constant [[ENTTY]] -// CHECK: [[DEVBEGIN:@.+]] = external constant i8 -// CHECK: [[DEVEND:@.+]] = external constant i8 +// CHECK: [[DEVBEGIN:@.+]] = extern_weak constant i8 +// CHECK: [[DEVEND:@.+]] = extern_weak constant i8 // CHECK: [[IMAGES:@.+]] = internal unnamed_addr constant [1 x [[DEVTY]]] [{{.+}} { i8* [[DEVBEGIN]], i8* [[DEVEND]], [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }], comdat($[[REGFN]]) // CHECK: [[DESC:@.+]] = internal constant [[DSCTY]] { i32 1, [[DEVTY]]* getelementptr inbounds ([1 x [[DEVTY]]], [1 x [[DEVTY]]]* [[IMAGES]], i32 0, i32 0), [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }, comdat($[[REGFN]]) diff --git a/test/OpenMP/target_teams_num_teams_codegen.cpp b/test/OpenMP/target_teams_num_teams_codegen.cpp index 0961c03e30f0..6edde0042edd 100644 --- a/test/OpenMP/target_teams_num_teams_codegen.cpp +++ b/test/OpenMP/target_teams_num_teams_codegen.cpp @@ -70,8 +70,8 @@ // Check if offloading descriptor is created. // CHECK: [[ENTBEGIN:@.+]] = external constant [[ENTTY]] // CHECK: [[ENTEND:@.+]] = external constant [[ENTTY]] -// CHECK: [[DEVBEGIN:@.+]] = external constant i8 -// CHECK: [[DEVEND:@.+]] = external constant i8 +// CHECK: [[DEVBEGIN:@.+]] = extern_weak constant i8 +// CHECK: [[DEVEND:@.+]] = extern_weak constant i8 // CHECK: [[IMAGES:@.+]] = internal unnamed_addr constant [1 x [[DEVTY]]] [{{.+}} { i8* [[DEVBEGIN]], i8* [[DEVEND]], [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }], comdat($[[REGFN]]) // CHECK: [[DESC:@.+]] = internal constant [[DSCTY]] { i32 1, [[DEVTY]]* getelementptr inbounds ([1 x [[DEVTY]]], [1 x [[DEVTY]]]* [[IMAGES]], i32 0, i32 0), [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }, comdat($[[REGFN]]) diff --git a/test/OpenMP/target_teams_thread_limit_codegen.cpp b/test/OpenMP/target_teams_thread_limit_codegen.cpp index 21c9c5a68e70..3baa81cc9ecb 100644 --- a/test/OpenMP/target_teams_thread_limit_codegen.cpp +++ b/test/OpenMP/target_teams_thread_limit_codegen.cpp @@ -70,8 +70,8 @@ // Check if offloading descriptor is created. // CHECK: [[ENTBEGIN:@.+]] = external constant [[ENTTY]] // CHECK: [[ENTEND:@.+]] = external constant [[ENTTY]] -// CHECK: [[DEVBEGIN:@.+]] = external constant i8 -// CHECK: [[DEVEND:@.+]] = external constant i8 +// CHECK: [[DEVBEGIN:@.+]] = extern_weak constant i8 +// CHECK: [[DEVEND:@.+]] = extern_weak constant i8 // CHECK: [[IMAGES:@.+]] = internal unnamed_addr constant [1 x [[DEVTY]]] [{{.+}} { i8* [[DEVBEGIN]], i8* [[DEVEND]], [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }], comdat($[[REGFN]]) // CHECK: [[DESC:@.+]] = internal constant [[DSCTY]] { i32 1, [[DEVTY]]* getelementptr inbounds ([1 x [[DEVTY]]], [1 x [[DEVTY]]]* [[IMAGES]], i32 0, i32 0), [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }, comdat($[[REGFN]]) diff --git a/test/PCH/coroutines.cpp b/test/PCH/coroutines.cpp index 46a2872420bf..f907d1213731 100644 --- a/test/PCH/coroutines.cpp +++ b/test/PCH/coroutines.cpp @@ -66,6 +66,14 @@ int f2(T x) { // checks coawait_expr and coroutine_body_stmt co_return x; // checks coreturn_stmt with expr } +struct S {}; +S operator co_await(S) { return S(); } + +template <typename T> +int f3(T x) { + co_await x; // checks dependent_coawait with overloaded co_await operator +} + #else // expected-no-diagnostics diff --git a/test/PCH/cxx-templates.cpp b/test/PCH/cxx-templates.cpp index e241701f50df..a7f7b1981f56 100644 --- a/test/PCH/cxx-templates.cpp +++ b/test/PCH/cxx-templates.cpp @@ -116,3 +116,19 @@ namespace MemberSpecializationLocation { #endif int k = A<int>::n; } + +// https://bugs.llvm.org/show_bug.cgi?id=34728 +namespace PR34728 { +int test() { + // Verify with several TemplateParmDecl kinds, using PCH (incl. modules). + int z1 = func1(/*ignored*/2.718); + int z2 = func2(/*ignored*/3.142); + int tmp3 = 30; + Container<int> c = func3(tmp3); + int z3 = c.item; + + // Return value is meaningless. Just "use" all these values to avoid + // warning about unused vars / values. + return z1 + z2 + z3; +} +} // end namespace PR34728 diff --git a/test/PCH/cxx-templates.h b/test/PCH/cxx-templates.h index 68b252e7974e..e812aa68fb81 100644 --- a/test/PCH/cxx-templates.h +++ b/test/PCH/cxx-templates.h @@ -361,3 +361,38 @@ namespace rdar15468709c { namespace MemberSpecializationLocation { template<typename T> struct A { static int n; }; } + +// https://bugs.llvm.org/show_bug.cgi?id=34728 +namespace PR34728 { + +// case 1: defaulted `NonTypeTemplateParmDecl`, non-defaulted 2nd tpl param +template <int foo = 10, class T> +int func1(T const &); + +template <int foo, class T> +int func1(T const &) { + return foo; +} + +// case 2: defaulted `TemplateTypeParmDecl`, non-defaulted 2nd tpl param +template <class A = int, class B> +A func2(B const &); + +template <class A, class B> +A func2(B const &) { + return A(20.0f); +} + +// case 3: defaulted `TemplateTemplateParmDecl`, non-defaulted 2nd tpl param +template <class T> +struct Container { T const &item; }; + +template <template <class> class C = Container, class D> +C<D> func3(D const &); + +template <template <class> class C, class D> +C<D> func3(D const &d) { + return Container<D>{d}; +} + +} // end namespace PR34728 diff --git a/test/Parser/cxx1z-fold-expressions.cpp b/test/Parser/cxx1z-fold-expressions.cpp index 342f11555fa7..93ee6f20ffc6 100644 --- a/test/Parser/cxx1z-fold-expressions.cpp +++ b/test/Parser/cxx1z-fold-expressions.cpp @@ -60,3 +60,29 @@ template <int... N> constexpr int nestedFoldOperator() { } static_assert(nestedFoldOperator<3, 1>() == 1); + +// A fold-expression is a primary-expression. +template <typename T, typename... Ts> +constexpr auto castSum(Ts... Args) { + return (T)(Args + ...).Value; // expected-error{{member reference base type 'int' is not a structure or union}} +} + +template <typename... Ts> +constexpr auto simpleSum(Ts... Args) { + return (... + Args).Value; // expected-error{{member reference base type 'int' is not a structure or union}} +} + +void prim() { + castSum<int>(1, 2); + // expected-note@-1{{in instantiation of function template specialization}} + simpleSum(1, 2); + // expected-note@-1{{in instantiation of function template specialization}} + + struct Number { + int Value; + constexpr Number operator+(Number Rhs) const { return {Rhs.Value + Value}; } + }; + + static_assert(castSum<long>(Number{1}, Number{2}) == 3); + static_assert(simpleSum(Number{1}, Number{2}) == 3); +} diff --git a/test/SemaCUDA/device-var-init.cu b/test/SemaCUDA/device-var-init.cu index 46cb90da2ecf..dd5d19a6a2e8 100644 --- a/test/SemaCUDA/device-var-init.cu +++ b/test/SemaCUDA/device-var-init.cu @@ -207,17 +207,22 @@ __device__ void df_sema() { // expected-error@-1 {{initialization is not supported for __shared__ variables.}} static __device__ int ds; - // expected-error@-1 {{within a __device__ function, only __shared__ variables may be marked 'static'}} + // expected-error@-1 {{within a __device__ function, only __shared__ variables or const variables without device memory qualifier may be marked 'static'}} static __constant__ int dc; - // expected-error@-1 {{within a __device__ function, only __shared__ variables may be marked 'static'}} + // expected-error@-1 {{within a __device__ function, only __shared__ variables or const variables without device memory qualifier may be marked 'static'}} static int v; - // expected-error@-1 {{within a __device__ function, only __shared__ variables may be marked 'static'}} + // expected-error@-1 {{within a __device__ function, only __shared__ variables or const variables without device memory qualifier may be marked 'static'}} + static const int cv = 1; + static const __device__ int cds = 1; + // expected-error@-1 {{within a __device__ function, only __shared__ variables or const variables without device memory qualifier may be marked 'static'}} + static const __constant__ int cdc = 1; + // expected-error@-1 {{within a __device__ function, only __shared__ variables or const variables without device memory qualifier may be marked 'static'}} } __host__ __device__ void hd_sema() { static int x = 42; #ifdef __CUDA_ARCH__ - // expected-error@-2 {{within a __host__ __device__ function, only __shared__ variables may be marked 'static'}} + // expected-error@-2 {{within a __host__ __device__ function, only __shared__ variables or const variables without device memory qualifier may be marked 'static'}} #endif } diff --git a/test/SemaCXX/attr-lifetimebound.cpp b/test/SemaCXX/attr-lifetimebound.cpp new file mode 100644 index 000000000000..90124c323d02 --- /dev/null +++ b/test/SemaCXX/attr-lifetimebound.cpp @@ -0,0 +1,115 @@ +// RUN: %clang_cc1 -std=c++2a -verify %s + +namespace usage_invalid { + // FIXME: Should we diagnose a void return type? + void voidreturn(int ¶m [[clang::lifetimebound]]); + + int *not_class_member() [[clang::lifetimebound]]; // expected-error {{non-member function has no implicit object parameter}} + struct A { + A() [[clang::lifetimebound]]; // expected-error {{cannot be applied to a constructor}} + ~A() [[clang::lifetimebound]]; // expected-error {{cannot be applied to a destructor}} + static int *static_class_member() [[clang::lifetimebound]]; // expected-error {{static member function has no implicit object parameter}} + int not_function [[clang::lifetimebound]]; // expected-error {{only applies to parameters and implicit object parameters}} + int [[clang::lifetimebound]] also_not_function; // expected-error {{cannot be applied to types}} + }; + int *attr_with_param(int ¶m [[clang::lifetimebound(42)]]); // expected-error {{takes no arguments}} +} + +namespace usage_ok { + struct IntRef { int *target; }; + + int &refparam(int ¶m [[clang::lifetimebound]]); + int &classparam(IntRef param [[clang::lifetimebound]]); + + // Do not diagnose non-void return types; they can still be lifetime-bound. + long long ptrintcast(int ¶m [[clang::lifetimebound]]) { + return (long long)¶m; + } + // Likewise. + int &intptrcast(long long param [[clang::lifetimebound]]) { + return *(int*)param; + } + + struct A { + A(); + A(int); + int *class_member() [[clang::lifetimebound]]; + operator int*() [[clang::lifetimebound]]; + }; + + int *p = A().class_member(); // expected-warning {{temporary whose address is used as value of local variable 'p' will be destroyed at the end of the full-expression}} + int *q = A(); // expected-warning {{temporary whose address is used as value of local variable 'q' will be destroyed at the end of the full-expression}} + int *r = A(1); // expected-warning {{temporary whose address is used as value of local variable 'r' will be destroyed at the end of the full-expression}} +} + +# 1 "<std>" 1 3 +namespace std { + using size_t = __SIZE_TYPE__; + struct string { + string(); + string(const char*); + + char &operator[](size_t) const [[clang::lifetimebound]]; + }; + string operator""s(const char *, size_t); + + struct string_view { + string_view(); + string_view(const char *p [[clang::lifetimebound]]); + string_view(const string &s [[clang::lifetimebound]]); + }; + string_view operator""sv(const char *, size_t); + + struct vector { + int *data(); + size_t size(); + }; + + template<typename K, typename V> struct map {}; +} +# 68 "attr-lifetimebound.cpp" 2 + +using std::operator""s; +using std::operator""sv; + +namespace p0936r0_examples { + std::string_view s = "foo"s; // expected-warning {{temporary}} + + std::string operator+(std::string_view s1, std::string_view s2); + void f() { + std::string_view sv = "hi"; + std::string_view sv2 = sv + sv; // expected-warning {{temporary}} + sv2 = sv + sv; // FIXME: can we infer that we should warn here too? + } + + struct X { int a, b; }; + const int &f(const X &x [[clang::lifetimebound]]) { return x.a; } + const int &r = f(X()); // expected-warning {{temporary}} + + char &c = std::string("hello my pretty long strong")[0]; // expected-warning {{temporary}} + + struct reversed_range { + int *begin(); + int *end(); + int *p; + std::size_t n; + }; + template <typename R> reversed_range reversed(R &&r [[clang::lifetimebound]]) { + return reversed_range{r.data(), r.size()}; + } + + std::vector make_vector(); + void use_reversed_range() { + // FIXME: Don't expose the name of the internal range variable. + for (auto x : reversed(make_vector())) {} // expected-warning {{temporary implicitly bound to local reference will be destroyed at the end of the full-expression}} + } + + template <typename K, typename V> + const V &findOrDefault(const std::map<K, V> &m [[clang::lifetimebound]], + const K &key, + const V &defvalue [[clang::lifetimebound]]); + + // FIXME: Maybe weaken the wording here: "local reference 'v' could bind to temporary that will be destroyed at end of full-expression"? + std::map<std::string, std::string> m; + const std::string &v = findOrDefault(m, "foo"s, "bar"s); // expected-warning {{temporary bound to local reference 'v'}} +} diff --git a/test/SemaCXX/constexpr-string.cpp b/test/SemaCXX/constexpr-string.cpp index 2ed35fcc2bdd..1145a2081cba 100644 --- a/test/SemaCXX/constexpr-string.cpp +++ b/test/SemaCXX/constexpr-string.cpp @@ -1,6 +1,6 @@ -// RUN: %clang_cc1 %s -std=c++1z -fsyntax-only -verify -pedantic -// RUN: %clang_cc1 %s -std=c++1z -fsyntax-only -verify -pedantic -fno-signed-char -// RUN: %clang_cc1 %s -std=c++1z -fsyntax-only -verify -pedantic -fno-wchar -Dwchar_t=__WCHAR_TYPE__ +// RUN: %clang_cc1 %s -triple x86_64-linux-gnu -std=c++1z -fsyntax-only -verify -pedantic +// RUN: %clang_cc1 %s -triple x86_64-linux-gnu -std=c++1z -fsyntax-only -verify -pedantic -fno-signed-char +// RUN: %clang_cc1 %s -triple x86_64-linux-gnu -std=c++1z -fsyntax-only -verify -pedantic -fno-wchar -Dwchar_t=__WCHAR_TYPE__ # 6 "/usr/include/string.h" 1 3 4 extern "C" { @@ -14,10 +14,13 @@ extern "C" { extern char *strchr(const char *s, int c); extern void *memchr(const void *s, int c, size_t n); + + extern void *memcpy(void *d, const void *s, size_t n); + extern void *memmove(void *d, const void *s, size_t n); } -# 19 "SemaCXX/constexpr-string.cpp" 2 +# 22 "SemaCXX/constexpr-string.cpp" 2 -# 21 "/usr/include/wchar.h" 1 3 4 +# 24 "/usr/include/wchar.h" 1 3 4 extern "C" { extern size_t wcslen(const wchar_t *p); @@ -27,9 +30,12 @@ extern "C" { extern wchar_t *wcschr(const wchar_t *s, wchar_t c); extern wchar_t *wmemchr(const wchar_t *s, wchar_t c, size_t n); + + extern wchar_t *wmemcpy(wchar_t *d, const wchar_t *s, size_t n); + extern wchar_t *wmemmove(wchar_t *d, const wchar_t *s, size_t n); } -# 33 "SemaCXX/constexpr-string.cpp" 2 +# 39 "SemaCXX/constexpr-string.cpp" 2 namespace Strlen { constexpr int n = __builtin_strlen("hello"); // ok static_assert(n == 5); @@ -235,3 +241,133 @@ namespace WcschrEtc { constexpr bool a = !wcschr(L"hello", L'h'); // expected-error {{constant expression}} expected-note {{non-constexpr function 'wcschr' cannot be used in a constant expression}} constexpr bool b = !wmemchr(L"hello", L'h', 3); // expected-error {{constant expression}} expected-note {{non-constexpr function 'wmemchr' cannot be used in a constant expression}} } + +namespace MemcpyEtc { + template<typename T> + constexpr T result(T (&arr)[4]) { + return arr[0] * 1000 + arr[1] * 100 + arr[2] * 10 + arr[3]; + } + + constexpr int test_memcpy(int a, int b, int n) { + int arr[4] = {1, 2, 3, 4}; + __builtin_memcpy(arr + a, arr + b, n); + // expected-note@-1 2{{overlapping memory regions}} + // expected-note@-2 {{size to copy (1) is not a multiple of size of element type 'int'}} + // expected-note@-3 {{source is not a contiguous array of at least 2 elements of type 'int'}} + // expected-note@-4 {{destination is not a contiguous array of at least 3 elements of type 'int'}} + return result(arr); + } + constexpr int test_memmove(int a, int b, int n) { + int arr[4] = {1, 2, 3, 4}; + __builtin_memmove(arr + a, arr + b, n); + // expected-note@-1 {{size to copy (1) is not a multiple of size of element type 'int'}} + // expected-note@-2 {{source is not a contiguous array of at least 2 elements of type 'int'}} + // expected-note@-3 {{destination is not a contiguous array of at least 3 elements of type 'int'}} + return result(arr); + } + constexpr int test_wmemcpy(int a, int b, int n) { + wchar_t arr[4] = {1, 2, 3, 4}; + __builtin_wmemcpy(arr + a, arr + b, n); + // expected-note@-1 2{{overlapping memory regions}} + // expected-note-re@-2 {{source is not a contiguous array of at least 2 elements of type '{{wchar_t|int}}'}} + // expected-note-re@-3 {{destination is not a contiguous array of at least 3 elements of type '{{wchar_t|int}}'}} + return result(arr); + } + constexpr int test_wmemmove(int a, int b, int n) { + wchar_t arr[4] = {1, 2, 3, 4}; + __builtin_wmemmove(arr + a, arr + b, n); + // expected-note-re@-1 {{source is not a contiguous array of at least 2 elements of type '{{wchar_t|int}}'}} + // expected-note-re@-2 {{destination is not a contiguous array of at least 3 elements of type '{{wchar_t|int}}'}} + return result(arr); + } + + static_assert(test_memcpy(1, 2, 4) == 1334); + static_assert(test_memcpy(2, 1, 4) == 1224); + static_assert(test_memcpy(0, 1, 8) == 2334); // expected-error {{constant}} expected-note {{in call}} + static_assert(test_memcpy(1, 0, 8) == 1124); // expected-error {{constant}} expected-note {{in call}} + static_assert(test_memcpy(1, 2, 1) == 1334); // expected-error {{constant}} expected-note {{in call}} + static_assert(test_memcpy(0, 3, 4) == 4234); + static_assert(test_memcpy(0, 3, 8) == 4234); // expected-error {{constant}} expected-note {{in call}} + static_assert(test_memcpy(2, 0, 12) == 4234); // expected-error {{constant}} expected-note {{in call}} + + static_assert(test_memmove(1, 2, 4) == 1334); + static_assert(test_memmove(2, 1, 4) == 1224); + static_assert(test_memmove(0, 1, 8) == 2334); + static_assert(test_memmove(1, 0, 8) == 1124); + static_assert(test_memmove(1, 2, 1) == 1334); // expected-error {{constant}} expected-note {{in call}} + static_assert(test_memmove(0, 3, 4) == 4234); + static_assert(test_memmove(0, 3, 8) == 4234); // expected-error {{constant}} expected-note {{in call}} + static_assert(test_memmove(2, 0, 12) == 4234); // expected-error {{constant}} expected-note {{in call}} + + static_assert(test_wmemcpy(1, 2, 1) == 1334); + static_assert(test_wmemcpy(2, 1, 1) == 1224); + static_assert(test_wmemcpy(0, 1, 2) == 2334); // expected-error {{constant}} expected-note {{in call}} + static_assert(test_wmemcpy(1, 0, 2) == 1124); // expected-error {{constant}} expected-note {{in call}} + static_assert(test_wmemcpy(1, 2, 1) == 1334); + static_assert(test_wmemcpy(0, 3, 1) == 4234); + static_assert(test_wmemcpy(0, 3, 2) == 4234); // expected-error {{constant}} expected-note {{in call}} + static_assert(test_wmemcpy(2, 0, 3) == 4234); // expected-error {{constant}} expected-note {{in call}} + + static_assert(test_wmemmove(1, 2, 1) == 1334); + static_assert(test_wmemmove(2, 1, 1) == 1224); + static_assert(test_wmemmove(0, 1, 2) == 2334); + static_assert(test_wmemmove(1, 0, 2) == 1124); + static_assert(test_wmemmove(1, 2, 1) == 1334); + static_assert(test_wmemmove(0, 3, 1) == 4234); + static_assert(test_wmemmove(0, 3, 2) == 4234); // expected-error {{constant}} expected-note {{in call}} + static_assert(test_wmemmove(2, 0, 3) == 4234); // expected-error {{constant}} expected-note {{in call}} + + // Copying is permitted for any trivially-copyable type. + struct Trivial { char k; short s; constexpr bool ok() { return k == 3 && s == 4; } }; + constexpr bool test_trivial() { + Trivial arr[3] = {{1, 2}, {3, 4}, {5, 6}}; + __builtin_memcpy(arr, arr+1, sizeof(Trivial)); + __builtin_memmove(arr+1, arr, 2 * sizeof(Trivial)); + return arr[0].ok() && arr[1].ok() && arr[2].ok(); + } + static_assert(test_trivial()); + + // But not for a non-trivially-copyable type. + struct NonTrivial { + constexpr NonTrivial() : n(0) {} + constexpr NonTrivial(const NonTrivial &) : n(1) {} + int n; + }; + constexpr bool test_nontrivial_memcpy() { // expected-error {{never produces a constant}} + NonTrivial arr[3] = {}; + __builtin_memcpy(arr, arr + 1, sizeof(NonTrivial)); // expected-note 2{{non-trivially-copyable}} + return true; + } + static_assert(test_nontrivial_memcpy()); // expected-error {{constant}} expected-note {{in call}} + constexpr bool test_nontrivial_memmove() { // expected-error {{never produces a constant}} + NonTrivial arr[3] = {}; + __builtin_memcpy(arr, arr + 1, sizeof(NonTrivial)); // expected-note 2{{non-trivially-copyable}} + return true; + } + static_assert(test_nontrivial_memmove()); // expected-error {{constant}} expected-note {{in call}} + + // Type puns via constant evaluated memcpy are not supported yet. + constexpr float type_pun(const unsigned &n) { + float f = 0.0f; + __builtin_memcpy(&f, &n, 4); // expected-note {{cannot constant evaluate 'memcpy' from object of type 'const unsigned int' to object of type 'float'}} + return f; + } + static_assert(type_pun(0x3f800000) == 1.0f); // expected-error {{constant}} expected-note {{in call}} + + // Make sure we're not confused by derived-to-base conversions. + struct Base { int a; }; + struct Derived : Base { int b; }; + constexpr int test_derived_to_base(int n) { + Derived arr[2] = {1, 2, 3, 4}; + Base *p = &arr[0]; + Base *q = &arr[1]; + __builtin_memcpy(p, q, sizeof(Base) * n); // expected-note {{source is not a contiguous array of at least 2 elements of type 'MemcpyEtc::Base'}} + return arr[0].a * 1000 + arr[0].b * 100 + arr[1].a * 10 + arr[1].b; + } + static_assert(test_derived_to_base(0) == 1234); + static_assert(test_derived_to_base(1) == 3234); + // FIXME: We could consider making this work by stripping elements off both + // designators until we have a long enough matching size, if both designators + // point to the start of their respective final elements. + static_assert(test_derived_to_base(2) == 3434); // expected-error {{constant}} expected-note {{in call}} +} diff --git a/test/SemaCXX/cxx1z-class-template-argument-deduction.cpp b/test/SemaCXX/cxx1z-class-template-argument-deduction.cpp index f72cb886d81a..cbf7c2eee51c 100644 --- a/test/SemaCXX/cxx1z-class-template-argument-deduction.cpp +++ b/test/SemaCXX/cxx1z-class-template-argument-deduction.cpp @@ -373,6 +373,35 @@ void bar(D<int>& d) { } } +namespace rdar41330135 { +template <int> struct A {}; +template <class T> +struct S { + template <class U> + S(T a, U t, A<sizeof(t)>); +}; +template <class T> struct D { + D(T t, A<sizeof(t)>); +}; +int f() { + S s(0, 0, A<sizeof(int)>()); + D d(0, A<sizeof(int)>()); +} + +namespace test_dupls { +template<unsigned long> struct X {}; +template<typename T> struct A { + A(T t, X<sizeof(t)>); +}; +A a(0, {}); +template<typename U> struct B { + B(U u, X<sizeof(u)>); +}; +B b(0, {}); +} + +} + #else // expected-no-diagnostics diff --git a/test/SemaCXX/warn-dangling-local.cpp b/test/SemaCXX/warn-dangling-local.cpp index 19a722f84d16..5c1d56972945 100644 --- a/test/SemaCXX/warn-dangling-local.cpp +++ b/test/SemaCXX/warn-dangling-local.cpp @@ -18,3 +18,9 @@ void f() { // points to, which doesn't live long enough. int *const &s = (int *const &)T{1, 2, 3}; // expected-warning {{temporary bound to local reference 's' will be destroyed at the end of the full-expression}} } + +// PR38355 +void g() { + const int a[] = {a[0]}; + const int b[] = {a[0]}; +} diff --git a/test/SemaObjCXX/class-templ-error-null-init.mm b/test/SemaObjCXX/class-templ-error-null-init.mm new file mode 100644 index 000000000000..b621a3ab24de --- /dev/null +++ b/test/SemaObjCXX/class-templ-error-null-init.mm @@ -0,0 +1,7 @@ +// RUN: %clang_cc1 -fsyntax-only -std=c++17 -verify %s +// expected-no-diagnostics +template <typename a, int* = nullptr> +struct e { + e(a) {} +}; +e c(0); diff --git a/test/SemaObjCXX/noescape.mm b/test/SemaObjCXX/noescape.mm index 6c5d9897aaf0..9432a3a48a0b 100644 --- a/test/SemaObjCXX/noescape.mm +++ b/test/SemaObjCXX/noescape.mm @@ -88,3 +88,42 @@ void test0() { S5<&noescapeFunc2> ne1; } + +@protocol NoescapeProt +-(void) m0:(int*)__attribute__((noescape)) p; // expected-note 2 {{parameter of overridden method is annotated with __attribute__((noescape))}} ++(void) m1:(int*)__attribute__((noescape)) p; +-(void) m1:(int*) p; +@end + +__attribute__((objc_root_class)) +@interface C3 +-(void) m0:(int*) p; ++(void) m1:(int*)__attribute__((noescape)) p; +-(void) m1:(int*) p; +@end + +@interface C3 () <NoescapeProt> // expected-note {{class extension conforms to protocol 'NoescapeProt' which defines method 'm0:'}} +@end + +@implementation C3 +-(void) m0:(int*) p { // expected-warning {{parameter of overriding method should be annotated with __attribute__((noescape))}} +} ++(void) m1:(int*)__attribute__((noescape)) p { +} +-(void) m1:(int*) p { +} +@end + +__attribute__((objc_root_class)) +@interface C4 <NoescapeProt> +-(void) m0:(int*) p; // expected-warning {{parameter of overriding method should be annotated with __attribute__((noescape))}} +@end + +@implementation C4 +-(void) m0:(int*) p { +} ++(void) m1:(int*)__attribute__((noescape)) p { +} +-(void) m1:(int*) p { +} +@end diff --git a/test/SemaOpenCL/invalid-kernel-parameters.cl b/test/SemaOpenCL/invalid-kernel-parameters.cl index 2433c17fe022..e3372b188877 100644 --- a/test/SemaOpenCL/invalid-kernel-parameters.cl +++ b/test/SemaOpenCL/invalid-kernel-parameters.cl @@ -9,7 +9,35 @@ kernel void half_arg(half x) { } // expected-error{{declaring function parameter // bool, half, size_t, ptrdiff_t, intptr_t, and uintptr_t // or a struct / union with any of these types in them -// TODO: Ban int types, size_t, ptrdiff_t ... +typedef __SIZE_TYPE__ size_t; // expected-note{{'size_t' (aka 'unsigned int') declared here}} + // expected-note@-1{{'size_t' (aka 'unsigned int') declared here}} +typedef __PTRDIFF_TYPE__ ptrdiff_t; // expected-note{{'ptrdiff_t' (aka 'int') declared here}} +typedef __INTPTR_TYPE__ intptr_t; // expected-note{{'intptr_t' (aka 'int') declared here}} +typedef __UINTPTR_TYPE__ uintptr_t; // expected-note{{'uintptr_t' (aka 'unsigned int') declared here}} + +kernel void size_t_arg(size_t x) {} // expected-error{{'size_t' (aka 'unsigned int') cannot be used as the type of a kernel parameter}} + +kernel void ptrdiff_t_arg(ptrdiff_t x) {} // expected-error{{'ptrdiff_t' (aka 'int') cannot be used as the type of a kernel parameter}} + +kernel void intptr_t_arg(intptr_t x) {} // expected-error{{'intptr_t' (aka 'int') cannot be used as the type of a kernel parameter}} + +kernel void uintptr_t_arg(uintptr_t x) {} // expected-error{{'uintptr_t' (aka 'unsigned int') cannot be used as the type of a kernel parameter}} + +typedef size_t size_ty; +struct SizeTStruct { // expected-note{{within field of type 'SizeTStruct' declared here}} + size_ty s; // expected-note{{field of illegal type 'size_ty' (aka 'unsigned int') declared here}} +}; +kernel void size_t_struct_arg(struct SizeTStruct x) {} // expected-error{{'struct SizeTStruct' cannot be used as the type of a kernel parameter}} + +union SizeTUnion { // expected-note{{within field of type 'SizeTUnion' declared here}} + size_t s; // expected-note{{field of illegal type 'size_t' (aka 'unsigned int') declared here}} + float f; +}; +kernel void size_t_union_arg(union SizeTUnion x) {} // expected-error{{'union SizeTUnion' cannot be used as the type of a kernel parameter}} + +typedef size_t s_ty; // expected-note{{'s_ty' (aka 'unsigned int') declared here}} +typedef s_ty ss_ty; // expected-note{{'ss_ty' (aka 'unsigned int') declared here}} +kernel void typedef_to_size_t(ss_ty s) {} // expected-error{{'ss_ty' (aka 'unsigned int') cannot be used as the type of a kernel parameter}} kernel void bool_arg(bool x) { } // expected-error{{'bool' cannot be used as the type of a kernel parameter}} @@ -136,3 +164,16 @@ struct AlsoUser // expected-note{{within field of type 'AlsoUser' declared here} }; kernel void pointer_in_nested_struct_arg_2(struct Valid valid, struct NestedPointer arg, struct AlsoUser also) { } // expected-error 2 {{struct kernel parameters may not contain pointers}} + +struct ArrayOfPtr // expected-note{{within field of type 'ArrayOfPtr' declared here}} +{ + float *arr[3]; // expected-note{{field of illegal type 'float *[3]' declared here}} + // expected-note@-1{{field of illegal type 'float *[3]' declared here}} +}; +kernel void array_of_ptr(struct ArrayOfPtr arr) {} // expected-error{{struct kernel parameters may not contain pointers}} + +struct ArrayOfStruct // expected-note{{within field of type 'ArrayOfStruct' declared here}} +{ + struct ArrayOfPtr arr[3]; // expected-note{{within field of type 'struct ArrayOfPtr [3]' declared here}} +}; +kernel void array_of_struct(struct ArrayOfStruct arr) {} // expected-error{{struct kernel parameters may not contain pointers}} diff --git a/unittests/Format/FormatTestComments.cpp b/unittests/Format/FormatTestComments.cpp index cacd2024fef3..2b07dedf6706 100644 --- a/unittests/Format/FormatTestComments.cpp +++ b/unittests/Format/FormatTestComments.cpp @@ -3105,6 +3105,106 @@ TEST_F(FormatTestComments, ReflowBackslashCrash) { // clang-format on } +TEST_F(FormatTestComments, IndentsLongJavadocAnnotatedLines) { + FormatStyle Style = getGoogleStyle(FormatStyle::LK_Java); + Style.ColumnLimit = 60; + FormatStyle Style20 = getGoogleStyle(FormatStyle::LK_Java); + Style20.ColumnLimit = 20; + EXPECT_EQ( + "/**\n" + " * @param x long long long long long long long long long\n" + " * long\n" + " */\n", + format("/**\n" + " * @param x long long long long long long long long long long\n" + " */\n", + Style)); + EXPECT_EQ("/**\n" + " * @param x long long long long long long long long long\n" + " * long long long long long long long long long long\n" + " */\n", + format("/**\n" + " * @param x long long long long long long long long long " + "long long long long long long long long long long\n" + " */\n", + Style)); + EXPECT_EQ("/**\n" + " * @param x long long long long long long long long long\n" + " * long long long long long long long long long long\n" + " * long\n" + " */\n", + format("/**\n" + " * @param x long long long long long long long long long " + "long long long long long long long long long long long\n" + " */\n", + Style)); + EXPECT_EQ( + "/**\n" + " * Sentence that\n" + " * should be broken.\n" + " * @param short\n" + " * keep indentation\n" + " */\n", format( + "/**\n" + " * Sentence that should be broken.\n" + " * @param short\n" + " * keep indentation\n" + " */\n", Style20)); + + EXPECT_EQ("/**\n" + " * @param l1 long1\n" + " * to break\n" + " * @param l2 long2\n" + " * to break\n" + " */\n", + format("/**\n" + " * @param l1 long1 to break\n" + " * @param l2 long2 to break\n" + " */\n", + Style20)); + + EXPECT_EQ("/**\n" + " * @param xx to\n" + " * break\n" + " * no reflow\n" + " */\n", + format("/**\n" + " * @param xx to break\n" + " * no reflow\n" + " */\n", + Style20)); + + EXPECT_EQ("/**\n" + " * @param xx to\n" + " * break yes\n" + " * reflow\n" + " */\n", + format("/**\n" + " * @param xx to break\n" + " * yes reflow\n" + " */\n", + Style20)); + + FormatStyle JSStyle20 = getGoogleStyle(FormatStyle::LK_JavaScript); + JSStyle20.ColumnLimit = 20; + EXPECT_EQ("/**\n" + " * @param l1 long1\n" + " * to break\n" + " */\n", + format("/**\n" + " * @param l1 long1 to break\n" + " */\n", + JSStyle20)); + EXPECT_EQ("/**\n" + " * @param {l1 long1\n" + " * to break}\n" + " */\n", + format("/**\n" + " * @param {l1 long1 to break}\n" + " */\n", + JSStyle20)); +} + } // end namespace } // end namespace format } // end namespace clang diff --git a/unittests/Format/FormatTestJS.cpp b/unittests/Format/FormatTestJS.cpp index 9975b7d31125..e7808c6596d0 100644 --- a/unittests/Format/FormatTestJS.cpp +++ b/unittests/Format/FormatTestJS.cpp @@ -191,19 +191,28 @@ TEST_F(FormatTestJS, JSDocComments) { // Break a single line long jsdoc comment pragma. EXPECT_EQ("/**\n" - " * @returns {string} jsdoc line 12\n" + " * @returns\n" + " * {string}\n" + " * jsdoc line 12\n" " */", format("/** @returns {string} jsdoc line 12 */", getGoogleJSStyleWithColumns(20))); EXPECT_EQ("/**\n" - " * @returns {string} jsdoc line 12\n" + " * @returns\n" + " * {string}\n" + " * jsdoc line 12\n" " */", format("/** @returns {string} jsdoc line 12 */", getGoogleJSStyleWithColumns(20))); + // FIXME: this overcounts the */ as a continuation of the 12 when breaking. + // Related to the FIXME in BreakableBlockComment::getRangeLength. EXPECT_EQ("/**\n" - " * @returns {string} jsdoc line 12\n" + " * @returns\n" + " * {string}\n" + " * jsdoc line\n" + " * 12\n" " */", format("/** @returns {string} jsdoc line 12*/", getGoogleJSStyleWithColumns(20))); @@ -212,7 +221,8 @@ TEST_F(FormatTestJS, JSDocComments) { EXPECT_EQ("/**\n" " * line 1\n" " * line 2\n" - " * @returns {string} jsdoc line 12\n" + " * @returns {string}\n" + " * jsdoc line 12\n" " */", format("/** line 1\n" " * line 2\n" @@ -2028,21 +2038,24 @@ TEST_F(FormatTestJS, WrapAfterParen) { TEST_F(FormatTestJS, JSDocAnnotations) { verifyFormat("/**\n" - " * @export {this.is.a.long.path.to.a.Type}\n" + " * @exports\n" + " * {this.is.a.long.path.to.a.Type}\n" " */", "/**\n" - " * @export {this.is.a.long.path.to.a.Type}\n" + " * @exports {this.is.a.long.path.to.a.Type}\n" " */", getGoogleJSStyleWithColumns(20)); verifyFormat("/**\n" - " * @mods {this.is.a.long.path.to.a.Type}\n" + " * @mods\n" + " * {this.is.a.long.path.to.a.Type}\n" " */", "/**\n" " * @mods {this.is.a.long.path.to.a.Type}\n" " */", getGoogleJSStyleWithColumns(20)); verifyFormat("/**\n" - " * @param {this.is.a.long.path.to.a.Type}\n" + " * @param\n" + " * {this.is.a.long.path.to.a.Type}\n" " */", "/**\n" " * @param {this.is.a.long.path.to.a.Type}\n" @@ -2058,34 +2071,36 @@ TEST_F(FormatTestJS, JSDocAnnotations) { verifyFormat( "/**\n" " * @param This is a\n" - " * long comment but\n" - " * no type\n" + " * long comment\n" + " * but no type\n" " */", "/**\n" " * @param This is a long comment but no type\n" " */", getGoogleJSStyleWithColumns(20)); - // Don't break @param line, but reindent it and reflow unrelated lines. - verifyFormat("{\n" - " /**\n" - " * long long long\n" - " * long\n" - " * @param {this.is.a.long.path.to.a.Type} a\n" - " * long long long\n" - " * long long\n" - " */\n" - " function f(a) {}\n" - "}", - "{\n" - "/**\n" - " * long long long long\n" - " * @param {this.is.a.long.path.to.a.Type} a\n" - " * long long long long\n" - " * long\n" - " */\n" - " function f(a) {}\n" - "}", - getGoogleJSStyleWithColumns(20)); + // Break and reindent @param line and reflow unrelated lines. + EXPECT_EQ("{\n" + " /**\n" + " * long long long\n" + " * long\n" + " * @param\n" + " * {this.is.a.long.path.to.a.Type}\n" + " * a\n" + " * long long long\n" + " * long long\n" + " */\n" + " function f(a) {}\n" + "}", + format("{\n" + "/**\n" + " * long long long long\n" + " * @param {this.is.a.long.path.to.a.Type} a\n" + " * long long long long\n" + " * long\n" + " */\n" + " function f(a) {}\n" + "}", + getGoogleJSStyleWithColumns(20))); } TEST_F(FormatTestJS, RequoteStringsSingle) { diff --git a/utils/TableGen/ClangAttrEmitter.cpp b/utils/TableGen/ClangAttrEmitter.cpp index 0bf7a07cf6e1..6b3df825808f 100644 --- a/utils/TableGen/ClangAttrEmitter.cpp +++ b/utils/TableGen/ClangAttrEmitter.cpp @@ -3305,11 +3305,16 @@ static std::string GenerateAppertainsTo(const Record &Attr, raw_ostream &OS) { // Otherwise, generate an appertainsTo check specific to this attribute which // checks all of the given subjects against the Decl passed in. Return the // name of that check to the caller. + // + // If D is null, that means the attribute was not applied to a declaration + // at all (for instance because it was applied to a type), or that the caller + // has determined that the check should fail (perhaps prior to the creation + // of the declaration). std::string FnName = "check" + Attr.getName().str() + "AppertainsTo"; std::stringstream SS; SS << "static bool " << FnName << "(Sema &S, const ParsedAttr &Attr, "; SS << "const Decl *D) {\n"; - SS << " if ("; + SS << " if (!D || ("; for (auto I = Subjects.begin(), E = Subjects.end(); I != E; ++I) { // If the subject has custom code associated with it, generate a function // for it. The function cannot be inlined into this check (yet) because it @@ -3325,7 +3330,7 @@ static std::string GenerateAppertainsTo(const Record &Attr, raw_ostream &OS) { if (I + 1 != E) SS << " && "; } - SS << ") {\n"; + SS << ")) {\n"; SS << " S.Diag(Attr.getLoc(), diag::"; SS << (Warn ? "warn_attribute_wrong_decl_type_str" : "err_attribute_wrong_decl_type_str"); diff --git a/utils/analyzer/CmpRuns.py b/utils/analyzer/CmpRuns.py index 1b8fe7bd698d..7c9744727e90 100755 --- a/utils/analyzer/CmpRuns.py +++ b/utils/analyzer/CmpRuns.py @@ -312,11 +312,11 @@ def compareStats(resultsA, resultsB): # Only apply highlighting when writing to TTY and it's not Windows if sys.stdout.isatty() and os.name != 'nt': if valB != 0: - ratio = (valB - valA) / valB - if ratio < -0.2: - report = Colors.GREEN + report + Colors.CLEAR - elif ratio > 0.2: - report = Colors.RED + report + Colors.CLEAR + ratio = (valB - valA) / valB + if ratio < -0.2: + report = Colors.GREEN + report + Colors.CLEAR + elif ratio > 0.2: + report = Colors.RED + report + Colors.CLEAR print "\t %s %s" % (kkey, report) def dumpScanBuildResultsDiff(dirA, dirB, opts, deleteEmpty=True, @@ -324,7 +324,7 @@ def dumpScanBuildResultsDiff(dirA, dirB, opts, deleteEmpty=True, # Load the run results. resultsA = loadResults(dirA, opts, opts.rootA, deleteEmpty) resultsB = loadResults(dirB, opts, opts.rootB, deleteEmpty) - if resultsA.stats: + if opts.show_stats: compareStats(resultsA, resultsB) if opts.stats_only: return @@ -399,6 +399,8 @@ def generate_option_parser(): Requires matplotlib") parser.add_option("--stats-only", action="store_true", dest="stats_only", default=False, help="Only show statistics on reports") + parser.add_option("--show-stats", action="store_true", dest="show_stats", + default=False, help="Show change in statistics") return parser diff --git a/utils/analyzer/SATestBuild.py b/utils/analyzer/SATestBuild.py index 4da025aa53b3..ea95ee289e99 100644 --- a/utils/analyzer/SATestBuild.py +++ b/utils/analyzer/SATestBuild.py @@ -60,9 +60,9 @@ import threading import time import Queue -#------------------------------------------------------------------------------ +############################################################################### # Helper functions. -#------------------------------------------------------------------------------ +############################################################################### Local = threading.local() Local.stdout = sys.stdout @@ -91,9 +91,9 @@ def getProjectMapPath(): ProjectMapPath = os.path.join(os.path.abspath(os.curdir), ProjectMapFile) if not os.path.exists(ProjectMapPath): - Local.stdout.write("Error: Cannot find the Project Map file " - + ProjectMapPath - + "\nRunning script for the wrong directory?\n") + Local.stdout.write("Error: Cannot find the Project Map file " + + ProjectMapPath + + "\nRunning script for the wrong directory?\n") sys.exit(1) return ProjectMapPath @@ -108,9 +108,9 @@ def getSBOutputDirName(IsReferenceBuild): else: return SBOutputDirName -#------------------------------------------------------------------------------ +############################################################################### # Configuration setup. -#------------------------------------------------------------------------------ +############################################################################### # Find Clang for static analysis. @@ -185,9 +185,9 @@ Checkers = ",".join([ Verbose = 0 -#------------------------------------------------------------------------------ +############################################################################### # Test harness logic. -#------------------------------------------------------------------------------ +############################################################################### def runCleanupScript(Dir, PBuildLogFile): |