2 changes: 1 addition & 1 deletion clang/cmake/caches/HLSL.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ set(LLVM_ENABLE_PROJECTS "clang;clang-tools-extra" CACHE STRING "")

set(CLANG_ENABLE_HLSL On CACHE BOOL "")

if (NOT CMAKE_CONFIGURATION_TYPES)
if (HLSL_ENABLE_DISTRIBUTION)
set(LLVM_DISTRIBUTION_COMPONENTS
"clang;hlsl-resource-headers;clangd"
CACHE STRING "")
Expand Down
4 changes: 1 addition & 3 deletions clang/cmake/caches/VectorEngine.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,7 @@
# ninja
#

# Disable TERMINFO, ZLIB, and ZSTD for VE since there is no pre-compiled
# libraries.
set(LLVM_ENABLE_TERMINFO OFF CACHE BOOL "")
# Disable ZLIB, and ZSTD for VE since there is no pre-compiled libraries.
set(LLVM_ENABLE_ZLIB OFF CACHE BOOL "")
set(LLVM_ENABLE_ZSTD OFF CACHE BOOL "")

Expand Down
3 changes: 0 additions & 3 deletions clang/cmake/modules/AddClang.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ function(clang_tablegen)

if(CTG_TARGET)
add_public_tablegen_target(${CTG_TARGET})
set_target_properties( ${CTG_TARGET} PROPERTIES FOLDER "Clang tablegenning")
set_property(GLOBAL APPEND PROPERTY CLANG_TABLEGEN_TARGETS ${CTG_TARGET})
endif()
endfunction(clang_tablegen)
Expand Down Expand Up @@ -138,13 +137,11 @@ macro(add_clang_library name)
endif()
endforeach()

set_target_properties(${name} PROPERTIES FOLDER "Clang libraries")
set_clang_windows_version_resource_properties(${name})
endmacro(add_clang_library)

macro(add_clang_executable name)
add_llvm_executable( ${name} ${ARGN} )
set_target_properties(${name} PROPERTIES FOLDER "Clang executables")
set_clang_windows_version_resource_properties(${name})
endmacro(add_clang_executable)

Expand Down
1 change: 1 addition & 0 deletions clang/docs/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ if (LLVM_ENABLE_DOXYGEN)
COMMAND ${DOXYGEN_EXECUTABLE} ${CMAKE_CURRENT_BINARY_DIR}/doxygen.cfg
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
COMMENT "Generating clang doxygen documentation." VERBATIM)
set_target_properties(doxygen-clang PROPERTIES FOLDER "Clang/Docs")

if (LLVM_BUILD_DOCS)
add_dependencies(doxygen doxygen-clang)
Expand Down
12 changes: 10 additions & 2 deletions clang/docs/ClangFormatStyleOptions.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1421,13 +1421,21 @@ the configuration (without a prefix: ``Auto``).

.. code-block:: c++

true:
#define A \
int aaaa; \
int b; \
int dddddddddd;

false:
* ``ENAS_LeftWithLastLine`` (in configuration: ``LeftWithLastLine``)
Align escaped newlines as far left as possible, using the last line of
the preprocessor directive as the reference if it's the longest.

.. code-block:: c++

#define A \
int aaaa; \
int b; \
int dddddddddd;

* ``ENAS_Right`` (in configuration: ``Right``)
Align escaped newlines in the right-most column.
Expand Down
137 changes: 137 additions & 0 deletions clang/docs/HLSL/AvailabilityDiagnostics.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
=============================
HLSL Availability Diagnostics
=============================

.. contents::
:local:

Introduction
============

HLSL availability diagnostics emits errors or warning when unavailable shader APIs are used. Unavailable shader APIs are APIs that are exposed in HLSL code but are not available in the target shader stage or shader model version.

There are three modes of HLSL availability diagnostic:

#. **Default mode** - compiler emits an error when an unavailable API is found in a code that is reachable from the shader entry point function or from an exported library function (when compiling a shader library)

#. **Relaxed mode** - same as default mode except the compiler emits a warning. This mode is enabled by ``-Wno-error=hlsl-availability``.

#. **Strict mode** - compiler emits an error when an unavailable API is found in parsed code regardless of whether it can be reached from the shader entry point or exported functions, or not. This mode is enabled by ``-fhlsl-strict-availability``.

Implementation Details
======================

Environment Parameter
---------------------

In order to encode API availability based on the shader model version and shader model stage a new ``environment`` parameter was added to the existing Clang ``availability`` attribute.

The values allowed for this parameter are a subset of values allowed as the ``llvm::Triple`` environment component. If the environment parameters is present, the declared availability attribute applies only to targets with the same platform and environment.

Default and Relaxed Diagnostic Modes
------------------------------------

This mode is implemented in ``DiagnoseHLSLAvailability`` class in ``SemaHLSL.cpp`` and it is invoked after the whole translation unit is parsed (from ``Sema::ActOnEndOfTranslationUnit``). The implementation iterates over all shader entry points and exported library functions in the translation unit and performs an AST traversal of each function body.

When a reference to another function or member method is found (``DeclRefExpr`` or ``MemberExpr``) and it has a body, the AST of the referenced function is also scanned. This chain of AST traversals will reach all of the code that is reachable from the initial shader entry point or exported library function and avoids the need to generate a call graph.

All shader APIs have an availability attribute that specifies the shader model version (and environment, if applicable) when this API was first introduced.When a reference to a function without a definition is found and it has an availability attribute, the version of the attribute is checked against the target shader model version and shader stage (if shader stage context is known), and an appropriate diagnostic is generated as needed.

All shader entry functions have ``HLSLShaderAttr`` attribute that specifies what type of shader this function represents. However, for exported library functions the target shader stage is unknown, so in this case the HLSL API availability will be only checked against the shader model version. It means that for exported library functions the diagnostic of APIs with availability specific to shader stage will be deferred until DXIL linking time.

A list of functions that were already scanned is kept in order to avoid duplicate scans and diagnostics (see ``DiagnoseHLSLAvailability::ScannedDecls``). It might happen that a shader library has multiple shader entry points for different shader stages that all call into the same shared function. It is therefore important to record not just that a function has been scanned, but also in which shader stage context. This is done by using ``llvm::DenseMap`` that maps ``FunctionDecl *`` to a ``unsigned`` bitmap that represents a set of shader stages (or environments) the function has been scanned for. The ``N``'th bit in the set is set if the function has been scanned in shader environment whose ``HLSLShaderAttr::ShaderType`` integer value equals ``N``.

The emitted diagnostic messages belong to ``hlsl-availability`` diagnostic group and are reported as errors by default. With ``-Wno-error=hlsl-availability`` flag they become warning, making it relaxed HLSL diagnostics mode.

Strict Diagnostic Mode
----------------------

When strict HLSL availability diagnostic mode is enabled the compiler must report all HLSL API availability issues regardless of code reachability. The implementation of this mode takes advantage of an existing diagnostic scan in ``DiagnoseUnguardedAvailability`` class which is already traversing AST of each function as soon as the function body has been parsed. For HLSL, this pass was only slightly modified, such as making sure diagnostic messages are in the ``hlsl-availability`` group and that availability checks based on shader stage are not included if the shader stage context is unknown.

If the compilation target is a shader library, only availability based on shader model version can be diagnosed during this scan. To diagnose availability based on shader stage, the compiler needs to run the AST traversals implementated in ``DiagnoseHLSLAvailability`` at the end of the translation unit as described above.

As a result, availability based on specific shader stage will only be diagnosed in code that is reachable from a shader entry point or library export function. It also means that function bodies might be scanned multiple time. When that happens, care should be taken not to produce duplicated diagnostics.

========
Examples
========

**Note**
For the example below, the ``WaveActiveCountBits`` API function became available in shader model 6.0 and ``WaveMultiPrefixSum`` in shader model 6.5.

The availability of ``ddx`` function depends on a shader stage. It is available for pixel shaders in shader model 2.1 and higher, for compute, mesh and amplification shaders in shader model 6.6 and higher. For any other shader stages it is not available.

Compute shader example
======================

.. code-block:: c++

float unusedFunction(float f) {
return ddx(f);
}

[numthreads(4, 4, 1)]
void main(uint3 threadId : SV_DispatchThreadId) {
float f1 = ddx(threadId.x);
float f2 = WaveActiveCountBits(threadId.y == 1.0);
}

When compiled as compute shader for shader model version 5.0, Clang will emit the following error by default:

.. code-block:: console
<>:7:13: error: 'ddx' is only available in compute shader environment on Shader Model 6.6 or newer
<>:8:13: error: 'WaveActiveCountBits' is only available on Shader Model 6.5 or newer
With relaxed diagnostic mode this errors will become warnings.

With strict diagnostic mode, in addition to the 2 errors above Clang will also emit error for the ``ddx`` call in ``unusedFunction``.:

.. code-block:: console
<>:2:9: error: 'ddx' is only available in compute shader environment on Shader Model 6.5 or newer
<>:7:13: error: 'ddx' is only available in compute shader environment on Shader Model 6.5 or newer
<>:7:13: error: 'WaveActiveCountBits' is only available on Shader Model 6.5 or newer
Shader library example
======================

.. code-block:: c++

float myFunction(float f) {
return ddx(f);
}

float unusedFunction(float f) {
return WaveMultiPrefixSum(f, 1.0);
}

[shader("compute")]
[numthreads(4, 4, 1)]
void main(uint3 threadId : SV_DispatchThreadId) {
float f = 3;
float e = myFunction(f);
}

[shader("pixel")]
void main() {
float f = 3;
float e = myFunction(f);
}

When compiled as shader library vshader model version 6.4, Clang will emit the following error by default:

.. code-block:: console
<>:2:9: error: 'ddx' is only available in compute shader environment on Shader Model 6.5 or newer
With relaxed diagnostic mode this errors will become warnings.

With strict diagnostic mode Clang will also emit errors for availability issues in code that is not used by any of the entry points:

.. code-block:: console
<>2:9: error: 'ddx' is only available in compute shader environment on Shader Model 6.6 or newer
<>:6:9: error: 'WaveActiveCountBits' is only available on Shader Model 6.5 or newer
Note that ``myFunction`` is reachable from both pixel and compute shader entry points is therefore scanned twice - once for each context. The diagnostic is emitted only for the compute shader context.
1 change: 1 addition & 0 deletions clang/docs/HLSL/HLSLDocs.rst
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,4 @@ HLSL Design and Implementation
ResourceTypes
EntryFunctions
FunctionCalls
AvailabilityDiagnostics
39 changes: 38 additions & 1 deletion clang/docs/LanguageExtensions.rst
Original file line number Diff line number Diff line change
Expand Up @@ -4403,6 +4403,7 @@ immediately after the name being declared.
For example, this applies the GNU ``unused`` attribute to ``a`` and ``f``, and
also applies the GNU ``noreturn`` attribute to ``f``.
Examples:
.. code-block:: c++
[[gnu::unused]] int a, f [[gnu::noreturn]] ();
Expand All @@ -4412,6 +4413,42 @@ Target-Specific Extensions
Clang supports some language features conditionally on some targets.
AMDGPU Language Extensions
--------------------------
__builtin_amdgcn_fence
^^^^^^^^^^^^^^^^^^^^^^
``__builtin_amdgcn_fence`` emits a fence.
* ``unsigned`` atomic ordering, e.g. ``__ATOMIC_ACQUIRE``
* ``const char *`` synchronization scope, e.g. ``workgroup``
* Zero or more ``const char *`` address spaces names.
The address spaces arguments must be one of the following string literals:
* ``"local"``
* ``"global"``
If one or more address space name are provided, the code generator will attempt
to emit potentially faster instructions that order access to at least those
address spaces.
Emitting such instructions may not always be possible and the compiler is free
to fence more aggressively.
If no address spaces names are provided, all address spaces are fenced.
.. code-block:: c++
// Fence all address spaces.
__builtin_amdgcn_fence(__ATOMIC_SEQ_CST, "workgroup");
__builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "agent");
// Fence only requested address spaces.
__builtin_amdgcn_fence(__ATOMIC_SEQ_CST, "workgroup", "local")
__builtin_amdgcn_fence(__ATOMIC_SEQ_CST, "workgroup", "local", "global")
ARM/AArch64 Language Extensions
-------------------------------
Expand Down Expand Up @@ -5602,4 +5639,4 @@ Compiling different TUs depending on these flags (including use of
``std::hardware_constructive_interference`` or
``std::hardware_destructive_interference``) with different compilers, macro
definitions, or architecture flags will lead to ODR violations and should be
avoided.
avoided.
58 changes: 56 additions & 2 deletions clang/docs/ReleaseNotes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,18 @@ C++ Specific Potentially Breaking Changes
- Clang now performs semantic analysis for unary operators with dependent operands
that are known to be of non-class non-enumeration type prior to instantiation.

This change uncovered a bug in libstdc++ 14.1.0 which may cause compile failures
on systems using that version of libstdc++ and Clang 19, with an error that looks
something like this:

.. code-block:: text
<source>:4:5: error: expression is not assignable
4 | ++this;
| ^ ~~~~
To fix this, update libstdc++ to version 14.1.1 or greater.

ABI Changes in This Version
---------------------------
- Fixed Microsoft name mangling of implicitly defined variables used for thread
Expand Down Expand Up @@ -155,6 +167,11 @@ C++17 Feature Support
files because they may not be stable across multiple TUs (the values may vary
based on compiler version as well as CPU tuning). #GH60174

C++14 Feature Support
^^^^^^^^^^^^^^^^^^^^^
- Sized deallocation is enabled by default in C++14 onwards. The user may specify
``-fno-sized-deallocation`` to disable it if there are some regressions.

C++20 Feature Support
^^^^^^^^^^^^^^^^^^^^^

Expand Down Expand Up @@ -325,6 +342,10 @@ New Compiler Flags
``__attribute__((section(...)))``. This enables linker GC to collect unused
symbols without having to use a per-symbol section.

- ``-fms-define-stdc`` and its clang-cl counterpart ``/Zc:__STDC__``.
Matches MSVC behaviour by defining ``__STDC__`` to ``1`` when
MSVC compatibility mode is used. It has no effect for C++ code.

Deprecated Compiler Flags
-------------------------

Expand Down Expand Up @@ -605,9 +626,14 @@ Bug Fixes in This Version
- Clang now correctly disallows VLA type compound literals, e.g. ``(int[size]){}``,
as the C standard mandates. (#GH89835)

- ``__is_array`` and ``__is_bounded_array`` no longer return ``true`` for
zero-sized arrays. Fixes (#GH54705).

Bug Fixes to Compiler Builtins
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

- Fix crash when atomic builtins are called with pointer to zero-size struct (#GH90330)

Bug Fixes to Attribute Support
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Expand Down Expand Up @@ -710,7 +736,6 @@ Bug Fixes to C++ Support
from being explicitly specialized for a given implicit instantiation of the class template.
- Fixed a crash when ``this`` is used in a dependent class scope function template specialization
that instantiates to a static member function.

- Fix crash when inheriting from a cv-qualified type. Fixes #GH35603
- Fix a crash when the using enum declaration uses an anonymous enumeration. Fixes (#GH86790).
- Handled an edge case in ``getFullyPackExpandedSize`` so that we now avoid a false-positive diagnostic. (#GH84220)
Expand Down Expand Up @@ -758,6 +783,25 @@ Bug Fixes to C++ Support
- Fix a bug with checking constrained non-type template parameters for equivalence. Fixes (#GH77377).
- Fix a bug where the last argument was not considered when considering the most viable function for
explicit object argument member functions. Fixes (#GH92188).
- Fix a C++11 crash when a non-const non-static member function is defined out-of-line with
the ``constexpr`` specifier. Fixes (#GH61004).
- Clang no longer transforms dependent qualified names into implicit class member access expressions
until it can be determined whether the name is that of a non-static member.
- Clang now correctly diagnoses when the current instantiation is used as an incomplete base class.
- Clang no longer treats ``constexpr`` class scope function template specializations of non-static members
as implicitly ``const`` in language modes after C++11.
- Fixed a crash when trying to emit captures in a lambda call operator with an explicit object
parameter that is called on a derived type of the lambda.
Fixes (#GH87210), (GH89541).
- Clang no longer tries to check if an expression is immediate-escalating in an unevaluated context.
Fixes (#GH91308).
- Fix a crash caused by a regression in the handling of ``source_location``
in dependent contexts. Fixes (#GH92680).
- Fixed a crash when diagnosing failed conversions involving template parameter
packs. (#GH93076)
- Fixed a regression introduced in Clang 18 causing a static function overloading a non-static function
with the same parameters not to be diagnosed. (Fixes #GH93456).
- Clang now diagnoses unexpanded parameter packs in attributes. (Fixes #GH93269).

Bug Fixes to AST Handling
^^^^^^^^^^^^^^^^^^^^^^^^^
Expand All @@ -770,12 +814,15 @@ Miscellaneous Bug Fixes

- Fixed an infinite recursion in ASTImporter, on return type declared inside
body of C++11 lambda without trailing return (#GH68775).
- Fixed declaration name source location of instantiated function definitions (GH71161).
- Improve diagnostic output to print an expression instead of 'no argument` when comparing Values as template arguments.

Miscellaneous Clang Crashes Fixed
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

- Do not attempt to dump the layout of dependent types or invalid declarations
when ``-fdump-record-layouts-complete`` is passed. Fixes #GH83684.
- Unhandled StructuralValues in the template differ (#GH93068).

OpenACC Specific Changes
------------------------
Expand All @@ -789,6 +836,8 @@ AMDGPU Support
X86 Support
^^^^^^^^^^^

- Remove knl/knm specific ISA supports: AVX512PF, AVX512ER, PREFETCHWT1

Arm and AArch64 Support
^^^^^^^^^^^^^^^^^^^^^^^

Expand Down Expand Up @@ -841,6 +890,10 @@ Windows Support
including STL headers will no longer slow down compile times since ``intrin.h``
is not included from MSVC STL.

- When the target triple is `*-windows-msvc` strict aliasing is now disabled by default
to ensure compatibility with msvc. Previously strict aliasing was only disabled if the
driver mode was cl.

LoongArch Support
^^^^^^^^^^^^^^^^^

Expand Down Expand Up @@ -911,9 +964,10 @@ clang-format
``BreakTemplateDeclarations``.
- ``AlwaysBreakAfterReturnType`` is deprecated and renamed to
``BreakAfterReturnType``.
- Handles Java ``switch`` expressions.
- Handles Java switch expressions.
- Adds ``AllowShortCaseExpressionOnASingleLine`` option.
- Adds ``AlignCaseArrows`` suboption to ``AlignConsecutiveShortCaseStatements``.
- Adds ``LeftWithLastLine`` suboption to ``AlignEscapedNewlines``.

libclang
--------
Expand Down
125 changes: 76 additions & 49 deletions clang/docs/analyzer/checkers.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1179,6 +1179,47 @@ security.insecureAPI.DeprecatedOrUnsafeBufferHandling (C)
strncpy(buf, "a", 1); // warn
}
security.SetgidSetuidOrder (C)
""""""""""""""""""""""""""""""
When dropping user-level and group-level privileges in a program by using
``setuid`` and ``setgid`` calls, it is important to reset the group-level
privileges (with ``setgid``) first. Function ``setgid`` will likely fail if
the superuser privileges are already dropped.
The checker checks for sequences of ``setuid(getuid())`` and
``setgid(getgid())`` calls (in this order). If such a sequence is found and
there is no other privilege-changing function call (``seteuid``, ``setreuid``,
``setresuid`` and the GID versions of these) in between, a warning is
generated. The checker finds only exactly ``setuid(getuid())`` calls (and the
GID versions), not for example if the result of ``getuid()`` is stored in a
variable.
.. code-block:: c
void test1() {
// ...
// end of section with elevated privileges
// reset privileges (user and group) to normal user
if (setuid(getuid()) != 0) {
handle_error();
return;
}
if (setgid(getgid()) != 0) { // warning: A 'setgid(getgid())' call following a 'setuid(getuid())' call is likely to fail
handle_error();
return;
}
// user-ID and group-ID are reset to normal user now
// ...
}
In the code above the problem is that ``setuid(getuid())`` removes superuser
privileges before ``setgid(getgid())`` is called. To fix the problem the
``setgid(getgid())`` should be called first. Further attention is needed to
avoid code like ``setgid(getuid())`` (this checker does not detect bugs like
this) and always check the return value of these calls.
This check corresponds to SEI CERT Rule `POS36-C <https://wiki.sei.cmu.edu/confluence/display/c/POS36-C.+Observe+correct+revocation+order+while+relinquishing+privileges>`_.
.. _unix-checkers:
unix
Expand Down Expand Up @@ -2792,6 +2833,41 @@ Warn on mmap() calls that are both writable and executable.
// code
}
.. _alpha-security-putenv-stack-array:
alpha.security.PutenvStackArray (C)
"""""""""""""""""""""""""""""""""""
Finds calls to the ``putenv`` function which pass a pointer to a stack-allocated
(automatic) array as the argument. Function ``putenv`` does not copy the passed
string, only a pointer to the data is stored and this data can be read even by
other threads. Content of a stack-allocated array is likely to be overwritten
after returning from the parent function.
The problem can be solved by using a static array variable or dynamically
allocated memory. Even better is to avoid using ``putenv`` (it has other
problems related to memory leaks) and use ``setenv`` instead.
The check corresponds to CERT rule
`POS34-C. Do not call putenv() with a pointer to an automatic variable as the argument
<https://wiki.sei.cmu.edu/confluence/display/c/POS34-C.+Do+not+call+putenv%28%29+with+a+pointer+to+an+automatic+variable+as+the+argument>`_.
.. code-block:: c
int f() {
char env[] = "NAME=value";
return putenv(env); // putenv function should not be called with stack-allocated string
}
There is one case where the checker can report a false positive. This is when
the stack-allocated array is used at `putenv` in a function or code branch that
does not return (calls `fork` or `exec` like function).
Another special case is if the `putenv` is called from function `main`. Here
the stack is deallocated at the end of the program and it should be no problem
to use the stack-allocated string (a multi-threaded program may require more
attention). The checker does not warn for cases when stack space of `main` is
used at the `putenv` call.
.. _alpha-security-ReturnPtrRange:
alpha.security.ReturnPtrRange (C)
Expand All @@ -2818,55 +2894,6 @@ alpha.security.cert
SEI CERT checkers which tries to find errors based on their `C coding rules <https://wiki.sei.cmu.edu/confluence/display/c/2+Rules>`_.
.. _alpha-security-cert-pos-checkers:
alpha.security.cert.pos
^^^^^^^^^^^^^^^^^^^^^^^
SEI CERT checkers of `POSIX C coding rules <https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152405>`_.
.. _alpha-security-cert-pos-34c:
alpha.security.cert.pos.34c
"""""""""""""""""""""""""""
Finds calls to the ``putenv`` function which pass a pointer to an automatic variable as the argument.
.. code-block:: c
int func(const char *var) {
char env[1024];
int retval = snprintf(env, sizeof(env),"TEST=%s", var);
if (retval < 0 || (size_t)retval >= sizeof(env)) {
/* Handle error */
}
return putenv(env); // putenv function should not be called with auto variables
}
Limitations:
- Technically, one can pass automatic variables to ``putenv``,
but one needs to ensure that the given environment key stays
alive until it's removed or overwritten.
Since the analyzer cannot keep track of which envvars get overwritten
and when, it needs to be slightly more aggressive and warn for such
cases too, leading in some cases to false-positive reports like this:
.. code-block:: c
void baz() {
char env[] = "NAME=value";
putenv(env); // false-positive warning: putenv function should not be called...
// More code...
putenv((char *)"NAME=anothervalue");
// This putenv call overwrites the previous entry, thus that can no longer dangle.
} // 'env' array becomes dead only here.
alpha.security.cert.env
^^^^^^^^^^^^^^^^^^^^^^^
SEI CERT checkers of `Environment C coding rules <https://wiki.sei.cmu.edu/confluence/x/JdcxBQ>`_.
alpha.security.taint
^^^^^^^^^^^^^^^^^^^^
Expand Down
3 changes: 3 additions & 0 deletions clang/docs/tools/clang-formatted-files.txt
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@ clang/include/clang/Analysis/Analyses/CFGReachabilityAnalysis.h
clang/include/clang/Analysis/Analyses/ExprMutationAnalyzer.h
clang/include/clang/Analysis/FlowSensitive/AdornedCFG.h
clang/include/clang/Analysis/FlowSensitive/ASTOps.h
clang/include/clang/Analysis/FlowSensitive/CNFFormula.h
clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
Expand Down Expand Up @@ -621,6 +622,7 @@ clang/tools/libclang/CXCursor.h
clang/tools/scan-build-py/tests/functional/src/include/clean-one.h
clang/unittests/Analysis/CFGBuildResult.h
clang/unittests/Analysis/MacroExpansionContextTest.cpp
clang/unittests/Analysis/FlowSensitive/CNFFormula.cpp
clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp
clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
clang/unittests/Analysis/FlowSensitive/MapLatticeTest.cpp
Expand All @@ -632,6 +634,7 @@ clang/unittests/Analysis/FlowSensitive/TestingSupport.cpp
clang/unittests/Analysis/FlowSensitive/TestingSupport.h
clang/unittests/Analysis/FlowSensitive/TestingSupportTest.cpp
clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
clang/unittests/Analysis/FlowSensitive/WatchedLiteralsSolver.cpp
clang/unittests/Analysis/FlowSensitive/WatchedLiteralsSolverTest.cpp
clang/unittests/AST/ASTImporterFixtures.cpp
clang/unittests/AST/ASTImporterFixtures.h
Expand Down
11 changes: 10 additions & 1 deletion clang/include/clang/AST/ASTContext.h
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,9 @@ class VarTemplateDecl;
class VTableContextBase;
class XRayFunctionFilter;

/// A simple array of base specifiers.
typedef SmallVector<CXXBaseSpecifier *, 4> CXXCastPath;

namespace Builtin {

class Context;
Expand Down Expand Up @@ -1170,6 +1173,12 @@ class ASTContext : public RefCountedBase<ASTContext> {
/// in device compilation.
llvm::DenseSet<const FunctionDecl *> CUDAImplicitHostDeviceFunUsedByDevice;

/// For capturing lambdas with an explicit object parameter whose type is
/// derived from the lambda type, we need to perform derived-to-base
/// conversion so we can access the captures; the cast paths for that
/// are stored here.
llvm::DenseMap<const CXXMethodDecl *, CXXCastPath> LambdaCastPaths;

ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents,
SelectorTable &sels, Builtin::Context &builtins,
TranslationUnitKind TUKind);
Expand Down Expand Up @@ -2611,7 +2620,7 @@ class ASTContext : public RefCountedBase<ASTContext> {
///
/// \returns if this is an array type, the completely unqualified array type
/// that corresponds to it. Otherwise, returns T.getUnqualifiedType().
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals);
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals) const;

/// Determine whether the given types are equivalent after
/// cvr-qualifiers have been removed.
Expand Down
8 changes: 4 additions & 4 deletions clang/include/clang/AST/ASTNodeTraverser.h
Original file line number Diff line number Diff line change
Expand Up @@ -695,7 +695,7 @@ class ASTNodeTraverser
if (const auto *TC = D->getTypeConstraint())
Visit(TC->getImmediatelyDeclaredConstraint());
if (D->hasDefaultArgument())
Visit(D->getDefaultArgument(), SourceRange(),
Visit(D->getDefaultArgument().getArgument(), SourceRange(),
D->getDefaultArgStorage().getInheritedFrom(),
D->defaultArgumentWasInherited() ? "inherited from" : "previous");
}
Expand All @@ -704,9 +704,9 @@ class ASTNodeTraverser
if (const auto *E = D->getPlaceholderTypeConstraint())
Visit(E);
if (D->hasDefaultArgument())
Visit(D->getDefaultArgument(), SourceRange(),
D->getDefaultArgStorage().getInheritedFrom(),
D->defaultArgumentWasInherited() ? "inherited from" : "previous");
dumpTemplateArgumentLoc(
D->getDefaultArgument(), D->getDefaultArgStorage().getInheritedFrom(),
D->defaultArgumentWasInherited() ? "inherited from" : "previous");
}

void VisitTemplateTemplateParmDecl(const TemplateTemplateParmDecl *D) {
Expand Down
2 changes: 2 additions & 0 deletions clang/include/clang/AST/Decl.h
Original file line number Diff line number Diff line change
Expand Up @@ -2188,6 +2188,8 @@ class FunctionDecl : public DeclaratorDecl,

void setRangeEnd(SourceLocation E) { EndRangeLoc = E; }

void setDeclarationNameLoc(DeclarationNameLoc L) { DNLoc = L; }

/// Returns the location of the ellipsis of a variadic function.
SourceLocation getEllipsisLoc() const {
const auto *FPT = getType()->getAs<FunctionProtoType>();
Expand Down
28 changes: 14 additions & 14 deletions clang/include/clang/AST/DeclTemplate.h
Original file line number Diff line number Diff line change
Expand Up @@ -1185,7 +1185,7 @@ class TemplateTypeParmDecl final : public TypeDecl,

/// The default template argument, if any.
using DefArgStorage =
DefaultArgStorage<TemplateTypeParmDecl, TypeSourceInfo *>;
DefaultArgStorage<TemplateTypeParmDecl, TemplateArgumentLoc *>;
DefArgStorage DefaultArgument;

TemplateTypeParmDecl(DeclContext *DC, SourceLocation KeyLoc,
Expand Down Expand Up @@ -1225,13 +1225,9 @@ class TemplateTypeParmDecl final : public TypeDecl,
bool hasDefaultArgument() const { return DefaultArgument.isSet(); }

/// Retrieve the default argument, if any.
QualType getDefaultArgument() const {
return DefaultArgument.get()->getType();
}

/// Retrieves the default argument's source information, if any.
TypeSourceInfo *getDefaultArgumentInfo() const {
return DefaultArgument.get();
const TemplateArgumentLoc &getDefaultArgument() const {
static const TemplateArgumentLoc NoneLoc;
return DefaultArgument.isSet() ? *DefaultArgument.get() : NoneLoc;
}

/// Retrieves the location of the default argument declaration.
Expand All @@ -1244,9 +1240,8 @@ class TemplateTypeParmDecl final : public TypeDecl,
}

/// Set the default argument for this template parameter.
void setDefaultArgument(TypeSourceInfo *DefArg) {
DefaultArgument.set(DefArg);
}
void setDefaultArgument(const ASTContext &C,
const TemplateArgumentLoc &DefArg);

/// Set that this default argument was inherited from another
/// parameter.
Expand Down Expand Up @@ -1365,7 +1360,8 @@ class NonTypeTemplateParmDecl final

/// The default template argument, if any, and whether or not
/// it was inherited.
using DefArgStorage = DefaultArgStorage<NonTypeTemplateParmDecl, Expr *>;
using DefArgStorage =
DefaultArgStorage<NonTypeTemplateParmDecl, TemplateArgumentLoc *>;
DefArgStorage DefaultArgument;

// FIXME: Collapse this into TemplateParamPosition; or, just move depth/index
Expand Down Expand Up @@ -1435,7 +1431,10 @@ class NonTypeTemplateParmDecl final
bool hasDefaultArgument() const { return DefaultArgument.isSet(); }

/// Retrieve the default argument, if any.
Expr *getDefaultArgument() const { return DefaultArgument.get(); }
const TemplateArgumentLoc &getDefaultArgument() const {
static const TemplateArgumentLoc NoneLoc;
return DefaultArgument.isSet() ? *DefaultArgument.get() : NoneLoc;
}

/// Retrieve the location of the default argument, if any.
SourceLocation getDefaultArgumentLoc() const;
Expand All @@ -1449,7 +1448,8 @@ class NonTypeTemplateParmDecl final
/// Set the default argument for this template parameter, and
/// whether that default argument was inherited from another
/// declaration.
void setDefaultArgument(Expr *DefArg) { DefaultArgument.set(DefArg); }
void setDefaultArgument(const ASTContext &C,
const TemplateArgumentLoc &DefArg);
void setInheritedDefaultArgument(const ASTContext &C,
NonTypeTemplateParmDecl *Parm) {
DefaultArgument.setInherited(C, Parm);
Expand Down
19 changes: 15 additions & 4 deletions clang/include/clang/AST/ExprCXX.h
Original file line number Diff line number Diff line change
Expand Up @@ -4377,15 +4377,21 @@ class PackIndexingExpr final
// The pack being indexed, followed by the index
Stmt *SubExprs[2];

size_t TransformedExpressions;
// The size of the trailing expressions.
unsigned TransformedExpressions : 31;

LLVM_PREFERRED_TYPE(bool)
unsigned ExpandedToEmptyPack : 1;

PackIndexingExpr(QualType Type, SourceLocation EllipsisLoc,
SourceLocation RSquareLoc, Expr *PackIdExpr, Expr *IndexExpr,
ArrayRef<Expr *> SubstitutedExprs = {})
ArrayRef<Expr *> SubstitutedExprs = {},
bool ExpandedToEmptyPack = false)
: Expr(PackIndexingExprClass, Type, VK_LValue, OK_Ordinary),
EllipsisLoc(EllipsisLoc), RSquareLoc(RSquareLoc),
SubExprs{PackIdExpr, IndexExpr},
TransformedExpressions(SubstitutedExprs.size()) {
TransformedExpressions(SubstitutedExprs.size()),
ExpandedToEmptyPack(ExpandedToEmptyPack) {

auto *Exprs = getTrailingObjects<Expr *>();
std::uninitialized_copy(SubstitutedExprs.begin(), SubstitutedExprs.end(),
Expand All @@ -4408,10 +4414,14 @@ class PackIndexingExpr final
SourceLocation EllipsisLoc,
SourceLocation RSquareLoc, Expr *PackIdExpr,
Expr *IndexExpr, std::optional<int64_t> Index,
ArrayRef<Expr *> SubstitutedExprs = {});
ArrayRef<Expr *> SubstitutedExprs = {},
bool ExpandedToEmptyPack = false);
static PackIndexingExpr *CreateDeserialized(ASTContext &Context,
unsigned NumTransformedExprs);

/// Determine if the expression was expanded to empty.
bool expandsToEmptyPack() const { return ExpandedToEmptyPack; }

/// Determine the location of the 'sizeof' keyword.
SourceLocation getEllipsisLoc() const { return EllipsisLoc; }

Expand Down Expand Up @@ -4445,6 +4455,7 @@ class PackIndexingExpr final
return getTrailingObjects<Expr *>()[*Index];
}

/// Return the trailing expressions, regardless of the expansion.
ArrayRef<Expr *> getExpressions() const {
return {getTrailingObjects<Expr *>(), TransformedExpressions};
}
Expand Down
29 changes: 29 additions & 0 deletions clang/include/clang/AST/OpenACCClause.h
Original file line number Diff line number Diff line change
Expand Up @@ -677,6 +677,35 @@ class OpenACCCreateClause final
ArrayRef<Expr *> VarList, SourceLocation EndLoc);
};

class OpenACCReductionClause final
: public OpenACCClauseWithVarList,
public llvm::TrailingObjects<OpenACCReductionClause, Expr *> {
OpenACCReductionOperator Op;

OpenACCReductionClause(SourceLocation BeginLoc, SourceLocation LParenLoc,
OpenACCReductionOperator Operator,
ArrayRef<Expr *> VarList, SourceLocation EndLoc)
: OpenACCClauseWithVarList(OpenACCClauseKind::Reduction, BeginLoc,
LParenLoc, EndLoc),
Op(Operator) {
std::uninitialized_copy(VarList.begin(), VarList.end(),
getTrailingObjects<Expr *>());
setExprs(MutableArrayRef(getTrailingObjects<Expr *>(), VarList.size()));
}

public:
static bool classof(const OpenACCClause *C) {
return C->getClauseKind() == OpenACCClauseKind::Reduction;
}

static OpenACCReductionClause *
Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc,
OpenACCReductionOperator Operator, ArrayRef<Expr *> VarList,
SourceLocation EndLoc);

OpenACCReductionOperator getReductionOp() const { return Op; }
};

template <class Impl> class OpenACCClauseVisitor {
Impl &getDerived() { return static_cast<Impl &>(*this); }

Expand Down
25 changes: 22 additions & 3 deletions clang/include/clang/AST/RecursiveASTVisitor.h
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
#include "clang/AST/ExprOpenMP.h"
#include "clang/AST/LambdaCapture.h"
#include "clang/AST/NestedNameSpecifier.h"
#include "clang/AST/OpenACCClause.h"
#include "clang/AST/OpenMPClause.h"
#include "clang/AST/Stmt.h"
#include "clang/AST/StmtCXX.h"
Expand Down Expand Up @@ -510,6 +511,7 @@ template <typename Derived> class RecursiveASTVisitor {
bool
TraverseOpenACCAssociatedStmtConstruct(OpenACCAssociatedStmtConstruct *S);
bool VisitOpenACCClauseList(ArrayRef<const OpenACCClause *>);
bool VisitOpenACCClause(const OpenACCClause *);
};

template <typename Derived>
Expand Down Expand Up @@ -1960,7 +1962,7 @@ DEF_TRAVERSE_DECL(TemplateTypeParmDecl, {
TRY_TO(TraverseType(QualType(D->getTypeForDecl(), 0)));
TRY_TO(TraverseTemplateTypeParamDeclConstraints(D));
if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
TRY_TO(TraverseTypeLoc(D->getDefaultArgumentInfo()->getTypeLoc()));
TRY_TO(TraverseTemplateArgumentLoc(D->getDefaultArgument()));
})

DEF_TRAVERSE_DECL(TypedefDecl, {
Expand Down Expand Up @@ -2320,7 +2322,7 @@ DEF_TRAVERSE_DECL(NonTypeTemplateParmDecl, {
// A non-type template parameter, e.g. "S" in template<int S> class Foo ...
TRY_TO(TraverseDeclaratorHelper(D));
if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
TRY_TO(TraverseStmt(D->getDefaultArgument()));
TRY_TO(TraverseTemplateArgumentLoc(D->getDefaultArgument()));
})

DEF_TRAVERSE_DECL(ParmVarDecl, {
Expand Down Expand Up @@ -3967,9 +3969,26 @@ bool RecursiveASTVisitor<Derived>::TraverseOpenACCAssociatedStmtConstruct(
return true;
}

template <typename Derived>
bool RecursiveASTVisitor<Derived>::VisitOpenACCClause(const OpenACCClause *C) {
for (const Stmt *Child : C->children())
TRY_TO(TraverseStmt(const_cast<Stmt *>(Child)));
return true;
}

template <typename Derived>
bool RecursiveASTVisitor<Derived>::VisitOpenACCClauseList(
ArrayRef<const OpenACCClause *>) {
ArrayRef<const OpenACCClause *> Clauses) {

for (const auto *C : Clauses)
TRY_TO(VisitOpenACCClause(C));
// if (const auto *WithCond = dyn_cast<OopenACCClauseWithCondition>(C);
// WithCond && WIthCond->hasConditionExpr()) {
// TRY_TO(TraverseStmt(WithCond->getConditionExpr());
// } else if (const auto *
// }
// OpenACCClauseWithCondition::getConditionExpr/hasConditionExpr
//OpenACCClauseWithExprs::children (might be null?)
// TODO OpenACC: When we have Clauses with expressions, we should visit them
// here.
return true;
Expand Down
5 changes: 5 additions & 0 deletions clang/include/clang/AST/Type.h
Original file line number Diff line number Diff line change
Expand Up @@ -2524,6 +2524,7 @@ class alignas(TypeAlignment) Type : public ExtQualsTypeCommonBase {
bool isVectorType() const; // GCC vector type.
bool isExtVectorType() const; // Extended vector type.
bool isExtVectorBoolType() const; // Extended vector type with bool element.
bool isSubscriptableVectorType() const;
bool isMatrixType() const; // Matrix type.
bool isConstantMatrixType() const; // Constant matrix type.
bool isDependentAddressSpaceType() const; // value-dependent address space qualifier
Expand Down Expand Up @@ -7730,6 +7731,10 @@ inline bool Type::isExtVectorBoolType() const {
return cast<ExtVectorType>(CanonicalType)->getElementType()->isBooleanType();
}

inline bool Type::isSubscriptableVectorType() const {
return isVectorType() || isSveVLSBuiltinType();
}

inline bool Type::isMatrixType() const {
return isa<MatrixType>(CanonicalType);
}
Expand Down
179 changes: 179 additions & 0 deletions clang/include/clang/Analysis/FlowSensitive/CNFFormula.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
//===- CNFFormula.h ---------------------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// A representation of a boolean formula in 3-CNF.
//
//===----------------------------------------------------------------------===//

#ifndef LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_CNFFORMULA_H
#define LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_CNFFORMULA_H

#include <cstdint>
#include <vector>

#include "clang/Analysis/FlowSensitive/Formula.h"

namespace clang {
namespace dataflow {

/// Boolean variables are represented as positive integers.
using Variable = uint32_t;

/// A null boolean variable is used as a placeholder in various data structures
/// and algorithms.
constexpr Variable NullVar = 0;

/// Literals are represented as positive integers. Specifically, for a boolean
/// variable `V` that is represented as the positive integer `I`, the positive
/// literal `V` is represented as the integer `2*I` and the negative literal
/// `!V` is represented as the integer `2*I+1`.
using Literal = uint32_t;

/// A null literal is used as a placeholder in various data structures and
/// algorithms.
constexpr Literal NullLit = 0;

/// Clause identifiers are represented as positive integers.
using ClauseID = uint32_t;

/// A null clause identifier is used as a placeholder in various data structures
/// and algorithms.
constexpr ClauseID NullClause = 0;

/// Returns the positive literal `V`.
inline constexpr Literal posLit(Variable V) { return 2 * V; }

/// Returns the negative literal `!V`.
inline constexpr Literal negLit(Variable V) { return 2 * V + 1; }

/// Returns whether `L` is a positive literal.
inline constexpr bool isPosLit(Literal L) { return 0 == (L & 1); }

/// Returns whether `L` is a negative literal.
inline constexpr bool isNegLit(Literal L) { return 1 == (L & 1); }

/// Returns the negated literal `!L`.
inline constexpr Literal notLit(Literal L) { return L ^ 1; }

/// Returns the variable of `L`.
inline constexpr Variable var(Literal L) { return L >> 1; }

/// A boolean formula in 3-CNF (conjunctive normal form with at most 3 literals
/// per clause).
class CNFFormula {
/// `LargestVar` is equal to the largest positive integer that represents a
/// variable in the formula.
const Variable LargestVar;

/// Literals of all clauses in the formula.
///
/// The element at index 0 stands for the literal in the null clause. It is
/// set to 0 and isn't used. Literals of clauses in the formula start from the
/// element at index 1.
///
/// For example, for the formula `(L1 v L2) ^ (L2 v L3 v L4)` the elements of
/// `Clauses` will be `[0, L1, L2, L2, L3, L4]`.
std::vector<Literal> Clauses;

/// Start indices of clauses of the formula in `Clauses`.
///
/// The element at index 0 stands for the start index of the null clause. It
/// is set to 0 and isn't used. Start indices of clauses in the formula start
/// from the element at index 1.
///
/// For example, for the formula `(L1 v L2) ^ (L2 v L3 v L4)` the elements of
/// `ClauseStarts` will be `[0, 1, 3]`. Note that the literals of the first
/// clause always start at index 1. The start index for the literals of the
/// second clause depends on the size of the first clause and so on.
std::vector<size_t> ClauseStarts;

/// Indicates that we already know the formula is unsatisfiable.
/// During construction, we catch simple cases of conflicting unit-clauses.
bool KnownContradictory;

public:
explicit CNFFormula(Variable LargestVar);

/// Adds the `L1 v ... v Ln` clause to the formula.
/// Requirements:
///
/// `Li` must not be `NullLit`.
///
/// All literals in the input that are not `NullLit` must be distinct.
void addClause(ArrayRef<Literal> lits);

/// Returns whether the formula is known to be contradictory.
/// This is the case if any of the clauses is empty.
bool knownContradictory() const { return KnownContradictory; }

/// Returns the largest variable in the formula.
Variable largestVar() const { return LargestVar; }

/// Returns the number of clauses in the formula.
/// Valid clause IDs are in the range [1, `numClauses()`].
ClauseID numClauses() const { return ClauseStarts.size() - 1; }

/// Returns the number of literals in clause `C`.
size_t clauseSize(ClauseID C) const {
return C == ClauseStarts.size() - 1 ? Clauses.size() - ClauseStarts[C]
: ClauseStarts[C + 1] - ClauseStarts[C];
}

/// Returns the literals of clause `C`.
/// If `knownContradictory()` is false, each clause has at least one literal.
llvm::ArrayRef<Literal> clauseLiterals(ClauseID C) const {
size_t S = clauseSize(C);
if (S == 0)
return llvm::ArrayRef<Literal>();
return llvm::ArrayRef<Literal>(&Clauses[ClauseStarts[C]], S);
}

/// An iterator over all literals of all clauses in the formula.
/// The iterator allows mutation of the literal through the `*` operator.
/// This is to support solvers that mutate the formula during solving.
class Iterator {
friend class CNFFormula;
CNFFormula *CNF;
size_t Idx;
Iterator(CNFFormula *CNF, size_t Idx) : CNF(CNF), Idx(Idx) {}

public:
Iterator(const Iterator &) = default;
Iterator &operator=(const Iterator &) = default;

Iterator &operator++() {
++Idx;
assert(Idx < CNF->Clauses.size() && "Iterator out of bounds");
return *this;
}

Iterator next() const {
Iterator I = *this;
++I;
return I;
}

Literal &operator*() const { return CNF->Clauses[Idx]; }
};
friend class Iterator;

/// Returns an iterator to the first literal of clause `C`.
Iterator startOfClause(ClauseID C) { return Iterator(this, ClauseStarts[C]); }
};

/// Converts the conjunction of `Vals` into a formula in conjunctive normal
/// form where each clause has at least one and at most three literals.
/// `Atomics` is populated with a mapping from `Variables` to the corresponding
/// `Atom`s for atomic booleans in the input formulas.
CNFFormula buildCNF(const llvm::ArrayRef<const Formula *> &Formulas,
llvm::DenseMap<Variable, Atom> &Atomics);

} // namespace dataflow
} // namespace clang

#endif // LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_CNFFORMULA_H
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,17 @@
#include "clang/Analysis/FlowSensitive/Formula.h"
#include "clang/Analysis/FlowSensitive/Solver.h"
#include "llvm/ADT/ArrayRef.h"
#include <limits>

namespace clang {
namespace dataflow {

/// A SAT solver that is an implementation of Algorithm D from Knuth's The Art
/// of Computer Programming Volume 4: Satisfiability, Fascicle 6. It is based on
/// the Davis-Putnam-Logemann-Loveland (DPLL) algorithm, keeps references to a
/// single "watched" literal per clause, and uses a set of "active" variables
/// the Davis-Putnam-Logemann-Loveland (DPLL) algorithm [1], keeps references to
/// a single "watched" literal per clause, and uses a set of "active" variables
/// for unit propagation.
//
// [1] https://en.wikipedia.org/wiki/DPLL_algorithm
class WatchedLiteralsSolver : public Solver {
// Count of the iterations of the main loop of the solver. This spans *all*
// calls to the underlying solver across the life of this object. It is
Expand Down
38 changes: 33 additions & 5 deletions clang/include/clang/Basic/Attr.td
Original file line number Diff line number Diff line change
Expand Up @@ -999,7 +999,7 @@ def Availability : InheritableAttr {
VersionArgument<"deprecated">, VersionArgument<"obsoleted">,
BoolArgument<"unavailable">, StringArgument<"message">,
BoolArgument<"strict">, StringArgument<"replacement">,
IntArgument<"priority">];
IntArgument<"priority">, IdentifierArgument<"environment">];
let AdditionalMembers =
[{static llvm::StringRef getPrettyPlatformName(llvm::StringRef Platform) {
return llvm::StringSwitch<llvm::StringRef>(Platform)
Expand All @@ -1019,7 +1019,7 @@ def Availability : InheritableAttr {
.Case("xros", "visionOS")
.Case("xros_app_extension", "visionOS (App Extension)")
.Case("swift", "Swift")
.Case("shadermodel", "HLSL ShaderModel")
.Case("shadermodel", "Shader Model")
.Case("ohos", "OpenHarmony OS")
.Default(llvm::StringRef());
}
Expand Down Expand Up @@ -1059,7 +1059,34 @@ static llvm::StringRef canonicalizePlatformName(llvm::StringRef Platform) {
.Case("visionos_app_extension", "xros_app_extension")
.Case("ShaderModel", "shadermodel")
.Default(Platform);
} }];
}
static llvm::StringRef getPrettyEnviromentName(llvm::StringRef Environment) {
return llvm::StringSwitch<llvm::StringRef>(Environment)
.Case("pixel", "pixel shader")
.Case("vertex", "vertex shader")
.Case("geometry", "geometry shader")
.Case("hull", "hull shader")
.Case("domain", "domain shader")
.Case("compute", "compute shader")
.Case("mesh", "mesh shader")
.Case("amplification", "amplification shader")
.Case("library", "shader library")
.Default(Environment);
}
static llvm::Triple::EnvironmentType getEnvironmentType(llvm::StringRef Environment) {
return llvm::StringSwitch<llvm::Triple::EnvironmentType>(Environment)
.Case("pixel", llvm::Triple::Pixel)
.Case("vertex", llvm::Triple::Vertex)
.Case("geometry", llvm::Triple::Geometry)
.Case("hull", llvm::Triple::Hull)
.Case("domain", llvm::Triple::Domain)
.Case("compute", llvm::Triple::Compute)
.Case("mesh", llvm::Triple::Mesh)
.Case("amplification", llvm::Triple::Amplification)
.Case("library", llvm::Triple::Library)
.Default(llvm::Triple::UnknownEnvironment);
}
}];
let HasCustomParsing = 1;
let InheritEvenIfAlreadyPresent = 1;
let Subjects = SubjectList<[Named]>;
Expand Down Expand Up @@ -1613,10 +1640,11 @@ def Unlikely : StmtAttr {
def : MutualExclusions<[Likely, Unlikely]>;

def CXXAssume : StmtAttr {
let Spellings = [CXX11<"", "assume", 202207>];
let Spellings = [CXX11<"", "assume", 202207>, Clang<"assume">];
let Subjects = SubjectList<[NullStmt], ErrorDiag, "empty statements">;
let Args = [ExprArgument<"Assumption">];
let Documentation = [CXXAssumeDocs];
let HasCustomParsing = 1;
}

def NoMerge : DeclOrStmtAttr {
Expand Down Expand Up @@ -4229,7 +4257,7 @@ def OMPDeclareVariant : InheritableAttr {
}

def OMPAssume : InheritableAttr {
let Spellings = [Clang<"assume">, CXX11<"omp", "assume">];
let Spellings = [CXX11<"omp", "assume">];
let Subjects = SubjectList<[Function, ObjCMethod]>;
let InheritEvenIfAlreadyPresent = 1;
let Documentation = [OMPAssumeDocs];
Expand Down
12 changes: 7 additions & 5 deletions clang/include/clang/Basic/AttrDocs.td
Original file line number Diff line number Diff line change
Expand Up @@ -1593,6 +1593,11 @@ replacement=\ *string-literal*
a warning about use of a deprecated declaration. The Fix-It will replace
the deprecated declaration with the new declaration specified.

environment=\ *identifier*
Target environment in which this declaration is available. If present,
the availability attribute applies only to targets with the same platform
and environment. The parameter is currently supported only in HLSL.

Multiple availability attributes can be placed on a declaration, which may
correspond to different platforms. For most platforms, the availability
attribute with the platform corresponding to the target platform will be used;
Expand Down Expand Up @@ -2022,9 +2027,6 @@ Different optimisers are likely to react differently to the presence of
this attribute; in some cases, adding ``assume`` may affect performance
negatively. It should be used with parsimony and care.

Note that `clang::assume` is a different attribute. Always write ``assume``
without a namespace if you intend to use the standard C++ attribute.

Example:

.. code-block:: c++
Expand Down Expand Up @@ -4735,7 +4737,7 @@ def OMPAssumeDocs : Documentation {
let Category = DocCatFunction;
let Heading = "assume";
let Content = [{
Clang supports the ``__attribute__((assume("assumption")))`` attribute to
Clang supports the ``[[omp::assume("assumption")]]`` attribute to
provide additional information to the optimizer. The string-literal, here
"assumption", will be attached to the function declaration such that later
analysis and optimization passes can assume the "assumption" to hold.
Expand All @@ -4747,7 +4749,7 @@ A function can have multiple assume attributes and they propagate from prior
declarations to later definitions. Multiple assumptions are aggregated into a
single comma separated string. Thus, one can provide multiple assumptions via
a comma separated string, i.a.,
``__attribute__((assume("assumption1,assumption2")))``.
``[[omp::assume("assumption1,assumption2")]]``.

While LLVM plugins might provide more assumption strings, the default LLVM
optimization passes are aware of the following assumptions:
Expand Down
2 changes: 1 addition & 1 deletion clang/include/clang/Basic/BuiltinsAArch64.def
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,7 @@ TARGET_HEADER_BUILTIN(_CountLeadingZeros64, "UiULLi", "nh", INTRIN_H, ALL_MS_LAN
TARGET_HEADER_BUILTIN(_CountOneBits, "UiUNi", "nh", INTRIN_H, ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(_CountOneBits64, "UiULLi", "nh", INTRIN_H, ALL_MS_LANGUAGES, "")

TARGET_HEADER_BUILTIN(__prefetch, "vv*", "nh", INTRIN_H, ALL_MS_LANGUAGES, "")
TARGET_HEADER_BUILTIN(__prefetch, "vvC*", "nh", INTRIN_H, ALL_MS_LANGUAGES, "")

#undef BUILTIN
#undef LANGBUILTIN
Expand Down
3 changes: 2 additions & 1 deletion clang/include/clang/Basic/BuiltinsAMDGPU.def
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ BUILTIN(__builtin_amdgcn_sched_group_barrier, "vIiIiIi", "n")
BUILTIN(__builtin_amdgcn_iglp_opt, "vIi", "n")
BUILTIN(__builtin_amdgcn_s_dcache_inv, "v", "n")
BUILTIN(__builtin_amdgcn_buffer_wbinvl1, "v", "n")
BUILTIN(__builtin_amdgcn_fence, "vUicC*", "n")
BUILTIN(__builtin_amdgcn_fence, "vUicC*.", "n")
BUILTIN(__builtin_amdgcn_groupstaticsize, "Ui", "n")
BUILTIN(__builtin_amdgcn_wavefrontsize, "Ui", "nc")

Expand Down Expand Up @@ -240,6 +240,7 @@ TARGET_BUILTIN(__builtin_amdgcn_flat_atomic_fadd_v2bf16, "V2sV2s*0V2s", "t", "at
TARGET_BUILTIN(__builtin_amdgcn_global_atomic_fadd_v2bf16, "V2sV2s*1V2s", "t", "atomic-global-pk-add-bf16-inst")
TARGET_BUILTIN(__builtin_amdgcn_ds_atomic_fadd_v2bf16, "V2sV2s*3V2s", "t", "atomic-ds-pk-add-16-insts")
TARGET_BUILTIN(__builtin_amdgcn_ds_atomic_fadd_v2f16, "V2hV2h*3V2h", "t", "atomic-ds-pk-add-16-insts")
TARGET_BUILTIN(__builtin_amdgcn_global_load_lds, "vv*1v*3UiiUi", "t", "gfx940-insts")

//===----------------------------------------------------------------------===//
// Deep learning builtins.
Expand Down
2 changes: 2 additions & 0 deletions clang/include/clang/Basic/BuiltinsWebAssembly.def
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,8 @@ TARGET_BUILTIN(__builtin_wasm_relaxed_dot_bf16x8_add_f32_f32x4, "V4fV8UsV8UsV4f"
// Half-Precision (fp16)
TARGET_BUILTIN(__builtin_wasm_loadf16_f32, "fh*", "nU", "half-precision")
TARGET_BUILTIN(__builtin_wasm_storef16_f32, "vfh*", "n", "half-precision")
TARGET_BUILTIN(__builtin_wasm_splat_f16x8, "V8hf", "nc", "half-precision")
TARGET_BUILTIN(__builtin_wasm_extract_lane_f16x8, "fV8hi", "nc", "half-precision")

// Reference Types builtins
// Some builtins are custom type-checked - see 't' as part of the third argument,
Expand Down
21 changes: 0 additions & 21 deletions clang/include/clang/Basic/BuiltinsX86.def
Original file line number Diff line number Diff line change
Expand Up @@ -832,23 +832,11 @@ TARGET_BUILTIN(__builtin_ia32_rsqrt14ss_mask, "V4fV4fV4fV4fUc", "ncV:128:", "avx
TARGET_BUILTIN(__builtin_ia32_rsqrt14pd512_mask, "V8dV8dV8dUc", "ncV:512:", "avx512f,evex512")
TARGET_BUILTIN(__builtin_ia32_rsqrt14ps512_mask, "V16fV16fV16fUs", "ncV:512:", "avx512f,evex512")

TARGET_BUILTIN(__builtin_ia32_rsqrt28sd_round_mask, "V2dV2dV2dV2dUcIi", "ncV:128:", "avx512er")
TARGET_BUILTIN(__builtin_ia32_rsqrt28ss_round_mask, "V4fV4fV4fV4fUcIi", "ncV:128:", "avx512er")
TARGET_BUILTIN(__builtin_ia32_rsqrt28pd_mask, "V8dV8dV8dUcIi", "ncV:512:", "avx512er,evex512")
TARGET_BUILTIN(__builtin_ia32_rsqrt28ps_mask, "V16fV16fV16fUsIi", "ncV:512:", "avx512er,evex512")

TARGET_BUILTIN(__builtin_ia32_rcp14sd_mask, "V2dV2dV2dV2dUc", "ncV:128:", "avx512f")
TARGET_BUILTIN(__builtin_ia32_rcp14ss_mask, "V4fV4fV4fV4fUc", "ncV:128:", "avx512f")
TARGET_BUILTIN(__builtin_ia32_rcp14pd512_mask, "V8dV8dV8dUc", "ncV:512:", "avx512f,evex512")
TARGET_BUILTIN(__builtin_ia32_rcp14ps512_mask, "V16fV16fV16fUs", "ncV:512:", "avx512f,evex512")

TARGET_BUILTIN(__builtin_ia32_rcp28sd_round_mask, "V2dV2dV2dV2dUcIi", "ncV:128:", "avx512er")
TARGET_BUILTIN(__builtin_ia32_rcp28ss_round_mask, "V4fV4fV4fV4fUcIi", "ncV:128:", "avx512er")
TARGET_BUILTIN(__builtin_ia32_rcp28pd_mask, "V8dV8dV8dUcIi", "ncV:512:", "avx512er,evex512")
TARGET_BUILTIN(__builtin_ia32_rcp28ps_mask, "V16fV16fV16fUsIi", "ncV:512:", "avx512er,evex512")
TARGET_BUILTIN(__builtin_ia32_exp2pd_mask, "V8dV8dV8dUcIi", "ncV:512:", "avx512er,evex512")
TARGET_BUILTIN(__builtin_ia32_exp2ps_mask, "V16fV16fV16fUsIi", "ncV:512:", "avx512er,evex512")

TARGET_BUILTIN(__builtin_ia32_cvttps2dq512_mask, "V16iV16fV16iUsIi", "ncV:512:", "avx512f,evex512")
TARGET_BUILTIN(__builtin_ia32_cvttps2udq512_mask, "V16iV16fV16iUsIi", "ncV:512:", "avx512f,evex512")
TARGET_BUILTIN(__builtin_ia32_cvttpd2dq512_mask, "V8iV8dV8iUcIi", "ncV:512:", "avx512f,evex512")
Expand Down Expand Up @@ -960,15 +948,6 @@ TARGET_BUILTIN(__builtin_ia32_scattersiv16si, "vv*UsV16iV16iIi", "nV:512:", "avx
TARGET_BUILTIN(__builtin_ia32_scatterdiv8di, "vv*UcV8OiV8OiIi", "nV:512:", "avx512f,evex512")
TARGET_BUILTIN(__builtin_ia32_scatterdiv16si, "vv*UcV8OiV8iIi", "nV:512:", "avx512f,evex512")

TARGET_BUILTIN(__builtin_ia32_gatherpfdpd, "vUcV8ivC*IiIi", "nV:512:", "avx512pf,evex512")
TARGET_BUILTIN(__builtin_ia32_gatherpfdps, "vUsV16ivC*IiIi", "nV:512:", "avx512pf,evex512")
TARGET_BUILTIN(__builtin_ia32_gatherpfqpd, "vUcV8OivC*IiIi", "nV:512:", "avx512pf,evex512")
TARGET_BUILTIN(__builtin_ia32_gatherpfqps, "vUcV8OivC*IiIi", "nV:512:", "avx512pf,evex512")
TARGET_BUILTIN(__builtin_ia32_scatterpfdpd, "vUcV8iv*IiIi", "nV:512:", "avx512pf,evex512")
TARGET_BUILTIN(__builtin_ia32_scatterpfdps, "vUsV16iv*IiIi", "nV:512:", "avx512pf,evex512")
TARGET_BUILTIN(__builtin_ia32_scatterpfqpd, "vUcV8Oiv*IiIi", "nV:512:", "avx512pf,evex512")
TARGET_BUILTIN(__builtin_ia32_scatterpfqps, "vUcV8Oiv*IiIi", "nV:512:", "avx512pf,evex512")

TARGET_BUILTIN(__builtin_ia32_knotqi, "UcUc", "nc", "avx512dq")
TARGET_BUILTIN(__builtin_ia32_knothi, "UsUs", "nc", "avx512f")
TARGET_BUILTIN(__builtin_ia32_knotsi, "UiUi", "nc", "avx512bw")
Expand Down
3 changes: 0 additions & 3 deletions clang/include/clang/Basic/DiagnosticCommonKinds.td
Original file line number Diff line number Diff line change
Expand Up @@ -361,9 +361,6 @@ def warn_invalid_feature_combination : Warning<
def warn_target_unrecognized_env : Warning<
"mismatch between architecture and environment in target triple '%0'; did you mean '%1'?">,
InGroup<InvalidCommandLineArgument>;
def warn_knl_knm_isa_support_removed : Warning<
"KNL, KNM related Intel Xeon Phi CPU's specific ISA's supports will be removed in LLVM 19.">,
InGroup<DiagGroup<"knl-knm-isa-support-removed">>;
def err_target_unsupported_abi_with_fpu : Error<
"'%0' ABI is not supported with FPU">;

Expand Down
61 changes: 25 additions & 36 deletions clang/include/clang/Basic/DiagnosticDriverKinds.td
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ def warn_drv_avr_stdlib_not_linked: Warning<
def err_drv_cuda_bad_gpu_arch : Error<"unsupported CUDA gpu architecture: %0">;
def err_drv_offload_bad_gpu_arch : Error<"unsupported %0 gpu architecture: %1">;
def err_drv_offload_missing_gpu_arch : Error<
"Must pass in an explicit %0 gpu architecture to '%1'">;
"must pass in an explicit %0 gpu architecture to '%1'">;
def err_drv_no_cuda_installation : Error<
"cannot find CUDA installation; provide its path via '--cuda-path', or pass "
"'-nocudainc' to build without CUDA includes">;
Expand Down Expand Up @@ -90,8 +90,8 @@ def err_drv_no_hipspv_device_lib : Error<
"'--hip-path' or '--hip-device-lib-path', or pass '-nogpulib' to build "
"without HIP device library">;
def err_drv_hipspv_no_hip_path : Error<
"'--hip-path' must be specified when offloading to "
"SPIR-V%select{| unless %1 is given}0.">;
"'--hip-path' must be specified when offloading to SPIR-V unless '-nogpuinc' "
"is given">;

// TODO: Remove when COV6 is fully supported by ROCm.
def warn_drv_amdgpu_cov6: Warning<
Expand Down Expand Up @@ -137,13 +137,13 @@ def warn_drv_unsupported_option_for_flang : Warning<
"the argument '%0' is not supported for option '%1'. Mapping to '%1%2'">,
InGroup<OptionIgnored>;
def warn_drv_unsupported_diag_option_for_flang : Warning<
"The warning option '-%0' is not supported">,
"the warning option '-%0' is not supported">,
InGroup<OptionIgnored>;
def warn_drv_unsupported_option_for_processor : Warning<
"ignoring '%0' option as it is not currently supported for processor '%1'">,
InGroup<OptionIgnored>;
def warn_drv_unsupported_openmp_library : Warning<
"The library '%0=%1' is not supported, openmp is not be enabled">,
"the library '%0=%1' is not supported, OpenMP will not be enabled">,
InGroup<OptionIgnored>;

def err_drv_invalid_thread_model_for_target : Error<
Expand Down Expand Up @@ -356,7 +356,7 @@ def err_drv_expecting_fopenmp_with_fopenmp_targets : Error<
"compatible with offloading; e.g., '-fopenmp=libomp' or '-fopenmp=libiomp5'">;
def err_drv_failed_to_deduce_target_from_arch : Error<
"failed to deduce triple for target architecture '%0'; specify the triple "
"using '-fopenmp-targets' and '-Xopenmp-target' instead.">;
"using '-fopenmp-targets' and '-Xopenmp-target' instead">;
def err_drv_omp_offload_target_missingbcruntime : Error<
"no library '%0' found in the default clang lib directory or in LIBRARY_PATH"
"; use '--libomptarget-%1-bc-path' to specify %1 bitcode library">;
Expand Down Expand Up @@ -515,14 +515,6 @@ def err_analyzer_checker_incompatible_analyzer_option : Error<
def err_analyzer_not_built_with_z3 : Error<
"analyzer constraint manager 'z3' is only available if LLVM was built with "
"-DLLVM_ENABLE_Z3_SOLVER=ON">;
def warn_analyzer_deprecated_option : Warning<
"analyzer option '%0' is deprecated. This flag will be removed in %1, and "
"passing this option will be an error.">,
InGroup<DeprecatedStaticAnalyzerFlag>;
def warn_analyzer_deprecated_option_with_alternative : Warning<
"analyzer option '%0' is deprecated. This flag will be removed in %1, and "
"passing this option will be an error. Use '%2' instead.">,
InGroup<DeprecatedStaticAnalyzerFlag>;

def warn_drv_needs_hvx : Warning<
"%0 requires HVX, use -mhvx/-mhvx= to enable it">,
Expand Down Expand Up @@ -555,10 +547,12 @@ def err_drv_extract_api_wrong_kind : Error<
"in api extraction; use '-x %2' to override">;

def err_drv_missing_symbol_graph_dir: Error<
"Must provide a symbol graph output directory using --symbol-graph-dir=<directory>">;
"must provide a symbol graph output directory using "
"'--symbol-graph-dir=<directory>'">;

def err_drv_unexpected_symbol_graph_output : Error<
"Unexpected output symbol graph '%1'; please provide --symbol-graph-dir=<directory> instead">;
"unexpected output symbol graph '%1'; please provide "
"'--symbol-graph-dir=<directory>' instead">;

def warn_slash_u_filename : Warning<"'/U%0' treated as the '/U' option">,
InGroup<DiagGroup<"slash-u-filename">>;
Expand Down Expand Up @@ -599,9 +593,6 @@ def warn_drv_unsupported_gpopt : Warning<
"ignoring '-mgpopt' option as it cannot be used with %select{|the implicit"
" usage of }0-mabicalls">,
InGroup<UnsupportedGPOpt>;
def warn_drv_unsupported_tocdata: Warning<
"ignoring '-mtocdata' as it is only supported for -mcmodel=small">,
InGroup<OptionIgnored>;
def warn_drv_unsupported_sdata : Warning<
"ignoring '-msmall-data-limit=' with -mcmodel=large for -fpic or RV64">,
InGroup<OptionIgnored>;
Expand Down Expand Up @@ -770,19 +761,19 @@ def err_drv_hlsl_16bit_types_unsupported: Error<
"'%0' option requires target HLSL Version >= 2018%select{| and shader model >= 6.2}1, but HLSL Version is '%2'%select{| and shader model is '%3'}1">;
def err_drv_hlsl_bad_shader_unsupported : Error<
"%select{shader model|Vulkan environment|shader stage}0 '%1' in target '%2' is invalid for HLSL code generation">;
def warn_drv_dxc_missing_dxv : Warning<"dxv not found. "
"Resulting DXIL will not be validated or signed for use in release environments.">,
InGroup<DXILValidation>;
def warn_drv_dxc_missing_dxv : Warning<
"dxv not found; resulting DXIL will not be validated or signed for use in "
"release environment">, InGroup<DXILValidation>;

def err_drv_invalid_range_dxil_validator_version : Error<
"invalid validator version : %0\n"
"Validator version must be less than or equal to current internal version.">;
"invalid validator version : %0; validator version must be less than or "
"equal to current internal version">;
def err_drv_invalid_format_dxil_validator_version : Error<
"invalid validator version : %0\n"
"Format of validator version is \"<major>.<minor>\" (ex:\"1.4\").">;
"invalid validator version : %0; format of validator version is "
"\"<major>.<minor>\" (ex:\"1.4\")">;
def err_drv_invalid_empty_dxil_validator_version : Error<
"invalid validator version : %0\n"
"If validator major version is 0, minor version must also be 0.">;
"invalid validator version : %0; if validator major version is 0, minor "
"version must also be 0">;

def warn_drv_sarif_format_unstable : Warning<
"diagnostic formatting in SARIF mode is currently unstable">,
Expand All @@ -796,12 +787,10 @@ def warn_drv_loongarch_conflicting_implied_val : Warning<
InGroup<OptionIgnored>;
def err_drv_loongarch_invalid_mfpu_EQ : Error<
"invalid argument '%0' to -mfpu=; must be one of: 64, 32, none, 0 (alias for none)">;
def err_drv_loongarch_wrong_fpu_width_for_lsx : Error<
"wrong fpu width; LSX depends on 64-bit FPU.">;
def err_drv_loongarch_wrong_fpu_width_for_lasx : Error<
"wrong fpu width; LASX depends on 64-bit FPU.">;
def err_drv_loongarch_wrong_fpu_width : Error<
"wrong fpu width; %select{LSX|LASX}0 depends on 64-bit FPU">;
def err_drv_loongarch_invalid_simd_option_combination : Error<
"invalid option combination; LASX depends on LSX.">;
"invalid option combination; LASX depends on LSX">;

def err_drv_expand_response_file : Error<
"failed to expand response file: %0">;
Expand All @@ -813,9 +802,9 @@ def note_drv_available_multilibs : Note<
"available multilibs are:%0">;

def warn_android_unversioned_fallback : Warning<
"Using unversioned Android target directory %0 for target %1. Unversioned"
" directories will not be used in Clang 19. Provide a versioned directory"
" for the target version or lower instead.">,
"using unversioned Android target directory %0 for target %1; unversioned "
"directories will not be used in Clang 19 -- provide a versioned directory "
"for the target version or lower instead">,
InGroup<DiagGroup<"android-unversioned-fallback">>;

def err_drv_triple_version_invalid : Error<
Expand Down
23 changes: 11 additions & 12 deletions clang/include/clang/Basic/DiagnosticFrontendKinds.td
Original file line number Diff line number Diff line change
Expand Up @@ -71,14 +71,14 @@ def remark_fe_backend_optimization_remark_analysis : Remark<"%0">, BackendInfo,
InGroup<BackendOptimizationRemarkAnalysis>;
def remark_fe_backend_optimization_remark_analysis_fpcommute : Remark<"%0; "
"allow reordering by specifying '#pragma clang loop vectorize(enable)' "
"before the loop or by providing the compiler option '-ffast-math'.">,
"before the loop or by providing the compiler option '-ffast-math'">,
BackendInfo, InGroup<BackendOptimizationRemarkAnalysis>;
def remark_fe_backend_optimization_remark_analysis_aliasing : Remark<"%0; "
"allow reordering by specifying '#pragma clang loop vectorize(enable)' "
"before the loop. If the arrays will always be independent specify "
"before the loop; if the arrays will always be independent, specify "
"'#pragma clang loop vectorize(assume_safety)' before the loop or provide "
"the '__restrict__' qualifier with the independent array arguments. "
"Erroneous results will occur if these options are incorrectly applied!">,
"the '__restrict__' qualifier with the independent array arguments -- "
"erroneous results will occur if these options are incorrectly applied">,
BackendInfo, InGroup<BackendOptimizationRemarkAnalysis>;

def warn_fe_backend_optimization_failure : Warning<"%0">, BackendInfo,
Expand Down Expand Up @@ -152,8 +152,8 @@ def warn_fe_serialized_diag_merge_failure : Warning<
def warn_fe_serialized_diag_failure : Warning<
"unable to open file %0 for serializing diagnostics (%1)">,
InGroup<SerializedDiagnostics>;
def warn_fe_serialized_diag_failure_during_finalisation : Warning<
"Received warning after diagnostic serialization teardown was underway: %0">,
def warn_fe_serialized_diag_failure_during_finalization : Warning<
"received warning after diagnostic serialization teardown was underway: %0">,
InGroup<SerializedDiagnostics>;

def err_verify_missing_line : Error<
Expand Down Expand Up @@ -337,7 +337,7 @@ def warn_atomic_op_oversized : Warning<
InGroup<AtomicAlignment>;

def warn_sync_op_misaligned : Warning<
"__sync builtin operation MUST have natural alignment (consider using __atomic).">,
"__sync builtin operation must have natural alignment (consider using __atomic)">,
InGroup<SyncAlignment>;

def warn_alias_with_section : Warning<
Expand All @@ -359,17 +359,16 @@ def warn_profile_data_unprofiled : Warning<
"no profile data available for file \"%0\"">,
InGroup<ProfileInstrUnprofiled>;
def warn_profile_data_misexpect : Warning<
"Potential performance regression from use of __builtin_expect(): "
"Annotation was correct on %0 of profiled executions.">,
BackendInfo,
InGroup<MisExpect>;
"potential performance regression from use of __builtin_expect(): "
"annotation was correct on %0 of profiled executions">,
BackendInfo, InGroup<MisExpect>;
} // end of instrumentation issue category

def err_extract_api_ignores_file_not_found :
Error<"file '%0' specified by '--extract-api-ignores=' not found">, DefaultFatal;

def warn_missing_symbol_graph_dir : Warning<
"Missing symbol graph output directory, defaulting to working directory">,
"missing symbol graph output directory, defaulting to working directory">,
InGroup<ExtractAPIMisuse>;

def err_ast_action_on_llvm_ir : Error<
Expand Down
2 changes: 0 additions & 2 deletions clang/include/clang/Basic/DiagnosticGroups.td
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@ def Implicit : DiagGroup<"implicit", [
ImplicitInt
]>;

def DeprecatedStaticAnalyzerFlag : DiagGroup<"deprecated-static-analyzer-flag">;

// Empty DiagGroups are recognized by clang but ignored.
def ODR : DiagGroup<"odr">;
def : DiagGroup<"abi">;
Expand Down
6 changes: 3 additions & 3 deletions clang/include/clang/Basic/DiagnosticInstallAPIKinds.td
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def err_no_matching_target : Error<"no matching target found for target variant
def err_unsupported_vendor : Error<"vendor '%0' is not supported: '%1'">;
def err_unsupported_environment : Error<"environment '%0' is not supported: '%1'">;
def err_unsupported_os : Error<"os '%0' is not supported: '%1'">;
def err_cannot_read_input_list : Error<"could not read %select{alias list|filelist}0 '%1': %2">;
def err_cannot_read_input_list : Error<"could not read %0 input list '%1': %2">;
def err_invalid_label: Error<"label '%0' is reserved: use a different label name for -X<label>">;
} // end of command line category.

Expand Down Expand Up @@ -59,8 +59,8 @@ def err_platform_mismatch : Error<"platform does not match: '%0' (provided) vs '
def err_install_name_mismatch : Error<"install_name does not match: '%0' (provided) vs '%1' (found)">;
def err_current_version_mismatch : Error<"current_version does not match: '%0' (provided) vs '%1' (found)">;
def err_compatibility_version_mismatch : Error<"compatibility_version does not match: '%0' (provided) vs '%1' (found)">;
def err_appextension_safe_mismatch : Error<"ApplicationExtensionSafe flag does not match: '%0' (provided) vs '%1' (found)">;
def err_shared_cache_eligiblity_mismatch : Error<"NotForDyldSharedCache flag does not match: '%0' (provided) vs '%1' (found)">;
def err_appextension_safe_mismatch : Error<"the ApplicationExtensionSafe flag does not match: '%0' (provided) vs '%1' (found)">;
def err_shared_cache_eligiblity_mismatch : Error<"the NotForDyldSharedCache flag does not match: '%0' (provided) vs '%1' (found)">;
def err_no_twolevel_namespace : Error<"flat namespace libraries are not supported">;
def err_parent_umbrella_missing: Error<"parent umbrella missing from %0: '%1'">;
def err_parent_umbrella_mismatch : Error<"parent umbrella does not match: '%0' (provided) vs '%1' (found)">;
Expand Down
2 changes: 1 addition & 1 deletion clang/include/clang/Basic/DiagnosticLexKinds.td
Original file line number Diff line number Diff line change
Expand Up @@ -991,5 +991,5 @@ def err_pp_unclosed_pragma_unsafe_buffer_usage :
Error<"'#pragma unsafe_buffer_usage' was not ended">;

def err_pp_pragma_unsafe_buffer_usage_syntax :
Error<"Expected 'begin' or 'end'">;
Error<"expected 'begin' or 'end'">;
}
8 changes: 5 additions & 3 deletions clang/include/clang/Basic/DiagnosticParseKinds.td
Original file line number Diff line number Diff line change
Expand Up @@ -1112,10 +1112,12 @@ 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'">;
def err_availability_expected_environment : Error<
"expected an environment name, e.g., 'compute'">;

// objc_bridge_related attribute
def err_objcbridge_related_expected_related_class : Error<
"expected a related ObjectiveC class name, e.g., 'NSColor'">;
"expected a related Objective-C class name, e.g., 'NSColor'">;
def err_objcbridge_related_selector_name : Error<
"expected a class method selector with single argument, e.g., 'colorWithCGColor:'">;

Expand Down Expand Up @@ -1343,8 +1345,8 @@ def note_pragma_attribute_namespace_on_attribute : Note<
"omit the namespace to add attributes to the most-recently"
" pushed attribute group">;
def warn_no_support_for_eval_method_source_on_m32 : Warning<
"Setting the floating point evaluation method to `source` on a target"
" without SSE is not supported.">, InGroup<Pragmas>;
"setting the floating point evaluation method to `source` on a target "
"without SSE is not supported">, InGroup<Pragmas>;
// - #pragma __debug
def warn_pragma_debug_dependent_argument : Warning<
"%select{value|type}0-dependent expression passed as an argument to debug "
Expand Down
113 changes: 69 additions & 44 deletions clang/include/clang/Basic/DiagnosticSemaKinds.td

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions clang/include/clang/Basic/FileManager.h
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,8 @@ class FileManager : public RefCountedBase<FileManager> {
getBufferForFileImpl(StringRef Filename, int64_t FileSize, bool isVolatile,
bool RequiresNullTerminator) const;

DirectoryEntry *&getRealDirEntry(const llvm::vfs::Status &Status);

public:
/// Get the 'stat' information for the given \p Path.
///
Expand Down
1 change: 1 addition & 0 deletions clang/include/clang/Basic/LangOptions.def
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,7 @@ LANGOPT(HIPStdParInterposeAlloc, 1, 0, "Replace allocations / deallocations with

LANGOPT(OpenACC , 1, 0, "OpenACC Enabled")

LANGOPT(MSVCEnableStdcMacro , 1, 0, "Define __STDC__ with '-fms-compatibility'")
LANGOPT(SizedDeallocation , 1, 0, "sized deallocation")
LANGOPT(AlignedAllocation , 1, 0, "aligned allocation")
LANGOPT(AlignedAllocationUnavailable, 1, 0, "aligned allocation functions are unavailable")
Expand Down
1 change: 1 addition & 0 deletions clang/include/clang/Basic/OpenACCClauses.def
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ VISIT_CLAUSE(NumGangs)
VISIT_CLAUSE(NumWorkers)
VISIT_CLAUSE(Present)
VISIT_CLAUSE(Private)
VISIT_CLAUSE(Reduction)
VISIT_CLAUSE(Self)
VISIT_CLAUSE(VectorLength)
VISIT_CLAUSE(Wait)
Expand Down
36 changes: 36 additions & 0 deletions clang/include/clang/Basic/OpenACCKinds.h
Original file line number Diff line number Diff line change
Expand Up @@ -514,6 +514,42 @@ enum class OpenACCReductionOperator {
/// Invalid Reduction Clause Kind.
Invalid,
};

template <typename StreamTy>
inline StreamTy &printOpenACCReductionOperator(StreamTy &Out,
OpenACCReductionOperator Op) {
switch (Op) {
case OpenACCReductionOperator::Addition:
return Out << "+";
case OpenACCReductionOperator::Multiplication:
return Out << "*";
case OpenACCReductionOperator::Max:
return Out << "max";
case OpenACCReductionOperator::Min:
return Out << "min";
case OpenACCReductionOperator::BitwiseAnd:
return Out << "&";
case OpenACCReductionOperator::BitwiseOr:
return Out << "|";
case OpenACCReductionOperator::BitwiseXOr:
return Out << "^";
case OpenACCReductionOperator::And:
return Out << "&&";
case OpenACCReductionOperator::Or:
return Out << "||";
case OpenACCReductionOperator::Invalid:
return Out << "<invalid>";
}
llvm_unreachable("Unknown reduction operator kind");
}
inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &Out,
OpenACCReductionOperator Op) {
return printOpenACCReductionOperator(Out, Op);
}
inline llvm::raw_ostream &operator<<(llvm::raw_ostream &Out,
OpenACCReductionOperator Op) {
return printOpenACCReductionOperator(Out, Op);
}
} // namespace clang

#endif // LLVM_CLANG_BASIC_OPENACCKINDS_H
6 changes: 3 additions & 3 deletions clang/include/clang/Basic/arm_sve.td
Original file line number Diff line number Diff line change
Expand Up @@ -2186,9 +2186,6 @@ let TargetGuard = "sme2" in {

def SVSQRSHRUN_X4 : SInst<"svqrshrun[_n]_{0}[_{d}_x4]", "b4i", "il", MergeNone, "aarch64_sve_sqrshrun_x4", [IsStreaming], [ImmCheck<1, ImmCheckShiftRight, 0>]>;

def REINTERPRET_SVBOOL_TO_SVCOUNT : Inst<"svreinterpret[_c]", "}P", "Pc", MergeNone, "", [IsStreamingCompatible], []>;
def REINTERPRET_SVCOUNT_TO_SVBOOL : Inst<"svreinterpret[_b]", "P}", "Pc", MergeNone, "", [IsStreamingCompatible], []>;

// SQDMULH
def SVSQDMULH_SINGLE_X2 : SInst<"svqdmulh[_single_{d}_x2]", "22d", "csil", MergeNone, "aarch64_sve_sqdmulh_single_vgx2", [IsStreaming], []>;
def SVSQDMULH_SINGLE_X4 : SInst<"svqdmulh[_single_{d}_x4]", "44d", "csil", MergeNone, "aarch64_sve_sqdmulh_single_vgx4", [IsStreaming], []>;
Expand All @@ -2197,6 +2194,9 @@ let TargetGuard = "sme2" in {
}

let TargetGuard = "sve2p1|sme2" in {
def REINTERPRET_SVBOOL_TO_SVCOUNT : Inst<"svreinterpret[_c]", "}P", "Pc", MergeNone, "", [IsStreamingCompatible], []>;
def REINTERPRET_SVCOUNT_TO_SVBOOL : Inst<"svreinterpret[_b]", "P}", "Pc", MergeNone, "", [IsStreamingCompatible], []>;

// SQRSHRN / UQRSHRN
def SVQRSHRN_X2 : SInst<"svqrshrn[_n]_{0}[_{d}_x2]", "h2i", "i", MergeNone, "aarch64_sve_sqrshrn_x2", [IsStreamingCompatible], [ImmCheck<1, ImmCheck1_16>]>;
def SVUQRSHRN_X2 : SInst<"svqrshrn[_n]_{0}[_{d}_x2]", "e2i", "Ui", MergeNone, "aarch64_sve_uqrshrn_x2", [IsStreamingCompatible], [ImmCheck<1, ImmCheck1_16>]>;
Expand Down
21 changes: 11 additions & 10 deletions clang/include/clang/Driver/Options.td
Original file line number Diff line number Diff line change
Expand Up @@ -603,6 +603,7 @@ class MarshallingInfoVisibility<KeyPathAndMacro kpm, code default>
// Key paths that are constant during parsing of options with the same key path prefix.
defvar cplusplus = LangOpts<"CPlusPlus">;
defvar cpp11 = LangOpts<"CPlusPlus11">;
defvar cpp14 = LangOpts<"CPlusPlus14">;
defvar cpp17 = LangOpts<"CPlusPlus17">;
defvar cpp20 = LangOpts<"CPlusPlus20">;
defvar c99 = LangOpts<"C99">;
Expand Down Expand Up @@ -2980,6 +2981,10 @@ def fms_compatibility : Flag<["-"], "fms-compatibility">, Group<f_Group>,
Visibility<[ClangOption, CC1Option, CLOption]>,
HelpText<"Enable full Microsoft Visual C++ compatibility">,
MarshallingInfoFlag<LangOpts<"MSVCCompat">>;
def fms_define_stdc : Flag<["-"], "fms-define-stdc">, Group<f_Group>,
Visibility<[ClangOption, CC1Option, CLOption]>,
HelpText<"Define '__STDC__' to '1' in MSVC Compatibility mode">,
MarshallingInfoFlag<LangOpts<"MSVCEnableStdcMacro">>;
def fms_extensions : Flag<["-"], "fms-extensions">, Group<f_Group>,
Visibility<[ClangOption, CC1Option, CLOption]>,
HelpText<"Accept some non-standard constructs supported by the Microsoft compiler">,
Expand Down Expand Up @@ -3388,10 +3393,9 @@ defm relaxed_template_template_args : BoolFOption<"relaxed-template-template-arg
NegFlag<SetFalse, [], [CC1Option], "Disable">,
BothFlags<[], [ClangOption], " C++17 relaxed template template argument matching">>;
defm sized_deallocation : BoolFOption<"sized-deallocation",
LangOpts<"SizedDeallocation">, DefaultFalse,
PosFlag<SetTrue, [], [ClangOption, CC1Option],
"Enable C++14 sized global deallocation functions">,
NegFlag<SetFalse>>;
LangOpts<"SizedDeallocation">, Default<cpp14.KeyPath>,
PosFlag<SetTrue, [], [], "Enable C++14 sized global deallocation functions">,
NegFlag<SetFalse>, BothFlags<[], [ClangOption, CC1Option]>>;
defm aligned_allocation : BoolFOption<"aligned-allocation",
LangOpts<"AlignedAllocation">, Default<cpp17.KeyPath>,
PosFlag<SetTrue, [], [ClangOption], "Enable C++17 aligned allocation functions">,
Expand Down Expand Up @@ -6111,14 +6115,10 @@ def mavx512cd : Flag<["-"], "mavx512cd">, Group<m_x86_Features_Group>;
def mno_avx512cd : Flag<["-"], "mno-avx512cd">, Group<m_x86_Features_Group>;
def mavx512dq : Flag<["-"], "mavx512dq">, Group<m_x86_Features_Group>;
def mno_avx512dq : Flag<["-"], "mno-avx512dq">, Group<m_x86_Features_Group>;
def mavx512er : Flag<["-"], "mavx512er">, Group<m_x86_Features_Group>;
def mno_avx512er : Flag<["-"], "mno-avx512er">, Group<m_x86_Features_Group>;
def mavx512fp16 : Flag<["-"], "mavx512fp16">, Group<m_x86_Features_Group>;
def mno_avx512fp16 : Flag<["-"], "mno-avx512fp16">, Group<m_x86_Features_Group>;
def mavx512ifma : Flag<["-"], "mavx512ifma">, Group<m_x86_Features_Group>;
def mno_avx512ifma : Flag<["-"], "mno-avx512ifma">, Group<m_x86_Features_Group>;
def mavx512pf : Flag<["-"], "mavx512pf">, Group<m_x86_Features_Group>;
def mno_avx512pf : Flag<["-"], "mno-avx512pf">, Group<m_x86_Features_Group>;
def mavx512vbmi : Flag<["-"], "mavx512vbmi">, Group<m_x86_Features_Group>;
def mno_avx512vbmi : Flag<["-"], "mno-avx512vbmi">, Group<m_x86_Features_Group>;
def mavx512vbmi2 : Flag<["-"], "mavx512vbmi2">, Group<m_x86_Features_Group>;
Expand Down Expand Up @@ -6209,8 +6209,6 @@ def mpopcnt : Flag<["-"], "mpopcnt">, Group<m_x86_Features_Group>;
def mno_popcnt : Flag<["-"], "mno-popcnt">, Group<m_x86_Features_Group>;
def mprefetchi : Flag<["-"], "mprefetchi">, Group<m_x86_Features_Group>;
def mno_prefetchi : Flag<["-"], "mno-prefetchi">, Group<m_x86_Features_Group>;
def mprefetchwt1 : Flag<["-"], "mprefetchwt1">, Group<m_x86_Features_Group>;
def mno_prefetchwt1 : Flag<["-"], "mno-prefetchwt1">, Group<m_x86_Features_Group>;
def mprfchw : Flag<["-"], "mprfchw">, Group<m_x86_Features_Group>;
def mno_prfchw : Flag<["-"], "mno-prfchw">, Group<m_x86_Features_Group>;
def mptwrite : Flag<["-"], "mptwrite">, Group<m_x86_Features_Group>;
Expand Down Expand Up @@ -8312,6 +8310,9 @@ def _SLASH_vd : CLJoined<"vd">, HelpText<"Control vtordisp placement">,
Alias<vtordisp_mode_EQ>;
def _SLASH_X : CLFlag<"X">,
HelpText<"Do not add %INCLUDE% to include search path">, Alias<nostdlibinc>;
def _SLASH_Zc___STDC__ : CLFlag<"Zc:__STDC__">,
HelpText<"Define __STDC__">,
Alias<fms_define_stdc>;
def _SLASH_Zc_sizedDealloc : CLFlag<"Zc:sizedDealloc">,
HelpText<"Enable C++14 sized global deallocation functions">,
Alias<fsized_deallocation>;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,8 @@ class SymbolGraphSerializer : public APISetVisitor<SymbolGraphSerializer> {

const bool EmitSymbolLabelsForTesting = false;

const bool SkipSymbolsInCategoriesToExternalTypes = false;

/// The object instantiated by the last call to serializeAPIRecord.
Object *CurrentSymbol = nullptr;

Expand Down Expand Up @@ -271,10 +273,13 @@ class SymbolGraphSerializer : public APISetVisitor<SymbolGraphSerializer> {

SymbolGraphSerializer(const APISet &API, const APIIgnoresList &IgnoresList,
bool EmitSymbolLabelsForTesting = false,
bool ForceEmitToMainModule = false)
bool ForceEmitToMainModule = false,
bool SkipSymbolsInCategoriesToExternalTypes = false)
: Base(API), ForceEmitToMainModule(ForceEmitToMainModule),
IgnoresList(IgnoresList),
EmitSymbolLabelsForTesting(EmitSymbolLabelsForTesting) {}
EmitSymbolLabelsForTesting(EmitSymbolLabelsForTesting),
SkipSymbolsInCategoriesToExternalTypes(
SkipSymbolsInCategoriesToExternalTypes) {}
};

} // namespace extractapi
Expand Down
25 changes: 15 additions & 10 deletions clang/include/clang/Format/Format.h
Original file line number Diff line number Diff line change
Expand Up @@ -480,15 +480,21 @@ struct FormatStyle {
ENAS_DontAlign,
/// Align escaped newlines as far left as possible.
/// \code
/// true:
/// #define A \
/// int aaaa; \
/// int b; \
/// int dddddddddd;
///
/// false:
/// \endcode
ENAS_Left,
/// Align escaped newlines as far left as possible, using the last line of
/// the preprocessor directive as the reference if it's the longest.
/// \code
/// #define A \
/// int aaaa; \
/// int b; \
/// int dddddddddd;
/// \endcode
ENAS_LeftWithLastLine,
/// Align escaped newlines in the right-most column.
/// \code
/// #define A \
Expand Down Expand Up @@ -5239,7 +5245,7 @@ tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
/// Returns the replacements corresponding to applying and formatting
/// \p Replaces on success; otheriwse, return an llvm::Error carrying
/// llvm::StringError.
llvm::Expected<tooling::Replacements>
Expected<tooling::Replacements>
formatReplacements(StringRef Code, const tooling::Replacements &Replaces,
const FormatStyle &Style);

Expand All @@ -5256,7 +5262,7 @@ formatReplacements(StringRef Code, const tooling::Replacements &Replaces,
/// The include manipulation is done via ``tooling::HeaderInclude``, see its
/// documentation for more details on how include insertion points are found and
/// what edits are produced.
llvm::Expected<tooling::Replacements>
Expected<tooling::Replacements>
cleanupAroundReplacements(StringRef Code, const tooling::Replacements &Replaces,
const FormatStyle &Style);

Expand Down Expand Up @@ -5381,11 +5387,10 @@ extern const char *DefaultFallbackStyle;
/// \returns FormatStyle as specified by ``StyleName``. If ``StyleName`` is
/// "file" and no file is found, returns ``FallbackStyle``. If no style could be
/// determined, returns an Error.
llvm::Expected<FormatStyle> getStyle(StringRef StyleName, StringRef FileName,
StringRef FallbackStyle,
StringRef Code = "",
llvm::vfs::FileSystem *FS = nullptr,
bool AllowUnknownOptions = false);
Expected<FormatStyle> getStyle(StringRef StyleName, StringRef FileName,
StringRef FallbackStyle, StringRef Code = "",
llvm::vfs::FileSystem *FS = nullptr,
bool AllowUnknownOptions = false);

// Guesses the language from the ``FileName`` and ``Code`` to be formatted.
// Defaults to FormatStyle::LK_Cpp.
Expand Down
16 changes: 11 additions & 5 deletions clang/include/clang/Parse/Parser.h
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,9 @@ class Parser : public CodeCompletionHandler {
/// Identifier for "replacement".
IdentifierInfo *Ident_replacement;

/// Identifier for "environment".
IdentifierInfo *Ident_environment;

/// Identifiers used by the 'external_source_symbol' attribute.
IdentifierInfo *Ident_language, *Ident_defined_in,
*Ident_generated_declaration, *Ident_USR;
Expand Down Expand Up @@ -1643,9 +1646,11 @@ class Parser : public CodeCompletionHandler {
void ParseLexedAttributes(ParsingClass &Class);
void ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
bool EnterScope, bool OnDefinition);
void ParseLexedCAttributeList(LateParsedAttrList &LA, bool EnterScope,
ParsedAttributes *OutAttrs = nullptr);
void ParseLexedAttribute(LateParsedAttribute &LA,
bool EnterScope, bool OnDefinition);
void ParseLexedCAttribute(LateParsedAttribute &LA,
void ParseLexedCAttribute(LateParsedAttribute &LA, bool EnterScope,
ParsedAttributes *OutAttrs = nullptr);
void ParseLexedMethodDeclarations(ParsingClass &Class);
void ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM);
Expand Down Expand Up @@ -2814,7 +2819,7 @@ class Parser : public CodeCompletionHandler {
SourceLocation CorrectLocation);

void stripTypeAttributesOffDeclSpec(ParsedAttributes &Attrs, DeclSpec &DS,
Sema::TagUseKind TUK);
TagUseKind TUK);

// FixItLoc = possible correct location for the attributes
void ProhibitAttributes(ParsedAttributes &Attrs,
Expand Down Expand Up @@ -2997,7 +3002,8 @@ class Parser : public CodeCompletionHandler {
bool ParseCXXAssumeAttributeArg(ParsedAttributes &Attrs,
IdentifierInfo *AttrName,
SourceLocation AttrNameLoc,
SourceLocation *EndLoc);
SourceLocation *EndLoc,
ParsedAttr::Form Form);

IdentifierInfo *TryParseCXX11AttributeIdentifier(
SourceLocation &Loc,
Expand Down Expand Up @@ -3688,9 +3694,9 @@ class Parser : public CodeCompletionHandler {

using OpenACCVarParseResult = std::pair<ExprResult, OpenACCParseCanContinue>;
/// Parses a single variable in a variable list for OpenACC.
OpenACCVarParseResult ParseOpenACCVar();
OpenACCVarParseResult ParseOpenACCVar(OpenACCClauseKind CK);
/// Parses the variable list for the variety of places that take a var-list.
llvm::SmallVector<Expr *> ParseOpenACCVarList();
llvm::SmallVector<Expr *> ParseOpenACCVarList(OpenACCClauseKind CK);
/// Parses any parameters for an OpenACC Clause, including required/optional
/// parens.
OpenACCClauseParseResult
Expand Down
42 changes: 28 additions & 14 deletions clang/include/clang/Sema/ParsedAttr.h
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ class LangOptions;
class Sema;
class Stmt;
class TargetInfo;
struct IdentifierLoc;

/// Represents information about a change in availability for
/// an entity, which is part of the encoding of the 'availability'
Expand Down Expand Up @@ -68,12 +69,14 @@ struct AvailabilityData {
AvailabilityChange Changes[NumAvailabilitySlots];
SourceLocation StrictLoc;
const Expr *Replacement;
const IdentifierLoc *EnvironmentLoc;

AvailabilityData(const AvailabilityChange &Introduced,
const AvailabilityChange &Deprecated,
const AvailabilityChange &Obsoleted,
SourceLocation Strict, const Expr *ReplaceExpr)
: StrictLoc(Strict), Replacement(ReplaceExpr) {
const AvailabilityChange &Obsoleted, SourceLocation Strict,
const Expr *ReplaceExpr, const IdentifierLoc *EnvironmentLoc)
: StrictLoc(Strict), Replacement(ReplaceExpr),
EnvironmentLoc(EnvironmentLoc) {
Changes[IntroducedSlot] = Introduced;
Changes[DeprecatedSlot] = Deprecated;
Changes[ObsoletedSlot] = Obsoleted;
Expand Down Expand Up @@ -234,7 +237,7 @@ class ParsedAttr final
const AvailabilityChange &deprecated,
const AvailabilityChange &obsoleted, SourceLocation unavailable,
const Expr *messageExpr, Form formUsed, SourceLocation strict,
const Expr *replacementExpr)
const Expr *replacementExpr, const IdentifierLoc *environmentLoc)
: AttributeCommonInfo(attrName, scopeName, attrRange, scopeLoc, formUsed),
NumArgs(1), Invalid(false), UsedAsTypeAttr(false), IsAvailability(true),
IsTypeTagForDatatype(false), IsProperty(false), HasParsedType(false),
Expand All @@ -243,8 +246,9 @@ class ParsedAttr final
Info(ParsedAttrInfo::get(*this)) {
ArgsUnion PVal(Parm);
memcpy(getArgsBuffer(), &PVal, sizeof(ArgsUnion));
new (getAvailabilityData()) detail::AvailabilityData(
introduced, deprecated, obsoleted, strict, replacementExpr);
new (getAvailabilityData())
detail::AvailabilityData(introduced, deprecated, obsoleted, strict,
replacementExpr, environmentLoc);
}

/// Constructor for objc_bridge_related attributes.
Expand Down Expand Up @@ -445,6 +449,12 @@ class ParsedAttr final
return getAvailabilityData()->Replacement;
}

const IdentifierLoc *getEnvironment() const {
assert(getParsedKind() == AT_Availability &&
"Not an availability attribute");
return getAvailabilityData()->EnvironmentLoc;
}

const ParsedType &getMatchingCType() const {
assert(getParsedKind() == AT_TypeTagForDatatype &&
"Not a type_tag_for_datatype attribute");
Expand Down Expand Up @@ -759,11 +769,13 @@ class AttributePool {
const AvailabilityChange &obsoleted,
SourceLocation unavailable, const Expr *MessageExpr,
ParsedAttr::Form form, SourceLocation strict,
const Expr *ReplacementExpr) {
const Expr *ReplacementExpr,
IdentifierLoc *EnvironmentLoc) {
void *memory = allocate(AttributeFactory::AvailabilityAllocSize);
return add(new (memory) ParsedAttr(
attrName, attrRange, scopeName, scopeLoc, Param, introduced, deprecated,
obsoleted, unavailable, MessageExpr, form, strict, ReplacementExpr));
return add(new (memory) ParsedAttr(attrName, attrRange, scopeName, scopeLoc,
Param, introduced, deprecated, obsoleted,
unavailable, MessageExpr, form, strict,
ReplacementExpr, EnvironmentLoc));
}

ParsedAttr *create(IdentifierInfo *attrName, SourceRange attrRange,
Expand Down Expand Up @@ -994,10 +1006,12 @@ class ParsedAttributes : public ParsedAttributesView {
const AvailabilityChange &obsoleted,
SourceLocation unavailable, const Expr *MessageExpr,
ParsedAttr::Form form, SourceLocation strict,
const Expr *ReplacementExpr) {
ParsedAttr *attr = pool.create(
attrName, attrRange, scopeName, scopeLoc, Param, introduced, deprecated,
obsoleted, unavailable, MessageExpr, form, strict, ReplacementExpr);
const Expr *ReplacementExpr,
IdentifierLoc *EnvironmentLoc) {
ParsedAttr *attr =
pool.create(attrName, attrRange, scopeName, scopeLoc, Param, introduced,
deprecated, obsoleted, unavailable, MessageExpr, form,
strict, ReplacementExpr, EnvironmentLoc);
addAtEnd(attr);
return attr;
}
Expand Down
Loading