Import Clang 3.5svn r202566.

This commit is contained in:
joerg 2014-03-04 19:53:10 +00:00
parent 985bd56043
commit 83820d9427
647 changed files with 23748 additions and 9566 deletions

View File

@ -1,5 +1,6 @@
import gc
import os
import tempfile
from clang.cindex import CursorKind
from clang.cindex import Cursor
@ -93,15 +94,7 @@ def save_tu(tu):
Returns the filename it was saved to.
"""
# FIXME Generate a temp file path using system APIs.
base = 'TEMP_FOR_TRANSLATIONUNIT_SAVE.c'
path = os.path.join(kInputsDir, base)
# Just in case.
if os.path.exists(path):
os.unlink(path)
_, path = tempfile.mkstemp()
tu.save(path)
return path

File diff suppressed because it is too large Load Diff

View File

@ -146,6 +146,10 @@ the configuration (without a prefix: ``Auto``).
Like ``Attach``, but break before function definitions.
* ``BS_Allman`` (in configuration: ``Allman``)
Always break before braces.
* ``BS_GNU`` (in configuration: ``GNU``)
Always break before braces and add an extra level of indentation to
braces of control statements, not to those of class, function
or other definitions.
**BreakBeforeTernaryOperators** (``bool``)
@ -162,6 +166,10 @@ the configuration (without a prefix: ``Auto``).
clang-format will respect the input's line breaking decisions within
statements unless they contradict other rules.
**CommentPragmas** (``std::string``)
A regular expression that describes comments with special meaning,
which should not be split into lines or otherwise changed.
**ConstructorInitializerAllOnOneLineOrOnePerLine** (``bool``)
If the constructor initializers don't fit on a line, put each
initializer on its own line.
@ -189,7 +197,8 @@ the configuration (without a prefix: ``Auto``).
a zero-length name is assumed.
**DerivePointerBinding** (``bool``)
If ``true``, analyze the formatted file for the most common binding.
If ``true``, analyze the formatted file for the most common binding
and use ``PointerBindsToType`` only as fallback.
**ExperimentalAutoDetectBinPacking** (``bool``)
If ``true``, clang-format detects whether function calls and
@ -227,6 +236,9 @@ the configuration (without a prefix: ``Auto``).
Should be used for C, C++, ObjectiveC, ObjectiveC++.
* ``LK_JavaScript`` (in configuration: ``JavaScript``)
Should be used for JavaScript.
* ``LK_Proto`` (in configuration: ``Proto``)
Should be used for Protocol Buffers
(https://developers.google.com/protocol-buffers/).
**MaxEmptyLinesToKeep** (``unsigned``)
@ -245,6 +257,10 @@ the configuration (without a prefix: ``Auto``).
Indent in all namespaces.
**ObjCSpaceAfterProperty** (``bool``)
Add a space after ``@property`` in Objective-C, i.e. use
``@property (readonly)`` instead of ``@property(readonly)``.
**ObjCSpaceBeforeProtocolList** (``bool``)
Add a space in front of an Objective-C protocol list, i.e. use
``Foo <Protocol>`` instead of ``Foo<Protocol>``.
@ -292,7 +308,7 @@ the configuration (without a prefix: ``Auto``).
**SpaceInEmptyParentheses** (``bool``)
If ``false``, spaces may be inserted into '()'.
If ``true``, spaces may be inserted into '()'.
**SpacesBeforeTrailingComments** (``unsigned``)
The number of spaces to before trailing line comments.
@ -302,7 +318,11 @@ the configuration (without a prefix: ``Auto``).
template argument lists
**SpacesInCStyleCastParentheses** (``bool``)
If ``false``, spaces may be inserted into C style casts.
If ``true``, spaces may be inserted into C style casts.
**SpacesInContainerLiterals** (``bool``)
If ``true``, spaces are inserted inside container literals (e.g.
ObjC and Javascript array and dict literals).
**SpacesInParentheses** (``bool``)
If ``true``, spaces will be inserted after '(' and before ')'.

View File

@ -87,7 +87,8 @@ start with ``err_``, ``warn_``, ``ext_`` to encode the severity into the name.
Since the enum is referenced in the C++ code that produces the diagnostic, it
is somewhat useful for it to be reasonably short.
The severity of the diagnostic comes from the set {``NOTE``, ``WARNING``,
The severity of the diagnostic comes from the set {``NOTE``, ``REMARK``,
``WARNING``,
``EXTENSION``, ``EXTWARN``, ``ERROR``}. The ``ERROR`` severity is used for
diagnostics indicating the program is never acceptable under any circumstances.
When an error is emitted, the AST for the input code may not be fully built.
@ -97,11 +98,13 @@ represent them in the AST, but we produce diagnostics to tell the user their
code is non-portable. The difference is that the former are ignored by
default, and the later warn by default. The ``WARNING`` severity is used for
constructs that are valid in the currently selected source language but that
are dubious in some way. The ``NOTE`` level is used to staple more information
onto previous diagnostics.
are dubious in some way. The ``REMARK`` severity provides generic information
about the compilation that is not necessarily related to any dubious code. The
``NOTE`` level is used to staple more information onto previous diagnostics.
These *severities* are mapped into a smaller set (the ``Diagnostic::Level``
enum, {``Ignored``, ``Note``, ``Warning``, ``Error``, ``Fatal``}) of output
enum, {``Ignored``, ``Note``, ``Remark``, ``Warning``, ``Error``, ``Fatal``}) of
output
*levels* by the diagnostics subsystem based on various configuration options.
Clang internally supports a fully fine grained mapping mechanism that allows
you to map almost any diagnostic to the output level that you want. The only
@ -1727,6 +1730,21 @@ If additional functionality is desired for the semantic form of the attribute,
the ``AdditionalMembers`` field specifies code to be copied verbatim into the
semantic attribute class object.
All attributes must have one or more form of documentation, which is provided
in the ``Documentation`` list. Generally, the documentation for an attribute
is a stand-alone definition in `include/clang/Basic/AttrDocs.td
<http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/AttdDocs.td?view=markup>`_
that is named after the attribute being documented. Each documentation element
is given a ``Category`` (variable, function, or type) and ``Content``. A single
attribute may contain multiple documentation elements for distinct categories.
For instance, an attribute which can appertain to both function and types (such
as a calling convention attribute), should contain two documentation elements.
The ``Content`` for an attribute uses reStructuredText (RST) syntax.
If an attribute is used internally by the compiler, but is not written by users
(such as attributes with an empty spelling list), it can use the
``Undocumented`` documentation element.
Boilerplate
^^^^^^^^^^^

View File

@ -12,7 +12,7 @@ Clang Language Extensions
ObjectiveCLiterals
BlockLanguageSpec
Block-ABI-Apple
AutomaticReferenceCounting
AutomaticReferenceCounting
Introduction
============
@ -426,103 +426,6 @@ should be treated as a system framework, regardless of how it was found in the
framework search path. For consistency, we recommend that such files never be
included in installed versions of the framework.
Availability attribute
======================
Clang introduces the ``availability`` attribute, which can be placed on
declarations to describe the lifecycle of that declaration relative to
operating system versions. Consider the function declaration for a
hypothetical function ``f``:
.. code-block:: c++
void f(void) __attribute__((availability(macosx,introduced=10.4,deprecated=10.6,obsoleted=10.7)));
The availability attribute states that ``f`` was introduced in Mac OS X 10.4,
deprecated in Mac OS X 10.6, and obsoleted in Mac OS X 10.7. This information
is used by Clang to determine when it is safe to use ``f``: for example, if
Clang is instructed to compile code for Mac OS X 10.5, a call to ``f()``
succeeds. If Clang is instructed to compile code for Mac OS X 10.6, the call
succeeds but Clang emits a warning specifying that the function is deprecated.
Finally, if Clang is instructed to compile code for Mac OS X 10.7, the call
fails because ``f()`` is no longer available.
The availability attribute is a comma-separated list starting with the
platform name and then including clauses specifying important milestones in the
declaration's lifetime (in any order) along with additional information. Those
clauses can be:
introduced=\ *version*
The first version in which this declaration was introduced.
deprecated=\ *version*
The first version in which this declaration was deprecated, meaning that
users should migrate away from this API.
obsoleted=\ *version*
The first version in which this declaration was obsoleted, meaning that it
was removed completely and can no longer be used.
unavailable
This declaration is never available on this platform.
message=\ *string-literal*
Additional message text that Clang will provide when emitting a warning or
error about use of a deprecated or obsoleted declaration. Useful to direct
users to replacement APIs.
Multiple availability attributes can be placed on a declaration, which may
correspond to different platforms. Only the availability attribute with the
platform corresponding to the target platform will be used; any others will be
ignored. If no availability attribute specifies availability for the current
target platform, the availability attributes are ignored. Supported platforms
are:
``ios``
Apple's iOS operating system. The minimum deployment target is specified by
the ``-mios-version-min=*version*`` or ``-miphoneos-version-min=*version*``
command-line arguments.
``macosx``
Apple's Mac OS X operating system. The minimum deployment target is
specified by the ``-mmacosx-version-min=*version*`` command-line argument.
A declaration can be used even when deploying back to a platform version prior
to when the declaration was introduced. When this happens, the declaration is
`weakly linked
<https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPFrameworks/Concepts/WeakLinking.html>`_,
as if the ``weak_import`` attribute were added to the declaration. A
weakly-linked declaration may or may not be present a run-time, and a program
can determine whether the declaration is present by checking whether the
address of that declaration is non-NULL.
If there are multiple declarations of the same entity, the availability
attributes must either match on a per-platform basis or later
declarations must not have availability attributes for that
platform. For example:
.. code-block:: c
void g(void) __attribute__((availability(macosx,introduced=10.4)));
void g(void) __attribute__((availability(macosx,introduced=10.4))); // okay, matches
void g(void) __attribute__((availability(ios,introduced=4.0))); // okay, adds a new platform
void g(void); // okay, inherits both macosx and ios availability from above.
void g(void) __attribute__((availability(macosx,introduced=10.5))); // error: mismatch
When one method overrides another, the overriding method can be more widely available than the overridden method, e.g.,:
.. code-block:: objc
@interface A
- (id)method __attribute__((availability(macosx,introduced=10.4)));
- (id)method2 __attribute__((availability(macosx,introduced=10.4)));
@end
@interface B : A
- (id)method __attribute__((availability(macosx,introduced=10.3))); // okay: method moved into base class later
- (id)method __attribute__((availability(macosx,introduced=10.5))); // error: this method was available via the base class in 10.4
@end
Checks for Standard Language Features
=====================================
@ -1195,77 +1098,6 @@ feature, clang provides default synthesis of those properties not declared
``__has_feature(objc_default_synthesize_properties)`` checks for availability
of this feature in version of clang being used.
.. _langext-objc_method_family:
Objective-C requiring a call to ``super`` in an override
--------------------------------------------------------
Some Objective-C classes allow a subclass to override a particular method in a
parent class but expect that the overriding method also calls the overridden
method in the parent class. For these cases, we provide an attribute to
designate that a method requires a "call to ``super``" in the overriding
method in the subclass.
**Usage**: ``__attribute__((objc_requires_super))``. This attribute can only
be placed at the end of a method declaration:
.. code-block:: objc
- (void)foo __attribute__((objc_requires_super));
This attribute can only be applied the method declarations within a class, and
not a protocol. Currently this attribute does not enforce any placement of
where the call occurs in the overriding method (such as in the case of
``-dealloc`` where the call must appear at the end). It checks only that it
exists.
Note that on both OS X and iOS that the Foundation framework provides a
convenience macro ``NS_REQUIRES_SUPER`` that provides syntactic sugar for this
attribute:
.. code-block:: objc
- (void)foo NS_REQUIRES_SUPER;
This macro is conditionally defined depending on the compiler's support for
this attribute. If the compiler does not support the attribute the macro
expands to nothing.
Operationally, when a method has this annotation the compiler will warn if the
implementation of an override in a subclass does not call super. For example:
.. code-block:: objc
warning: method possibly missing a [super AnnotMeth] call
- (void) AnnotMeth{};
^
Objective-C Method Families
---------------------------
Many methods in Objective-C have conventional meanings determined by their
selectors. It is sometimes useful to be able to mark a method as having a
particular conventional meaning despite not having the right selector, or as
not having the conventional meaning that its selector would suggest. For these
use cases, we provide an attribute to specifically describe the "method family"
that a method belongs to.
**Usage**: ``__attribute__((objc_method_family(X)))``, where ``X`` is one of
``none``, ``alloc``, ``copy``, ``init``, ``mutableCopy``, or ``new``. This
attribute can only be placed at the end of a method declaration:
.. code-block:: objc
- (NSString *)initMyStringValue __attribute__((objc_method_family(none)));
Users who do not wish to change the conventional meaning of a method, and who
merely want to document its non-standard retain and release semantics, should
use the :ref:`retaining behavior attributes <langext-objc-retain-release>`
described below.
Query for this feature with ``__has_attribute(objc_method_family)``.
.. _langext-objc-retain-release:
Objective-C retaining behavior attributes
@ -1278,8 +1110,7 @@ conventions for ownership of object arguments and
return values. However, there are exceptions, and so Clang provides attributes
to allow these exceptions to be documented. This are used by ARC and the
`static analyzer <http://clang-analyzer.llvm.org>`_ Some exceptions may be
better described using the :ref:`objc_method_family
<langext-objc_method_family>` attribute instead.
better described using the ``objc_method_family`` attribute instead.
**Usage**: The ``ns_returns_retained``, ``ns_returns_not_retained``,
``ns_returns_autoreleased``, ``cf_returns_retained``, and
@ -1338,167 +1169,6 @@ Query the presence of this new mangling with
.. _langext-overloading:
Function Overloading in C
=========================
Clang provides support for C++ function overloading in C. Function overloading
in C is introduced using the ``overloadable`` attribute. For example, one
might provide several overloaded versions of a ``tgsin`` function that invokes
the appropriate standard function computing the sine of a value with ``float``,
``double``, or ``long double`` precision:
.. code-block:: c
#include <math.h>
float __attribute__((overloadable)) tgsin(float x) { return sinf(x); }
double __attribute__((overloadable)) tgsin(double x) { return sin(x); }
long double __attribute__((overloadable)) tgsin(long double x) { return sinl(x); }
Given these declarations, one can call ``tgsin`` with a ``float`` value to
receive a ``float`` result, with a ``double`` to receive a ``double`` result,
etc. Function overloading in C follows the rules of C++ function overloading
to pick the best overload given the call arguments, with a few C-specific
semantics:
* Conversion from ``float`` or ``double`` to ``long double`` is ranked as a
floating-point promotion (per C99) rather than as a floating-point conversion
(as in C++).
* A conversion from a pointer of type ``T*`` to a pointer of type ``U*`` is
considered a pointer conversion (with conversion rank) if ``T`` and ``U`` are
compatible types.
* A conversion from type ``T`` to a value of type ``U`` is permitted if ``T``
and ``U`` are compatible types. This conversion is given "conversion" rank.
The declaration of ``overloadable`` functions is restricted to function
declarations and definitions. Most importantly, if any function with a given
name is given the ``overloadable`` attribute, then all function declarations
and definitions with that name (and in that scope) must have the
``overloadable`` attribute. This rule even applies to redeclarations of
functions whose original declaration had the ``overloadable`` attribute, e.g.,
.. code-block:: c
int f(int) __attribute__((overloadable));
float f(float); // error: declaration of "f" must have the "overloadable" attribute
int g(int) __attribute__((overloadable));
int g(int) { } // error: redeclaration of "g" must also have the "overloadable" attribute
Functions marked ``overloadable`` must have prototypes. Therefore, the
following code is ill-formed:
.. code-block:: c
int h() __attribute__((overloadable)); // error: h does not have a prototype
However, ``overloadable`` functions are allowed to use a ellipsis even if there
are no named parameters (as is permitted in C++). This feature is particularly
useful when combined with the ``unavailable`` attribute:
.. code-block:: c++
void honeypot(...) __attribute__((overloadable, unavailable)); // calling me is an error
Functions declared with the ``overloadable`` attribute have their names mangled
according to the same rules as C++ function names. For example, the three
``tgsin`` functions in our motivating example get the mangled names
``_Z5tgsinf``, ``_Z5tgsind``, and ``_Z5tgsine``, respectively. There are two
caveats to this use of name mangling:
* Future versions of Clang may change the name mangling of functions overloaded
in C, so you should not depend on an specific mangling. To be completely
safe, we strongly urge the use of ``static inline`` with ``overloadable``
functions.
* The ``overloadable`` attribute has almost no meaning when used in C++,
because names will already be mangled and functions are already overloadable.
However, when an ``overloadable`` function occurs within an ``extern "C"``
linkage specification, it's name *will* be mangled in the same way as it
would in C.
Query for this feature with ``__has_extension(attribute_overloadable)``.
Controlling Overload Resolution
===============================
Clang introduces the ``enable_if`` attribute, which can be placed on function
declarations to control which overload is selected based on the values of the
function's arguments. When combined with the
:ref:`overloadable<langext-overloading>` attribute, this feature is also
available in C.
.. code-block:: c++
int isdigit(int c);
int isdigit(int c) __attribute__((enable_if(c <= -1 || c > 255, "chosen when 'c' is out of range"))) __attribute__((unavailable("'c' must have the value of an unsigned char or EOF")));
void foo(char c) {
isdigit(c);
isdigit(10);
isdigit(-10); // results in a compile-time error.
}
The enable_if attribute takes two arguments, the first is an expression written
in terms of the function parameters, the second is a string explaining why this
overload candidate could not be selected to be displayed in diagnostics. The
expression is part of the function signature for the purposes of determining
whether it is a redeclaration (following the rules used when determining
whether a C++ template specialization is ODR-equivalent), but is not part of
the type.
The enable_if expression is evaluated as if it were the body of a
bool-returning constexpr function declared with the arguments of the function
it is being applied to, then called with the parameters at the callsite. If the
result is false or could not be determined through constant expression
evaluation, then this overload will not be chosen and the provided string may
be used in a diagnostic if the compile fails as a result.
Because the enable_if expression is an unevaluated context, there are no global
state changes, nor the ability to pass information from the enable_if
expression to the function body. For example, suppose we want calls to
strnlen(strbuf, maxlen) to resolve to strnlen_chk(strbuf, maxlen, size of
strbuf) only if the size of strbuf can be determined:
.. code-block:: c++
__attribute__((always_inline))
static inline size_t strnlen(const char *s, size_t maxlen)
__attribute__((overloadable))
__attribute__((enable_if(__builtin_object_size(s, 0) != -1))),
"chosen when the buffer size is known but 'maxlen' is not")))
{
return strnlen_chk(s, maxlen, __builtin_object_size(s, 0));
}
Multiple enable_if attributes may be applied to a single declaration. In this
case, the enable_if expressions are evaluated from left to right in the
following manner. First, the candidates whose enable_if expressions evaluate to
false or cannot be evaluated are discarded. If the remaining candidates do not
share ODR-equivalent enable_if expressions, the overload resolution is
ambiguous. Otherwise, enable_if overload resolution continues with the next
enable_if attribute on the candidates that have not been discarded and have
remaining enable_if attributes. In this way, we pick the most specific
overload out of a number of viable overloads using enable_if.
.. code-block:: c++
void f() __attribute__((enable_if(true, ""))); // #1
void f() __attribute__((enable_if(true, ""))) __attribute__((enable_if(true, ""))); // #2
void g(int i, int j) __attribute__((enable_if(i, ""))); // #1
void g(int i, int j) __attribute__((enable_if(j, ""))) __attribute__((enable_if(true))); // #2
In this example, a call to f() is always resolved to #2, as the first enable_if
expression is ODR-equivalent for both declarations, but #1 does not have another
enable_if expression to continue evaluating, so the next round of evaluation has
only a single candidate. In a call to g(1, 1), the call is ambiguous even though
#2 has more enable_if attributes, because the first enable_if expressions are
not ODR-equivalent.
Query for this feature with ``__has_attribute(enable_if)``.
Initializer lists for complex numbers in C
==========================================
@ -1900,55 +1570,7 @@ Non-standard C++11 Attributes
Clang's non-standard C++11 attributes live in the ``clang`` attribute
namespace.
The ``clang::fallthrough`` attribute
------------------------------------
The ``clang::fallthrough`` attribute is used along with the
``-Wimplicit-fallthrough`` argument to annotate intentional fall-through
between switch labels. It can only be applied to a null statement placed at a
point of execution between any statement and the next switch label. It is
common to mark these places with a specific comment, but this attribute is
meant to replace comments with a more strict annotation, which can be checked
by the compiler. This attribute doesn't change semantics of the code and can
be used wherever an intended fall-through occurs. It is designed to mimic
control-flow statements like ``break;``, so it can be placed in most places
where ``break;`` can, but only if there are no statements on the execution path
between it and the next switch label.
Here is an example:
.. code-block:: c++
// compile with -Wimplicit-fallthrough
switch (n) {
case 22:
case 33: // no warning: no statements between case labels
f();
case 44: // warning: unannotated fall-through
g();
[[clang::fallthrough]];
case 55: // no warning
if (x) {
h();
break;
}
else {
i();
[[clang::fallthrough]];
}
case 66: // no warning
p();
[[clang::fallthrough]]; // warning: fallthrough annotation does not
// directly precede case label
q();
case 77: // warning: unannotated fall-through
r();
}
``gnu::`` attributes
--------------------
Clang also supports GCC's ``gnu`` attribute namespace. All GCC attributes which
Clang supports GCC's ``gnu`` attribute namespace. All GCC attributes which
are accepted with the ``__attribute__((foo))`` syntax are also accepted as
``[[gnu::foo]]``. This only extends to attributes which are specified by GCC
(see the list of `GCC function attributes
@ -2004,48 +1626,6 @@ Which compiles to (on X86-32):
movl %gs:(%eax), %eax
ret
ARM Language Extensions
-----------------------
Interrupt attribute
^^^^^^^^^^^^^^^^^^^
Clang supports the GNU style ``__attribute__((interrupt("TYPE")))`` attribute on
ARM targets. This attribute may be attached to a function definition and
instructs the backend to generate appropriate function entry/exit code so that
it can be used directly as an interrupt service routine.
The parameter passed to the interrupt attribute is optional, but if
provided it must be a string literal with one of the following values: "IRQ",
"FIQ", "SWI", "ABORT", "UNDEF".
The semantics are as follows:
- If the function is AAPCS, Clang instructs the backend to realign the stack to
8 bytes on entry. This is a general requirement of the AAPCS at public
interfaces, but may not hold when an exception is taken. Doing this allows
other AAPCS functions to be called.
- If the CPU is M-class this is all that needs to be done since the architecture
itself is designed in such a way that functions obeying the normal AAPCS ABI
constraints are valid exception handlers.
- If the CPU is not M-class, the prologue and epilogue are modified to save all
non-banked registers that are used, so that upon return the user-mode state
will not be corrupted. Note that to avoid unnecessary overhead, only
general-purpose (integer) registers are saved in this way. If VFP operations
are needed, that state must be saved manually.
Specifically, interrupt kinds other than "FIQ" will save all core registers
except "lr" and "sp". "FIQ" interrupts will save r0-r7.
- If the CPU is not M-class, the return instruction is changed to one of the
canonical sequences permitted by the architecture for exception return. Where
possible the function itself will make the necessary "lr" adjustments so that
the "preferred return address" is selected.
Unfortunately the compiler is unable to make this guarantee for an "UNDEF"
handler, where the offset from "lr" to the preferred return address depends on
the execution state of the code which generated the exception. In this case
a sequence equivalent to "movs pc, lr" will be used.
Extensions for Static Analysis
==============================
@ -2059,450 +1639,11 @@ in the analyzer's `list of source-level annotations
Extensions for Dynamic Analysis
===============================
.. _langext-address_sanitizer:
AddressSanitizer
----------------
Use ``__has_feature(address_sanitizer)`` to check if the code is being built
with :doc:`AddressSanitizer`.
Use ``__attribute__((no_sanitize_address))``
on a function declaration
to specify that address safety instrumentation (e.g. AddressSanitizer) should
not be applied to that function.
.. _langext-thread_sanitizer:
ThreadSanitizer
----------------
Use ``__has_feature(thread_sanitizer)`` to check if the code is being built
with :doc:`ThreadSanitizer`.
Use ``__attribute__((no_sanitize_thread))`` on a function declaration
to specify that checks for data races on plain (non-atomic) memory accesses
should not be inserted by ThreadSanitizer.
The function is still instrumented by the tool to avoid false positives and
provide meaningful stack traces.
.. _langext-memory_sanitizer:
MemorySanitizer
----------------
Use ``__has_feature(memory_sanitizer)`` to check if the code is being built
with :doc:`MemorySanitizer`.
Use ``__attribute__((no_sanitize_memory))`` on a function declaration
to specify that checks for uninitialized memory should not be inserted
(e.g. by MemorySanitizer). The function may still be instrumented by the tool
to avoid false positives in other places.
Thread-Safety Annotation Checking
=================================
Clang supports additional attributes for checking basic locking policies in
multithreaded programs. Clang currently parses the following list of
attributes, although **the implementation for these annotations is currently in
development.** For more details, see the `GCC implementation
<http://gcc.gnu.org/wiki/ThreadSafetyAnnotation>`_.
``no_thread_safety_analysis``
-----------------------------
Use ``__attribute__((no_thread_safety_analysis))`` on a function declaration to
specify that the thread safety analysis should not be run on that function.
This attribute provides an escape hatch (e.g. for situations when it is
difficult to annotate the locking policy).
``lockable``
------------
Use ``__attribute__((lockable))`` on a class definition to specify that it has
a lockable type (e.g. a Mutex class). This annotation is primarily used to
check consistency.
``scoped_lockable``
-------------------
Use ``__attribute__((scoped_lockable))`` on a class definition to specify that
it has a "scoped" lockable type. Objects of this type will acquire the lock
upon construction and release it upon going out of scope. This annotation is
primarily used to check consistency.
``guarded_var``
---------------
Use ``__attribute__((guarded_var))`` on a variable declaration to specify that
the variable must be accessed while holding some lock.
``pt_guarded_var``
------------------
Use ``__attribute__((pt_guarded_var))`` on a pointer declaration to specify
that the pointer must be dereferenced while holding some lock.
``guarded_by(l)``
-----------------
Use ``__attribute__((guarded_by(l)))`` on a variable declaration to specify
that the variable must be accessed while holding lock ``l``.
``pt_guarded_by(l)``
--------------------
Use ``__attribute__((pt_guarded_by(l)))`` on a pointer declaration to specify
that the pointer must be dereferenced while holding lock ``l``.
``acquired_before(...)``
------------------------
Use ``__attribute__((acquired_before(...)))`` on a declaration of a lockable
variable to specify that the lock must be acquired before all attribute
arguments. Arguments must be lockable type, and there must be at least one
argument.
``acquired_after(...)``
-----------------------
Use ``__attribute__((acquired_after(...)))`` on a declaration of a lockable
variable to specify that the lock must be acquired after all attribute
arguments. Arguments must be lockable type, and there must be at least one
argument.
``exclusive_lock_function(...)``
--------------------------------
Use ``__attribute__((exclusive_lock_function(...)))`` on a function declaration
to specify that the function acquires all listed locks exclusively. This
attribute takes zero or more arguments: either of lockable type or integers
indexing into function parameters of lockable type. If no arguments are given,
the acquired lock is implicitly ``this`` of the enclosing object.
``shared_lock_function(...)``
-----------------------------
Use ``__attribute__((shared_lock_function(...)))`` on a function declaration to
specify that the function acquires all listed locks, although the locks may be
shared (e.g. read locks). This attribute takes zero or more arguments: either
of lockable type or integers indexing into function parameters of lockable
type. If no arguments are given, the acquired lock is implicitly ``this`` of
the enclosing object.
``exclusive_trylock_function(...)``
-----------------------------------
Use ``__attribute__((exclusive_lock_function(...)))`` on a function declaration
to specify that the function will try (without blocking) to acquire all listed
locks exclusively. This attribute takes one or more arguments. The first
argument is an integer or boolean value specifying the return value of a
successful lock acquisition. The remaining arugments are either of lockable
type or integers indexing into function parameters of lockable type. If only
one argument is given, the acquired lock is implicitly ``this`` of the
enclosing object.
``shared_trylock_function(...)``
--------------------------------
Use ``__attribute__((shared_lock_function(...)))`` on a function declaration to
specify that the function will try (without blocking) to acquire all listed
locks, although the locks may be shared (e.g. read locks). This attribute
takes one or more arguments. The first argument is an integer or boolean value
specifying the return value of a successful lock acquisition. The remaining
arugments are either of lockable type or integers indexing into function
parameters of lockable type. If only one argument is given, the acquired lock
is implicitly ``this`` of the enclosing object.
``unlock_function(...)``
------------------------
Use ``__attribute__((unlock_function(...)))`` on a function declaration to
specify that the function release all listed locks. This attribute takes zero
or more arguments: either of lockable type or integers indexing into function
parameters of lockable type. If no arguments are given, the acquired lock is
implicitly ``this`` of the enclosing object.
``lock_returned(l)``
--------------------
Use ``__attribute__((lock_returned(l)))`` on a function declaration to specify
that the function returns lock ``l`` (``l`` must be of lockable type). This
annotation is used to aid in resolving lock expressions.
``locks_excluded(...)``
-----------------------
Use ``__attribute__((locks_excluded(...)))`` on a function declaration to
specify that the function must not be called with the listed locks. Arguments
must be lockable type, and there must be at least one argument.
``exclusive_locks_required(...)``
---------------------------------
Use ``__attribute__((exclusive_locks_required(...)))`` on a function
declaration to specify that the function must be called while holding the
listed exclusive locks. Arguments must be lockable type, and there must be at
least one argument.
``shared_locks_required(...)``
------------------------------
Use ``__attribute__((shared_locks_required(...)))`` on a function declaration
to specify that the function must be called while holding the listed shared
locks. Arguments must be lockable type, and there must be at least one
argument.
Consumed Annotation Checking
============================
Clang supports additional attributes for checking basic resource management
properties, specifically for unique objects that have a single owning reference.
The following attributes are currently supported, although **the implementation
for these annotations is currently in development and are subject to change.**
``consumable``
--------------
Each class that uses any of the following annotations must first be marked
using the consumable attribute. Failure to do so will result in a warning.
``set_typestate(new_state)``
----------------------------
Annotate methods that transition an object into a new state with
``__attribute__((set_typestate(new_state)))``. The new new state must be
unconsumed, consumed, or unknown.
``callable_when(...)``
----------------------
Use ``__attribute__((callable_when(...)))`` to indicate what states a method
may be called in. Valid states are unconsumed, consumed, or unknown. Each
argument to this attribute must be a quoted string. E.g.:
``__attribute__((callable_when("unconsumed", "unknown")))``
``tests_typestate(tested_state)``
---------------------------------
Use ``__attribute__((tests_typestate(tested_state)))`` to indicate that a method
returns true if the object is in the specified state..
``param_typestate(expected_state)``
-----------------------------------
This attribute specifies expectations about function parameters. Calls to an
function with annotated parameters will issue a warning if the corresponding
argument isn't in the expected state. The attribute is also used to set the
initial state of the parameter when analyzing the function's body.
``return_typestate(ret_state)``
-------------------------------
The ``return_typestate`` attribute can be applied to functions or parameters.
When applied to a function the attribute specifies the state of the returned
value. The function's body is checked to ensure that it always returns a value
in the specified state. On the caller side, values returned by the annotated
function are initialized to the given state.
If the attribute is applied to a function parameter it modifies the state of
an argument after a call to the function returns. The function's body is
checked to ensure that the parameter is in the expected state before returning.
Type Safety Checking
====================
Clang supports additional attributes to enable checking type safety properties
that can't be enforced by the C type system. Use cases include:
* MPI library implementations, where these attributes enable checking that
the buffer type matches the passed ``MPI_Datatype``;
* for HDF5 library there is a similar use case to MPI;
* checking types of variadic functions' arguments for functions like
``fcntl()`` and ``ioctl()``.
You can detect support for these attributes with ``__has_attribute()``. For
example:
.. code-block:: c++
#if defined(__has_attribute)
# if __has_attribute(argument_with_type_tag) && \
__has_attribute(pointer_with_type_tag) && \
__has_attribute(type_tag_for_datatype)
# define ATTR_MPI_PWT(buffer_idx, type_idx) __attribute__((pointer_with_type_tag(mpi,buffer_idx,type_idx)))
/* ... other macros ... */
# endif
#endif
#if !defined(ATTR_MPI_PWT)
# define ATTR_MPI_PWT(buffer_idx, type_idx)
#endif
int MPI_Send(void *buf, int count, MPI_Datatype datatype /*, other args omitted */)
ATTR_MPI_PWT(1,3);
``argument_with_type_tag(...)``
-------------------------------
Use ``__attribute__((argument_with_type_tag(arg_kind, arg_idx,
type_tag_idx)))`` on a function declaration to specify that the function
accepts a type tag that determines the type of some other argument.
``arg_kind`` is an identifier that should be used when annotating all
applicable type tags.
This attribute is primarily useful for checking arguments of variadic functions
(``pointer_with_type_tag`` can be used in most non-variadic cases).
For example:
.. code-block:: c++
int fcntl(int fd, int cmd, ...)
__attribute__(( argument_with_type_tag(fcntl,3,2) ));
``pointer_with_type_tag(...)``
------------------------------
Use ``__attribute__((pointer_with_type_tag(ptr_kind, ptr_idx, type_tag_idx)))``
on a function declaration to specify that the function accepts a type tag that
determines the pointee type of some other pointer argument.
For example:
.. code-block:: c++
int MPI_Send(void *buf, int count, MPI_Datatype datatype /*, other args omitted */)
__attribute__(( pointer_with_type_tag(mpi,1,3) ));
``type_tag_for_datatype(...)``
------------------------------
Clang supports annotating type tags of two forms.
* **Type tag that is an expression containing a reference to some declared
identifier.** Use ``__attribute__((type_tag_for_datatype(kind, type)))`` on a
declaration with that identifier:
.. code-block:: c++
extern struct mpi_datatype mpi_datatype_int
__attribute__(( type_tag_for_datatype(mpi,int) ));
#define MPI_INT ((MPI_Datatype) &mpi_datatype_int)
* **Type tag that is an integral literal.** Introduce a ``static const``
variable with a corresponding initializer value and attach
``__attribute__((type_tag_for_datatype(kind, type)))`` on that declaration,
for example:
.. code-block:: c++
#define MPI_INT ((MPI_Datatype) 42)
static const MPI_Datatype mpi_datatype_int
__attribute__(( type_tag_for_datatype(mpi,int) )) = 42
The attribute also accepts an optional third argument that determines how the
expression is compared to the type tag. There are two supported flags:
* ``layout_compatible`` will cause types to be compared according to
layout-compatibility rules (C++11 [class.mem] p 17, 18). This is
implemented to support annotating types like ``MPI_DOUBLE_INT``.
For example:
.. code-block:: c++
/* In mpi.h */
struct internal_mpi_double_int { double d; int i; };
extern struct mpi_datatype mpi_datatype_double_int
__attribute__(( type_tag_for_datatype(mpi, struct internal_mpi_double_int, layout_compatible) ));
#define MPI_DOUBLE_INT ((MPI_Datatype) &mpi_datatype_double_int)
/* In user code */
struct my_pair { double a; int b; };
struct my_pair *buffer;
MPI_Send(buffer, 1, MPI_DOUBLE_INT /*, ... */); // no warning
struct my_int_pair { int a; int b; }
struct my_int_pair *buffer2;
MPI_Send(buffer2, 1, MPI_DOUBLE_INT /*, ... */); // warning: actual buffer element
// type 'struct my_int_pair'
// doesn't match specified MPI_Datatype
* ``must_be_null`` specifies that the expression should be a null pointer
constant, for example:
.. code-block:: c++
/* In mpi.h */
extern struct mpi_datatype mpi_datatype_null
__attribute__(( type_tag_for_datatype(mpi, void, must_be_null) ));
#define MPI_DATATYPE_NULL ((MPI_Datatype) &mpi_datatype_null)
/* In user code */
MPI_Send(buffer, 1, MPI_DATATYPE_NULL /*, ... */); // warning: MPI_DATATYPE_NULL
// was specified but buffer
// is not a null pointer
Format String Checking
======================
Clang supports the ``format`` attribute, which indicates that the function
accepts a ``printf`` or ``scanf``-like format string and corresponding
arguments or a ``va_list`` that contains these arguments.
Please see `GCC documentation about format attribute
<http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_ to find details
about attribute syntax.
Clang implements two kinds of checks with this attribute.
#. Clang checks that the function with the ``format`` attribute is called with
a format string that uses format specifiers that are allowed, and that
arguments match the format string. This is the ``-Wformat`` warning, it is
on by default.
#. Clang checks that the format string argument is a literal string. This is
the ``-Wformat-nonliteral`` warning, it is off by default.
Clang implements this mostly the same way as GCC, but there is a difference
for functions that accept a ``va_list`` argument (for example, ``vprintf``).
GCC does not emit ``-Wformat-nonliteral`` warning for calls to such
fuctions. Clang does not warn if the format string comes from a function
parameter, where the function is annotated with a compatible attribute,
otherwise it warns. For example:
.. code-block:: c
__attribute__((__format__ (__scanf__, 1, 3)))
void foo(const char* s, char *buf, ...) {
va_list ap;
va_start(ap, buf);
vprintf(s, ap); // warning: format string is not a string literal
}
In this case we warn because ``s`` contains a format string for a
``scanf``-like function, but it is passed to a ``printf``-like function.
If the attribute is removed, clang still warns, because the format string is
not a string literal.
Another example:
.. code-block:: c
__attribute__((__format__ (__printf__, 1, 3)))
void foo(const char* s, char *buf, ...) {
va_list ap;
va_start(ap, buf);
vprintf(s, ap); // warning
}
In this case Clang does not warn because the format string ``s`` and
the corresponding arguments are annotated. If the arguments are
incorrect, the caller of ``foo`` will receive a warning.

View File

@ -250,7 +250,7 @@ Example matches f
<tr><td colspan="4" class="doc" id="methodDecl0"><pre>Matches method declarations.
Example matches y
class X { void y() };
class X { void y(); };
</pre></td></tr>
@ -1311,7 +1311,7 @@ Usable as: Any Matcher
</pre></td></tr>
<tr><td>Matcher&lt;*&gt;</td><td class="name" onclick="toggle('unless0')"><a name="unless0Anchor">unless</a></td><td>Matcher&lt;*&gt; InnerMatcher</td></tr>
<tr><td>Matcher&lt;*&gt;</td><td class="name" onclick="toggle('unless0')"><a name="unless0Anchor">unless</a></td><td>Matcher&lt;*&gt;</td></tr>
<tr><td colspan="4" class="doc" id="unless0"><pre>Matches if the provided matcher does not match.
Example matches Y (matcher = recordDecl(unless(hasName("X"))))
@ -1352,6 +1352,11 @@ Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2)))
</pre></td></tr>
<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXConstructExpr.html">CXXConstructExpr</a>&gt;</td><td class="name" onclick="toggle('isListInitialization0')"><a name="isListInitialization0Anchor">isListInitialization</a></td><td></td></tr>
<tr><td colspan="4" class="doc" id="isListInitialization0"><pre>Matches a constructor call expression which uses list initialization.
</pre></td></tr>
<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXConstructorDecl.html">CXXConstructorDecl</a>&gt;</td><td class="name" onclick="toggle('isImplicit0')"><a name="isImplicit0Anchor">isImplicit</a></td><td></td></tr>
<tr><td colspan="4" class="doc" id="isImplicit0"><pre>Matches a constructor declaration that has been implicitly added
by the compiler (eg. implicit defaultcopy constructors).
@ -1422,6 +1427,18 @@ Given
</pre></td></tr>
<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXMethodDecl.html">CXXMethodDecl</a>&gt;</td><td class="name" onclick="toggle('isPure0')"><a name="isPure0Anchor">isPure</a></td><td></td></tr>
<tr><td colspan="4" class="doc" id="isPure0"><pre>Matches if the given method declaration is pure.
Given
class A {
public:
virtual void x() = 0;
};
matches A::x
</pre></td></tr>
<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXMethodDecl.html">CXXMethodDecl</a>&gt;</td><td class="name" onclick="toggle('isVirtual0')"><a name="isVirtual0Anchor">isVirtual</a></td><td></td></tr>
<tr><td colspan="4" class="doc" id="isVirtual0"><pre>Matches if the given method declaration is virtual.
@ -2026,24 +2043,6 @@ Usable as: Any Matcher
</pre></td></tr>
<tr><td>Matcher&lt;*&gt;</td><td class="name" onclick="toggle('forEach0')"><a name="forEach0Anchor">forEach</a></td><td>Matcher&lt;*&gt;</td></tr>
<tr><td colspan="4" class="doc" id="forEach0"><pre>Matches AST nodes that have child AST nodes that match the
provided matcher.
Example matches X, Y (matcher = recordDecl(forEach(recordDecl(hasName("X")))
class X {}; Matches X, because X::X is a class of name X inside X.
class Y { class X {}; };
class Z { class Y { class X {}; }; }; Does not match Z.
ChildT must be an AST base type.
As opposed to 'has', 'forEach' will cause a match for each result that
matches instead of only on the first one.
Usable as: Any Matcher
</pre></td></tr>
<tr><td>Matcher&lt;*&gt;</td><td class="name" onclick="toggle('forEachDescendant0')"><a name="forEachDescendant0Anchor">forEachDescendant</a></td><td>Matcher&lt;*&gt;</td></tr>
<tr><td colspan="4" class="doc" id="forEachDescendant0"><pre>Matches AST nodes that have descendant AST nodes that match the
provided matcher.
@ -2068,17 +2067,20 @@ Usable as: Any Matcher
</pre></td></tr>
<tr><td>Matcher&lt;*&gt;</td><td class="name" onclick="toggle('has0')"><a name="has0Anchor">has</a></td><td>Matcher&lt;*&gt;</td></tr>
<tr><td colspan="4" class="doc" id="has0"><pre>Matches AST nodes that have child AST nodes that match the
<tr><td>Matcher&lt;*&gt;</td><td class="name" onclick="toggle('forEach0')"><a name="forEach0Anchor">forEach</a></td><td>Matcher&lt;*&gt;</td></tr>
<tr><td colspan="4" class="doc" id="forEach0"><pre>Matches AST nodes that have child AST nodes that match the
provided matcher.
Example matches X, Y (matcher = recordDecl(has(recordDecl(hasName("X")))
Example matches X, Y (matcher = recordDecl(forEach(recordDecl(hasName("X")))
class X {}; Matches X, because X::X is a class of name X inside X.
class Y { class X {}; };
class Z { class Y { class X {}; }; }; Does not match Z.
ChildT must be an AST base type.
As opposed to 'has', 'forEach' will cause a match for each result that
matches instead of only on the first one.
Usable as: Any Matcher
</pre></td></tr>
@ -2112,6 +2114,21 @@ Usable as: Any Matcher
</pre></td></tr>
<tr><td>Matcher&lt;*&gt;</td><td class="name" onclick="toggle('has0')"><a name="has0Anchor">has</a></td><td>Matcher&lt;*&gt;</td></tr>
<tr><td colspan="4" class="doc" id="has0"><pre>Matches AST nodes that have child AST nodes that match the
provided matcher.
Example matches X, Y (matcher = recordDecl(has(recordDecl(hasName("X")))
class X {}; Matches X, because X::X is a class of name X inside X.
class Y { class X {}; };
class Z { class Y { class X {}; }; }; Does not match Z.
ChildT must be an AST base type.
Usable as: Any Matcher
</pre></td></tr>
<tr><td>Matcher&lt;*&gt;</td><td class="name" onclick="toggle('hasParent0')"><a name="hasParent0Anchor">hasParent</a></td><td>Matcher&lt;*&gt;</td></tr>
<tr><td colspan="4" class="doc" id="hasParent0"><pre>Matches AST nodes that have a parent that matches the provided
matcher.
@ -2313,8 +2330,6 @@ The associated declaration is:
Also usable as Matcher&lt;T&gt; for any T supporting the getDecl() member
function. e.g. various subtypes of clang::Type and various expressions.
FIXME: Add all node types for which this is matcher is usable due to
getDecl().
Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CallExpr.html">CallExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXConstructExpr.html">CXXConstructExpr</a>&gt;,
Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1DeclRefExpr.html">DeclRefExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1EnumType.html">EnumType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1InjectedClassNameType.html">InjectedClassNameType</a>&gt;,
@ -2378,6 +2393,20 @@ with withInitializer matching (1)
</pre></td></tr>
<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXForRangeStmt.html">CXXForRangeStmt</a>&gt;</td><td class="name" onclick="toggle('hasLoopVariable0')"><a name="hasLoopVariable0Anchor">hasLoopVariable</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1VarDecl.html">VarDecl</a>&gt; InnerMatcher</td></tr>
<tr><td colspan="4" class="doc" id="hasLoopVariable0"><pre>Matches the initialization statement of a for loop.
Example:
forStmt(hasLoopVariable(anything()))
matches 'int x' in
for (int x : a) { }
</pre></td></tr>
<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXMemberCallExpr.html">CXXMemberCallExpr</a>&gt;</td><td class="name" onclick="toggle('onImplicitObjectArgument0')"><a name="onImplicitObjectArgument0Anchor">onImplicitObjectArgument</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt; InnerMatcher</td></tr>
<tr><td colspan="4" class="doc" id="onImplicitObjectArgument0"><pre></pre></td></tr>
<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXMemberCallExpr.html">CXXMemberCallExpr</a>&gt;</td><td class="name" onclick="toggle('on0')"><a name="on0Anchor">on</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt; InnerMatcher</td></tr>
<tr><td colspan="4" class="doc" id="on0"><pre>Matches on the implicit object argument of a member call expression.
@ -2389,15 +2418,17 @@ FIXME: Overload to allow directly matching types?
</pre></td></tr>
<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXMemberCallExpr.html">CXXMemberCallExpr</a>&gt;</td><td class="name" onclick="toggle('onImplicitObjectArgument0')"><a name="onImplicitObjectArgument0Anchor">onImplicitObjectArgument</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt; InnerMatcher</td></tr>
<tr><td colspan="4" class="doc" id="onImplicitObjectArgument0"><pre></pre></td></tr>
<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXMemberCallExpr.html">CXXMemberCallExpr</a>&gt;</td><td class="name" onclick="toggle('thisPointerType1')"><a name="thisPointerType1Anchor">thisPointerType</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt; InnerMatcher</td></tr>
<tr><td colspan="4" class="doc" id="thisPointerType1"><pre>Overloaded to match the type's declaration.
</pre></td></tr>
<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXMemberCallExpr.html">CXXMemberCallExpr</a>&gt;</td><td class="name" onclick="toggle('thisPointerType0')"><a name="thisPointerType0Anchor">thisPointerType</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt; InnerMatcher</td></tr>
<tr><td colspan="4" class="doc" id="thisPointerType0"><pre>Matches if the expression's type either matches the specified
matcher, or is a pointer to a type that matches the InnerMatcher.
</pre></td></tr>
<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXMethodDecl.html">CXXMethodDecl</a>&gt;</td><td class="name" onclick="toggle('ofClass0')"><a name="ofClass0Anchor">ofClass</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXRecordDecl.html">CXXRecordDecl</a>&gt; InnerMatcher</td></tr>
<tr><td colspan="4" class="doc" id="ofClass0"><pre>Matches the class declaration that the given method declaration
belongs to.
@ -2466,6 +2497,24 @@ Example matches y.x() (matcher = callExpr(callee(methodDecl(hasName("x")))))
</pre></td></tr>
<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CallExpr.html">CallExpr</a>&gt;</td><td class="name" onclick="toggle('callee0')"><a name="callee0Anchor">callee</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt; InnerMatcher</td></tr>
<tr><td colspan="4" class="doc" id="callee0"><pre>Matches if the call expression's callee expression matches.
Given
class Y { void x() { this-&gt;x(); x(); Y y; y.x(); } };
void f() { f(); }
callExpr(callee(expr()))
matches this-&gt;x(), x(), y.x(), f()
with callee(...)
matching this-&gt;x, x, y.x, f respectively
Note: Callee cannot take the more general internal::Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt;
because this introduces ambiguous overloads with calls to Callee taking a
internal::Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;, as the matcher hierarchy is purely
implemented in terms of implicit casts.
</pre></td></tr>
<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CallExpr.html">CallExpr</a>&gt;</td><td class="name" onclick="toggle('hasAnyArgument0')"><a name="hasAnyArgument0Anchor">hasAnyArgument</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt; InnerMatcher</td></tr>
<tr><td colspan="4" class="doc" id="hasAnyArgument0"><pre>Matches any argument of a call expression or a constructor call
expression.
@ -2506,8 +2555,6 @@ The associated declaration is:
Also usable as Matcher&lt;T&gt; for any T supporting the getDecl() member
function. e.g. various subtypes of clang::Type and various expressions.
FIXME: Add all node types for which this is matcher is usable due to
getDecl().
Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CallExpr.html">CallExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXConstructExpr.html">CXXConstructExpr</a>&gt;,
Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1DeclRefExpr.html">DeclRefExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1EnumType.html">EnumType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1InjectedClassNameType.html">InjectedClassNameType</a>&gt;,
@ -2647,8 +2694,6 @@ The associated declaration is:
Also usable as Matcher&lt;T&gt; for any T supporting the getDecl() member
function. e.g. various subtypes of clang::Type and various expressions.
FIXME: Add all node types for which this is matcher is usable due to
getDecl().
Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CallExpr.html">CallExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXConstructExpr.html">CXXConstructExpr</a>&gt;,
Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1DeclRefExpr.html">DeclRefExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1EnumType.html">EnumType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1InjectedClassNameType.html">InjectedClassNameType</a>&gt;,
@ -2813,8 +2858,6 @@ The associated declaration is:
Also usable as Matcher&lt;T&gt; for any T supporting the getDecl() member
function. e.g. various subtypes of clang::Type and various expressions.
FIXME: Add all node types for which this is matcher is usable due to
getDecl().
Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CallExpr.html">CallExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXConstructExpr.html">CXXConstructExpr</a>&gt;,
Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1DeclRefExpr.html">DeclRefExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1EnumType.html">EnumType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1InjectedClassNameType.html">InjectedClassNameType</a>&gt;,
@ -2852,6 +2895,17 @@ Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.h
</pre></td></tr>
<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt;</td><td class="name" onclick="toggle('hasType0')"><a name="hasType0Anchor">hasType</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt; InnerMatcher</td></tr>
<tr><td colspan="4" class="doc" id="hasType0"><pre>Matches if the expression's or declaration's type matches a type
matcher.
Example matches x (matcher = expr(hasType(recordDecl(hasName("X")))))
and z (matcher = varDecl(hasType(recordDecl(hasName("X")))))
class X {};
void y(X &amp;x) { x; X z; }
</pre></td></tr>
<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt;</td><td class="name" onclick="toggle('ignoringImpCasts0')"><a name="ignoringImpCasts0Anchor">ignoringImpCasts</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt; InnerMatcher</td></tr>
<tr><td colspan="4" class="doc" id="ignoringImpCasts0"><pre>Matches expressions that match InnerMatcher after any implicit casts
are stripped off.
@ -3034,8 +3088,6 @@ The associated declaration is:
Also usable as Matcher&lt;T&gt; for any T supporting the getDecl() member
function. e.g. various subtypes of clang::Type and various expressions.
FIXME: Add all node types for which this is matcher is usable due to
getDecl().
Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CallExpr.html">CallExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXConstructExpr.html">CXXConstructExpr</a>&gt;,
Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1DeclRefExpr.html">DeclRefExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1EnumType.html">EnumType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1InjectedClassNameType.html">InjectedClassNameType</a>&gt;,
@ -3058,8 +3110,6 @@ The associated declaration is:
Also usable as Matcher&lt;T&gt; for any T supporting the getDecl() member
function. e.g. various subtypes of clang::Type and various expressions.
FIXME: Add all node types for which this is matcher is usable due to
getDecl().
Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CallExpr.html">CallExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXConstructExpr.html">CXXConstructExpr</a>&gt;,
Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1DeclRefExpr.html">DeclRefExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1EnumType.html">EnumType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1InjectedClassNameType.html">InjectedClassNameType</a>&gt;,
@ -3082,8 +3132,6 @@ The associated declaration is:
Also usable as Matcher&lt;T&gt; for any T supporting the getDecl() member
function. e.g. various subtypes of clang::Type and various expressions.
FIXME: Add all node types for which this is matcher is usable due to
getDecl().
Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CallExpr.html">CallExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXConstructExpr.html">CXXConstructExpr</a>&gt;,
Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1DeclRefExpr.html">DeclRefExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1EnumType.html">EnumType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1InjectedClassNameType.html">InjectedClassNameType</a>&gt;,
@ -3290,8 +3338,6 @@ The associated declaration is:
Also usable as Matcher&lt;T&gt; for any T supporting the getDecl() member
function. e.g. various subtypes of clang::Type and various expressions.
FIXME: Add all node types for which this is matcher is usable due to
getDecl().
Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CallExpr.html">CallExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXConstructExpr.html">CXXConstructExpr</a>&gt;,
Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1DeclRefExpr.html">DeclRefExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1EnumType.html">EnumType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1InjectedClassNameType.html">InjectedClassNameType</a>&gt;,
@ -3307,11 +3353,36 @@ Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CallEx
</pre></td></tr>
<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt;</td><td class="name" onclick="toggle('pointsTo0')"><a name="pointsTo0Anchor">pointsTo</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt; InnerMatcher</td></tr>
<tr><td colspan="4" class="doc" id="pointsTo0"><pre>Matches if the matched type is a pointer type and the pointee type
matches the specified matcher.
Example matches y-&gt;x()
(matcher = callExpr(on(hasType(pointsTo(recordDecl(hasName("Y")))))))
class Y { public: void x(); };
void z() { Y *y; y-&gt;x(); }
</pre></td></tr>
<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt;</td><td class="name" onclick="toggle('references1')"><a name="references1Anchor">references</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt; InnerMatcher</td></tr>
<tr><td colspan="4" class="doc" id="references1"><pre>Overloaded to match the referenced type's declaration.
</pre></td></tr>
<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt;</td><td class="name" onclick="toggle('references0')"><a name="references0Anchor">references</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt; InnerMatcher</td></tr>
<tr><td colspan="4" class="doc" id="references0"><pre>Matches if the matched type is a reference type and the referenced
type matches the specified matcher.
Example matches X &amp;x and const X &amp;y
(matcher = varDecl(hasType(references(recordDecl(hasName("X"))))))
class X {
void a(X b) {
X &amp;x = b;
const X &amp;y = b;
};
</pre></td></tr>
<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1RecordType.html">RecordType</a>&gt;</td><td class="name" onclick="toggle('hasDeclaration5')"><a name="hasDeclaration5Anchor">hasDeclaration</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt; InnerMatcher</td></tr>
<tr><td colspan="4" class="doc" id="hasDeclaration5"><pre>Matches a node if the declaration associated with that node
matches the given matcher.
@ -3324,8 +3395,6 @@ The associated declaration is:
Also usable as Matcher&lt;T&gt; for any T supporting the getDecl() member
function. e.g. various subtypes of clang::Type and various expressions.
FIXME: Add all node types for which this is matcher is usable due to
getDecl().
Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CallExpr.html">CallExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXConstructExpr.html">CXXConstructExpr</a>&gt;,
Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1DeclRefExpr.html">DeclRefExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1EnumType.html">EnumType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1InjectedClassNameType.html">InjectedClassNameType</a>&gt;,
@ -3405,8 +3474,6 @@ The associated declaration is:
Also usable as Matcher&lt;T&gt; for any T supporting the getDecl() member
function. e.g. various subtypes of clang::Type and various expressions.
FIXME: Add all node types for which this is matcher is usable due to
getDecl().
Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CallExpr.html">CallExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXConstructExpr.html">CXXConstructExpr</a>&gt;,
Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1DeclRefExpr.html">DeclRefExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1EnumType.html">EnumType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1InjectedClassNameType.html">InjectedClassNameType</a>&gt;,
@ -3417,8 +3484,23 @@ Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CallEx
</pre></td></tr>
<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateArgument.html">TemplateArgument</a>&gt;</td><td class="name" onclick="toggle('isExpr0')"><a name="isExpr0Anchor">isExpr</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt; InnerMatcher</td></tr>
<tr><td colspan="4" class="doc" id="isExpr0"><pre>Matches a sugar TemplateArgument that refers to a certain expression.
Given
template&lt;typename T&gt; struct A {};
struct B { B* next; };
A&lt;&amp;B::next&gt; a;
templateSpecializationType(hasAnyTemplateArgument(
isExpr(hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))
matches the specialization A&lt;&amp;B::next&gt; with fieldDecl(...) matching
B::next
</pre></td></tr>
<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateArgument.html">TemplateArgument</a>&gt;</td><td class="name" onclick="toggle('refersToDeclaration0')"><a name="refersToDeclaration0Anchor">refersToDeclaration</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt; InnerMatcher</td></tr>
<tr><td colspan="4" class="doc" id="refersToDeclaration0"><pre>Matches a TemplateArgument that refers to a certain declaration.
<tr><td colspan="4" class="doc" id="refersToDeclaration0"><pre>Matches a canonical TemplateArgument that refers to a certain
declaration.
Given
template&lt;typename T&gt; struct A {};
@ -3444,6 +3526,20 @@ classTemplateSpecializationDecl(hasAnyTemplateArgument(
</pre></td></tr>
<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateSpecializationType.html">TemplateSpecializationType</a>&gt;</td><td class="name" onclick="toggle('hasAnyTemplateArgument1')"><a name="hasAnyTemplateArgument1Anchor">hasAnyTemplateArgument</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateArgument.html">TemplateArgument</a>&gt; InnerMatcher</td></tr>
<tr><td colspan="4" class="doc" id="hasAnyTemplateArgument1"><pre>Matches classTemplateSpecializations that have at least one
TemplateArgument matching the given InnerMatcher.
Given
template&lt;typename T&gt; class A {};
template&lt;&gt; class A&lt;double&gt; {};
A&lt;int&gt; a;
classTemplateSpecializationDecl(hasAnyTemplateArgument(
refersToType(asString("int"))))
matches the specialization A&lt;int&gt;
</pre></td></tr>
<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateSpecializationType.html">TemplateSpecializationType</a>&gt;</td><td class="name" onclick="toggle('hasDeclaration3')"><a name="hasDeclaration3Anchor">hasDeclaration</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt; InnerMatcher</td></tr>
<tr><td colspan="4" class="doc" id="hasDeclaration3"><pre>Matches a node if the declaration associated with that node
matches the given matcher.
@ -3456,8 +3552,6 @@ The associated declaration is:
Also usable as Matcher&lt;T&gt; for any T supporting the getDecl() member
function. e.g. various subtypes of clang::Type and various expressions.
FIXME: Add all node types for which this is matcher is usable due to
getDecl().
Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CallExpr.html">CallExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXConstructExpr.html">CXXConstructExpr</a>&gt;,
Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1DeclRefExpr.html">DeclRefExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1EnumType.html">EnumType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1InjectedClassNameType.html">InjectedClassNameType</a>&gt;,
@ -3468,6 +3562,20 @@ Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CallEx
</pre></td></tr>
<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateSpecializationType.html">TemplateSpecializationType</a>&gt;</td><td class="name" onclick="toggle('hasTemplateArgument1')"><a name="hasTemplateArgument1Anchor">hasTemplateArgument</a></td><td>unsigned N, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateArgument.html">TemplateArgument</a>&gt; InnerMatcher</td></tr>
<tr><td colspan="4" class="doc" id="hasTemplateArgument1"><pre>Matches classTemplateSpecializations where the n'th TemplateArgument
matches the given InnerMatcher.
Given
template&lt;typename T, typename U&gt; class A {};
A&lt;bool, int&gt; b;
A&lt;int, bool&gt; c;
classTemplateSpecializationDecl(hasTemplateArgument(
1, refersToType(asString("int"))))
matches the specialization A&lt;bool, int&gt;
</pre></td></tr>
<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateTypeParmType.html">TemplateTypeParmType</a>&gt;</td><td class="name" onclick="toggle('hasDeclaration2')"><a name="hasDeclaration2Anchor">hasDeclaration</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt; InnerMatcher</td></tr>
<tr><td colspan="4" class="doc" id="hasDeclaration2"><pre>Matches a node if the declaration associated with that node
matches the given matcher.
@ -3480,8 +3588,6 @@ The associated declaration is:
Also usable as Matcher&lt;T&gt; for any T supporting the getDecl() member
function. e.g. various subtypes of clang::Type and various expressions.
FIXME: Add all node types for which this is matcher is usable due to
getDecl().
Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CallExpr.html">CallExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXConstructExpr.html">CXXConstructExpr</a>&gt;,
Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1DeclRefExpr.html">DeclRefExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1EnumType.html">EnumType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1InjectedClassNameType.html">InjectedClassNameType</a>&gt;,
@ -3525,8 +3631,6 @@ The associated declaration is:
Also usable as Matcher&lt;T&gt; for any T supporting the getDecl() member
function. e.g. various subtypes of clang::Type and various expressions.
FIXME: Add all node types for which this is matcher is usable due to
getDecl().
Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CallExpr.html">CallExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXConstructExpr.html">CXXConstructExpr</a>&gt;,
Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1DeclRefExpr.html">DeclRefExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1EnumType.html">EnumType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1InjectedClassNameType.html">InjectedClassNameType</a>&gt;,
@ -3567,8 +3671,6 @@ The associated declaration is:
Also usable as Matcher&lt;T&gt; for any T supporting the getDecl() member
function. e.g. various subtypes of clang::Type and various expressions.
FIXME: Add all node types for which this is matcher is usable due to
getDecl().
Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CallExpr.html">CallExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXConstructExpr.html">CXXConstructExpr</a>&gt;,
Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1DeclRefExpr.html">DeclRefExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1EnumType.html">EnumType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1InjectedClassNameType.html">InjectedClassNameType</a>&gt;,
@ -3620,6 +3722,17 @@ Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.h
</pre></td></tr>
<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ValueDecl.html">ValueDecl</a>&gt;</td><td class="name" onclick="toggle('hasType1')"><a name="hasType1Anchor">hasType</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt; InnerMatcher</td></tr>
<tr><td colspan="4" class="doc" id="hasType1"><pre>Matches if the expression's or declaration's type matches a type
matcher.
Example matches x (matcher = expr(hasType(recordDecl(hasName("X")))))
and z (matcher = varDecl(hasType(recordDecl(hasName("X")))))
class X {};
void y(X &amp;x) { x; X z; }
</pre></td></tr>
<tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1VarDecl.html">VarDecl</a>&gt;</td><td class="name" onclick="toggle('hasInitializer0')"><a name="hasInitializer0Anchor">hasInitializer</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt; InnerMatcher</td></tr>
<tr><td colspan="4" class="doc" id="hasInitializer0"><pre>Matches a variable declaration that has an initializer expression
that matches the given matcher.

View File

@ -137,6 +137,10 @@ documentation <LibTooling.html>`_.
using namespace clang::tooling;
using namespace llvm;
// Apply a custom category to all command-line options so that they are the
// only ones displayed.
static llvm::cl::OptionCategory MyToolCategory("my-tool options");
// CommonOptionsParser declares HelpMessage with a description of the common
// command-line options related to the compilation database and input files.
// It's nice to have this help message in all tools.
@ -146,7 +150,7 @@ documentation <LibTooling.html>`_.
static cl::extrahelp MoreHelp("\nMore help text...");
int main(int argc, const char **argv) {
CommonOptionsParser OptionsParser(argc, argv);
CommonOptionsParser OptionsParser(argc, argv, MyToolCategory);
ClangTool Tool(OptionsParser.getCompilations(),
OptionsParser.getSourcePathList());
return Tool.run(newFrontendActionFactory<clang::SyntaxOnlyAction>());
@ -287,7 +291,7 @@ And change ``main()`` to:
.. code-block:: c++
int main(int argc, const char **argv) {
CommonOptionsParser OptionsParser(argc, argv);
CommonOptionsParser OptionsParser(argc, argv, MyToolCategory);
ClangTool Tool(OptionsParser.getCompilations(),
OptionsParser.getSourcePathList());

View File

@ -0,0 +1,121 @@
.. raw:: html
<style type="text/css">
.none { background-color: #FFCCCC }
.partial { background-color: #FFFF99 }
.good { background-color: #CCFF99 }
</style>
.. role:: none
.. role:: partial
.. role:: good
==================
MSVC compatibility
==================
When Clang compiles C++ code for Windows, it attempts to be compatible with
MSVC. There are multiple dimensions to compatibility.
First, Clang attempts to be ABI-compatible, meaning that Clang-compiled code
should be able to link against MSVC-compiled code successfully. However, C++
ABIs are particular large and complicated, and Clang's support for MSVC's C++
ABI is a work in progress. If you don't require MSVC ABI compatibility or don't
want to use Microsoft's C and C++ runtimes, the mingw32 toolchain might be a
better fit for your project.
Second, Clang implements many MSVC language extensions, such as
``__declspec(dllexport)`` and a handful of pragmas. These are typically
controlled by ``-fms-extensions``.
Finally, MSVC accepts some C++ code that Clang will typically diagnose as
invalid. When these constructs are present in widely included system headers,
Clang attempts to recover and continue compiling the user's program. Most
parsing and semantic compatibility tweaks are controlled by
``-fms-compatibility`` and ``-fdelayed-template-parsing``, and they are a work
in progress.
ABI features
============
The status of major ABI-impacting C++ features:
* Record layout: :good:`Mostly complete`. We've attacked this with a fuzzer,
and most of the remaining failures involve ``#pragma pack``,
``__declspec(align(N))``, or other pragmas.
* Class inheritance: :good:`Mostly complete`. This covers all of the standard
OO features you would expect: virtual method inheritance, multiple
inheritance, and virtual inheritance. Every so often we uncover a bug where
our tables are incompatible, but this is pretty well in hand.
* Name mangling: :good:`Ongoing`. Every new C++ feature generally needs its own
mangling. For example, member pointer template arguments have an interesting
and distinct mangling. Fortunately, incorrect manglings usually do not result
in runtime errors. Non-inline functions with incorrect manglings usually
result in link errors, which are relatively easy to diagnose. Incorrect
manglings for inline functions and templates result in multiple copies in the
final image. The C++ standard requires that those addresses be equal, but few
programs rely on this.
* Member pointers: :good:`Mostly complete`. Standard C++ member pointers are
fully implemented and should be ABI compatible. Both `#pragma
pointers_to_members`_ and the `/vm`_ flags are supported. However, MSVC
supports an extension to allow creating a `pointer to a member of a virtual
base class`_. Clang does not yet support this.
.. _#pragma pointers_to_members:
http://msdn.microsoft.com/en-us/library/83cch5a6.aspx
.. _/vm: http://msdn.microsoft.com/en-us/library/yad46a6z.aspx
.. _pointer to a member of a virtual base class: http://llvm.org/PR15713
* Debug info: :partial:`Minimal`. Clang emits CodeView line tables into the
object file, similar to what MSVC emits when given the ``/Z7`` flag.
Microsoft's link.exe will read this information and use it to create a PDB,
enabling stack traces in all modern Windows debuggers. Clang does not emit
any type info or description of variable layout.
* `RTTI`_: :none:`Unstarted`. See the bug for a discussion of what needs to
happen first.
.. _RTTI: http://llvm.org/PR18951
* Exceptions and SEH: :none:`Unstarted`. Clang can parse both constructs, but
does not know how to emit compatible handlers. This depends on RTTI.
* Thread-safe initialization of local statics: :none:`Unstarted`. We are ABI
compatible with MSVC 2012, which does not support thread-safe local statics.
MSVC 2013 changed the ABI to make initialization of local statics thread safe,
and we have not yet implemented this.
* Lambdas in ABI boundaries: :none:`Infeasible`. It is unlikely that we will
ever be fully ABI compatible with lambdas declared in inline functions due to
what appears to be a hash code in the name mangling. Lambdas that are not
externally visible should work fine.
Template instantiation and name lookup
======================================
In addition to the usual `dependent name lookup FAQs `_, Clang is often unable
to parse certain invalid C++ constructs that MSVC allows. As of this writing,
Clang will reject code with missing ``typename`` annotations:
.. _dependent name lookup FAQs:
http://clang.llvm.org/compatibility.html#dep_lookup
.. code-block:: c++
struct X {
typedef int type;
};
template<typename T> int f() {
// missing typename keyword
return sizeof(/*typename*/ T::type);
}
template void f<X>();
Accepting code like this is ongoing work. Ultimately, it may be cleaner to
`implement a token-based template instantiation mode`_ than it is to add
compatibility hacks to the existing AST-based instantiation.
.. _implement a token-based template instantiation mode: http://llvm.org/PR18714

View File

@ -198,6 +198,40 @@ Command-line parameters
``-fmodule-map-file=<file>``
Load the given module map file if a header from its directory or one of its subdirectories is loaded.
Module Semantics
================
Modules are modeled as if each submodule were a separate translation unit, and a module import makes names from the other translation unit visible. Each submodule starts with a new preprocessor state and an empty translation unit.
.. note::
This behavior is currently only approximated when building a module. Entities within a submodule that has already been built are visible when building later submodules in that module. This can lead to fragile modules that depend on the build order used for the submodules of the module, and should not be relied upon.
As an example, in C, this implies that if two structs are defined in different submodules with the same name, those two types are distinct types (but may be *compatible* types if their definitions match. In C++, two structs defined with the same name in different submodules are the *same* type, and must be equivalent under C++'s One Definition Rule.
.. note::
Clang currently only performs minimal checking for violations of the One Definition Rule.
Macros
------
The C and C++ preprocessor assumes that the input text is a single linear buffer, but with modules this is not the case. It is possible to import two modules that have conflicting definitions for a macro (or where one ``#define``\s a macro and the other ``#undef``\ines it). The rules for handling macro definitions in the presence of modules are as follows:
* Each definition and undefinition of a macro is considered to be a distinct entity.
* Such entities are *visible* if they are from the current submodule or translation unit, or if they were exported from a submodule that has been imported.
* A ``#define X`` or ``#undef X`` directive *overrides* all definitions of ``X`` that are visible at the point of the directive.
* A ``#define`` or ``#undef`` directive is *active* if it is visible and no visible directive overrides it.
* A set of macro directives is *consistent* if it consists of only ``#undef`` directives, or if all ``#define`` directives in the set define the macro name to the same sequence of tokens (following the usual rules for macro redefinitions).
* If a macro name is used and the set of active directives is not consistent, the program is ill-formed. Otherwise, the (unique) meaning of the macro name is used.
For example, suppose:
* ``<stdio.h>`` defines a macro ``getc`` (and exports its ``#define``)
* ``<cstdio>`` imports the ``<stdio.h>`` module and undefines the macro (and exports its ``#undef``)
The ``#undef`` overrides the ``#define``, and a source file that imports both modules *in any order* will not see ``getc`` defined as a macro.
Module Map Language
===================
@ -573,7 +607,7 @@ A *use-declaration* specifies one of the other modules that the module is allowe
use B
}
When compiling a source file that implements a module, use the option ``-fmodule-name=``module-id to indicate that the source file is logically part of that module.
When compiling a source file that implements a module, use the option ``-fmodule-name=module-id`` to indicate that the source file is logically part of that module.
The compiler at present only applies restrictions to the module directly being built.

View File

@ -48,13 +48,13 @@ Major New Features
------------------
- Clang uses the new MingW ABI
GCC 4.7 changed the mingw ABI. Clang 3.4 and older use the GCC 4.6
ABI. Clang 3.5 and newer use the GCC 4.7 abi.
GCC 4.7 changed the mingw ABI. Clang 3.4 and older use the GCC 4.6
ABI. Clang 3.5 and newer use the GCC 4.7 abi.
- The __has_attribute feature test is now target-aware. Older versions of Clang
would return true when the attribute spelling was known, regardless of whether
the attribute was available to the specific target. Clang now returns true only
when the attribute pertains to the current compilation target.
would return true when the attribute spelling was known, regardless of whether
the attribute was available to the specific target. Clang now returns true only
when the attribute pertains to the current compilation target.
Improvements to Clang's diagnostics
@ -70,16 +70,24 @@ New Compiler Flags
------------------
The integrated assembler is now turned on by default on ARM (and Thumb),
so the use of the option `-integrated-as` is now redundant on those
so the use of the option `-fintegrated-as` is now redundant on those
architectures. This is an important move to both *eat our own dog food*
and to ease cross-compilation tremendously.
We are aware of the problems that this may cause for code bases that
rely on specific GNU syntax or extensions, and we're working towards
getting them all fixed. Please, report bugs or feature requests if
you find anything. In the meantime, use `-no-integrated-as` to revert
you find anything. In the meantime, use `-fno-integrated-as` to revert
back the call to GNU assembler.
In order to provide better diagnostics, the integrated assembler validates
inline assembly when the integrated assembler is enabled. Because this is
considered a feature of the compiler, it is controlled via the `fintegrated-as`
and `fno-integrated-as` flags which enable and disable the integrated assembler
respectively. `-integrated-as` and `-no-integrated-as` are now considered
legacy flags (but are available as an alias to prevent breaking existing users),
and users are encouraged to switch to the equivalent new feature flag.
C Language Changes in Clang
---------------------------

View File

@ -0,0 +1,818 @@
======================
Thread Safety Analysis
======================
Introduction
============
Clang Thread Safety Analysis is a C++ language extension which warns about
potential race conditions in code. The analysis is completely static (i.e.
compile-time); there is no run-time overhead. The analysis is still
under active development, but it is mature enough to be deployed in an
industrial setting. It being developed by Google, and is used extensively
on their internal code base.
Thread safety analysis works very much like a type system for multi-threaded
programs. In addition to declaring the *type* of data (e.g. ``int``, ``float``,
etc.), the programmer can (optionally) declare how access to that data is
controlled in a multi-threaded environment. For example, if ``foo`` is
*guarded by* the mutex ``mu``, then the analysis will issue a warning whenever
a piece of code reads or writes to ``foo`` without first locking ``mu``.
Similarly, if there are particular routines that should only be called by
the GUI thread, then the analysis will warn if other threads call those
routines.
Getting Started
----------------
.. code-block:: c++
#include "mutex.h"
class BankAccount {
private:
Mutex mu;
int balance GUARDED_BY(mu);
void depositImpl(int amount) {
balance += amount; // WARNING! Cannot write balance without locking mu.
}
void withdrawImpl(int amount) EXCLUSIVE_LOCKS_REQUIRED(mu) {
balance -= amount; // OK. Caller must have locked mu.
}
public:
void withdraw(int amount) {
mu.Lock();
withdrawImpl(amount); // OK. We've locked mu.
} // WARNING! Failed to unlock mu.
void transferFrom(BankAccount& b, int amount) {
mu.Lock();
b.withdrawImpl(amount); // WARNING! Calling withdrawImpl() requires locking b.mu.
depositImpl(amount); // OK. depositImpl() has no requirements.
mu.Unlock();
}
};
This example demonstrates the basic concepts behind the analysis. The
``GUARDED_BY`` attribute declares that a thread must lock ``mu`` before it can
read or write to ``balance``, thus ensuring that the increment and decrement
operations are atomic. Similarly, ``EXCLUSIVE_LOCKS_REQUIRED`` declares that
the calling thread must lock ``mu`` before calling ``withdrawImpl``.
Because the caller is assumed to have locked ``mu``, it is safe to modify
``balance`` within the body of the method.
The ``depositImpl()`` method does not have ``EXCLUSIVE_LOCKS_REQUIRED``, so the
analysis issues a warning. Thread safety analysis is not inter-procedural, so
caller requirements must be explicitly declared.
There is also a warning in ``transferFrom()``, because although the method
locks ``this->mu``, it does not lock ``b.mu``. The analysis understands
that these are two separate mutexes, in two different objects.
Finally, there is a warning in the ``withdraw()`` method, because it fails to
unlock ``mu``. Every lock must have a corresponding unlock, and the analysis
will detect both double locks, and double unlocks. A function is allowed to
acquire a lock without releasing it, (or vice versa), but it must be annotated
as such (using ``LOCK``/``UNLOCK_FUNCTION``).
Running The Analysis
--------------------
To run the analysis, simply compile with the ``-Wthread-safety`` flag, e.g.
.. code-block:: bash
clang -c -Wthread-safety example.cpp
Note that this example assumes the presence of a suitably annotated
:ref:`mutexheader` that declares which methods perform locking,
unlocking, and so on.
Basic Concepts: Capabilities
============================
Thread safety analysis provides a way of protecting *resources* with
*capabilities*. A resource is either a data member, or a function/method
that provides access to some underlying resource. The analysis ensures that
the calling thread cannot access the *resource* (i.e. call the function, or
read/write the data) unless it has the *capability* to do so.
Capabilities are associated with named C++ objects which declare specific
methods to acquire and release the capability. The name of the object serves
to identify the capability. The most common example is a mutex. For example,
if ``mu`` is a mutex, then calling ``mu.Lock()`` causes the calling thread
to acquire the capability to access data that is protected by ``mu``. Similarly,
calling ``mu.Unlock()`` releases that capability.
A thread may hold a capability either *exclusively* or *shared*. An exclusive
capability can be held by only one thread at a time, while a shared capability
can be held by many threads at the same time. This mechanism enforces a
multiple-reader, single-writer pattern. Write operations to protected data
require exclusive access, while read operations require only shared access.
At any given moment during program execution, a thread holds a specific set of
capabilities (e.g. the set of mutexes that it has locked.) These act like keys
or tokens that allow the thread to access a given resource. Just like physical
security keys, a thread cannot make copy of a capability, nor can it destroy
one. A thread can only release a capability to another thread, or acquire one
from another thread. The annotations are deliberately agnostic about the
exact mechanism used to acquire and release capabilities; it assumes that the
underlying implementation (e.g. the Mutex implementation) does the handoff in
an appropriate manner.
The set of capabilities that are actually held by a given thread at a given
point in program execution is a run-time concept. The static analysis works
by calculating an approximation of that set, called the *capability
environment*. The capability environment is calculated for every program point,
and describes the set of capabilities that are statically known to be held, or
not held, at that particular point. This environment is a conservative
approximation of the full set of capabilities that will actually held by a
thread at run-time.
Reference Guide
===============
The thread safety analysis uses attributes to declare threading constraints.
Attributes must be attached to named declarations, such as classes, methods,
and data members. Users are *strongly advised* to define macros for the various
attributes; example definitions can be found in :ref:`mutexheader`, below.
The following documentation assumes the use of macros.
GUARDED_BY(c) and PT_GUARDED_BY(c)
----------------------------------
``GUARDED_BY`` is an attribute on data members, which declares that the data
member is protected by the given capability. Read operations on the data
require shared access, while write operations require exclusive access.
``PT_GUARDED_BY`` is similar, but is intended for use on pointers and smart
pointers. There is no constraint on the data member itself, but the *data that
it points to* is protected by the given capability.
.. code-block:: c++
Mutex mu;
int *p1 GUARDED_BY(mu);
int *p2 PT_GUARDED_BY(mu);
unique_ptr<int> p3 PT_GUARDED_BY(mu);
void test() {
p1 = 0; // Warning!
p2 = new int; // OK.
*p2 = 42; // Warning!
p3.reset(new int); // OK.
*p3 = 42; // Warning!
}
EXCLUSIVE_LOCKS_REQUIRED(...), SHARED_LOCKS_REQUIRED(...)
---------------------------------------------------------
``EXCLUSIVE_LOCKS_REQUIRED`` is an attribute on functions or methods, which
declares that the calling thread must have exclusive access to the given
capabilities. More than one capability may be specified. The capabilities
must be held on entry to the function, *and must still be held on exit*.
``SHARED_LOCKS_REQUIRED`` is similar, but requires only shared access.
.. code-block:: c++
Mutex mu1, mu2;
int a GUARDED_BY(mu1);
int b GUARDED_BY(mu2);
void foo() EXCLUSIVE_LOCKS_REQUIRED(mu1, mu2) {
a = 0;
b = 0;
}
void test() {
mu1.Lock();
foo(); // Warning! Requires mu2.
mu1.Unlock();
}
EXCLUSIVE_LOCK_FUNCTION(...), SHARED_LOCK_FUNCTION(...), UNLOCK_FUNCTION(...)
-----------------------------------------------------------------------------
``EXCLUSIVE_LOCK_FUNCTION`` is an attribute on functions or methods, which
declares that the function acquires a capability, but does not release it. The
caller must not hold the given capability on entry, and it will hold the
capability on exit. ``SHARED_LOCK_FUNCTION`` is similar.
``UNLOCK_FUNCTION`` declares that the function releases the given capability.
The caller must hold the capability on entry, and will no longer hold it on
exit. It does not matter whether the given capability is shared or exclusive.
.. code-block:: c++
Mutex mu;
MyClass myObject GUARDED_BY(mu);
void lockAndInit() EXCLUSIVE_LOCK_FUNCTION(mu) {
mu.Lock();
myObject.init();
}
void cleanupAndUnlock() UNLOCK_FUNCTION(mu) {
myObject.cleanup();
} // Warning! Need to unlock mu.
void test() {
lockAndInit();
myObject.doSomething();
cleanupAndUnlock();
myObject.doSomething(); // Warning, mu is not locked.
}
If no argument is passed to ``(UN)LOCK_FUNCTION``, then the argument is assumed
to be ``this``, and the analysis will not check the body of the function. This
pattern is intended for use by classes which hide locking details behind an
abstract interface. E.g.
.. code-block:: c++
template <class T>
class LOCKABLE Container {
private:
Mutex mu;
T* data;
public:
// Hide mu from public interface.
void Lock() EXCLUSIVE_LOCK_FUNCTION() { mu.Lock(); }
void Unlock() UNLOCK_FUNCTION() { mu.Unlock(); }
T& getElem(int i) { return data[i]; }
};
void test() {
Container<int> c;
c.Lock();
int i = c.getElem(0);
c.Unlock();
}
LOCKS_EXCLUDED(...)
-------------------
``LOCKS_EXCLUDED`` is an attribute on functions or methods, which declares that
the caller must *not* hold the given capabilities. This annotation is
used to prevent deadlock. Many mutex implementations are not re-entrant, so
deadlock can occur if the function in question acquires the mutex a second time.
.. code-block:: c++
Mutex mu;
int a GUARDED_BY(mu);
void clear() LOCKS_EXCLUDED(mu) {
mu.Lock();
a = 0;
mu.Unlock();
}
void reset() {
mu.Lock();
clear(); // Warning! Caller cannot hold 'mu'.
mu.Unlock();
}
Unlike ``LOCKS_REQUIRED``, ``LOCKS_EXCLUDED`` is optional. The analysis will
not issue a warning if the attribute is missing. See :ref:`limitations`.
NO_THREAD_SAFETY_ANALYSIS
-------------------------
``NO_THREAD_SAFETY_ANALYSIS`` is an attribute on functions or methods, which
turns off thread safety checking for that method. It provides an escape hatch
for functions which are either (1) deliberately thread-unsafe, or (2) are
thread-safe, but too complicated for the analysis to understand. Reasons for
(2) will be described in the :ref:`limitations`, below.
.. code-block:: c++
class Counter {
Mutex mu;
int a GUARDED_BY(mu);
void unsafeIncrement() NO_THREAD_SAFETY_ANALYSIS { a++; }
};
LOCK_RETURNED(c)
----------------
``LOCK_RETURNED`` is an attribute on functions or methods, which declares that
the function returns a reference to the given capability. It is used to
annotate getter methods that return mutexes.
.. code-block:: c++
class MyClass {
private:
Mutex mu;
int a GUARDED_BY(mu);
public:
Mutex* getMu() LOCK_RETURNED(mu) { return &mu; }
// analysis knows that getMu() == mu
void clear() EXCLUSIVE_LOCKS_REQUIRED(getMu()) { a = 0; }
};
ACQUIRED_BEFORE(...), ACQUIRED_AFTER(...)
-----------------------------------------
``ACQUIRED_BEFORE`` and ``ACQUIRED_AFTER`` are attributes on member
declarations, specifically declarations of mutexes or other capabilities.
These declarations enforce a particular order in which the mutexes must be
acquired, in order to prevent deadlock.
.. code-block:: c++
Mutex m1;
Mutex m2 ACQUIRED_AFTER(m1);
// Alternative declaration
// Mutex m2;
// Mutex m1 ACQUIRED_BEFORE(m2);
void foo() {
m2.Lock();
m1.Lock(); // Warning! m2 must be acquired after m1.
m1.Unlock();
m2.Unlock();
}
LOCKABLE
--------
``LOCKABLE`` is an attribute on classes, which specifies that objects of the
class can be used as a capability. See the ``Container`` example given above,
or the ``Mutex`` class in :ref:`mutexheader`.
SCOPED_LOCKABLE
---------------
``SCOPED_LOCKABLE`` is an attribute on classes that implement RAII-style
locking, in which a capability is acquired in the constructor, and released in
the destructor. Such classes require special handling because the constructor
and destructor refer to the capability via different names; see the
``MutexLocker`` class in :ref:`mutexheader`, below.
EXCLUSIVE_TRYLOCK_FUNCTION(<bool>, ...), SHARED_TRYLOCK_FUNCTION(<bool>, ...)
-----------------------------------------------------------------------------
These are attributes on a function or method that tries to acquire the given
capability, and returns a boolean value indicating success or failure.
The first argument must be ``true`` or ``false``, to specify which return value
indicates success, and the remaining arguments are interpreted in the same way
as ``(UN)LOCK_FUNCTION``. See :ref:`mutexheader`, below, for example uses.
ASSERT_EXCLUSIVE_LOCK(...) and ASSERT_SHARED_LOCK(...)
------------------------------------------------------
These are attributes on a function or method that does a run-time test to see
whether the calling thread holds the given capability. The function is assumed
to fail (no return) if the capability is not held. See :ref:`mutexheader`,
below, for example uses.
GUARDED_VAR and PT_GUARDED_VAR
------------------------------
Use of these attributes has been deprecated.
Warning flags
-------------
* ``-Wthread-safety``: Umbrella flag which turns on the following three:
+ ``-Wthread-safety-attributes``: Sanity checks on attribute syntax.
+ ``-Wthread-safety-analysis``: The core analysis.
+ ``-Wthread-safety-precise``: Requires that mutex expressions match precisely.
This warning can be disabled for code which has a lot of aliases.
When new features and checks are added to the analysis, they can often introduce
additional warnings. Those warnings are initially released as *beta* warnings
for a period of time, after which they are migrated to the standard analysis.
* ``-Wthread-safety-beta``: New features. Off by default.
.. _faq:
Frequently Asked Questions
==========================
(Q) Should I put attributes in the header file, or in the .cc/.cpp/.cxx file?
(A) Attributes should always go in the header.
(Q) "*Mutex is not locked on every path through here?*" What does that mean?
(A) See :ref:`conditional_locks`, below.
.. _limitations:
Known Limitations
=================
Lexical scope
-------------
Thread safety attributes contain ordinary C++ expressions, and thus follow
ordinary C++ scoping rules. In particular, this means that mutexes and other
capabilities must be declared before they can be used in an attribute.
Use-before-declaration is okay within a single class, because attributes are
parsed at the same time as method bodies. (C++ delays parsing of method bodies
until the end of the class.) However, use-before-declaration is not allowed
between classes, as illustrated below.
.. code-block:: c++
class Foo;
class Bar {
void bar(Foo* f) EXCLUSIVE_LOCKS_REQUIRED(f->mu); // Error: mu undeclared.
};
class Foo {
Mutex mu;
};
Private Mutexes
---------------
Good software engineering practice dictates that mutexes should be private
members, because the locking mechanism used by a thread-safe class is part of
its internal implementation. However, private mutexes can sometimes leak into
the public interface of a class.
Thread safety attributes follow normal C++ access restrictions, so if ``mu``
is a private member of ``c``, then it is an error to write ``c.mu`` in an
attribute.
One workround is to (ab)use the ``LOCK_RETURNED`` attribute to provide a public
*name* for a private mutex, without actually exposing the underlying mutex.
For example:
.. code-block:: c++
class MyClass {
private:
Mutex mu;
public:
// For thread safety analysis only. Does not actually return mu.
Mutex* getMu() LOCK_RETURNED(mu) { return 0; }
void doSomething() EXCLUSIVE_LOCKS_REQUIRED(mu);
};
void doSomethingTwice(MyClass& c) EXCLUSIVE_LOCKS_REQUIRED(c.getMu()) {
// The analysis thinks that c.getMu() == c.mu
c.doSomething();
c.doSomething();
}
In the above example, ``doSomethingTwice()`` is an external routine that
requires ``c.mu`` to be locked, which cannot be declared directly because ``mu``
is private. This pattern is discouraged because it
violates encapsulation, but it is sometimes necessary, especially when adding
annotations to an existing code base. The workaround is to define ``getMu()``
as a fake getter method, which is provided only for the benefit of thread
safety analysis.
False negatives on pass by reference.
-------------------------------------
The current version of the analysis only checks operations which refer to
guarded data members directly by name. If the data members are accessed
indirectly, via a pointer or reference, then no warning is generated. Thus,
no warnings will be generated for the following code:
.. code-block:: c++
Mutex mu;
int a GUARDED_BY(mu);
void clear(int& ra) { ra = 0; }
void test() {
int *p = &a;
*p = 0; // No warning. *p is an alias to a.
clear(a); // No warning. 'a' is passed by reference.
}
This issue is by far the biggest source of false negatives in the current
version of the analysis. At a fundamental level, the
false negatives are caused by the fact that annotations are attached to data
members, rather than types. The type of ``&a`` should really be
``int GUARDED_BY(mu)*``, rather than ``int*``, and the statement ``p = &a``
should thus generate a type error. However, attaching attributes to types
would be an invasive change to the C++ type system, with potential
ramifications with respect to template instantation, function overloading,
and so on. Thus, a complete solution to this issue is simply not feasible.
Future versions of the analysis will include better support for pointer
alias analysis, along with limited checking of guarded types, in order to
reduce the number of false negatives.
.. _conditional_locks:
No conditionally held locks.
----------------------------
The analysis must be able to determine whether a lock is held, or not held, at
every program point. Thus, sections of code where a lock *might be held* will
generate spurious warnings (false positives). For example:
.. code-block:: c++
void foo() {
bool b = needsToLock();
if (b) mu.Lock();
... // Warning! Mutex 'mu' is not held on every path through here.
if (b) mu.Unlock();
}
No checking inside constructors and destructors.
------------------------------------------------
The analysis currently does not do any checking inside constructors or
destructors. In other words, every constructor and destructor is treated as
if it was annotated with ``NO_THREAD_SAFETY_ANALYSIS``.
The reason for this is that during initialization, only one thread typically
has access to the object which is being initialized, and it is thus safe (and
common practice) to initialize guarded members without acquiring any locks.
The same is true of destructors.
Ideally, the analysis would allow initialization of guarded members inside the
object being initialized or destroyed, while still enforcing the usual access
restrictions on everything else. However, this is difficult to enforce in
practice, because in complex pointer-based data structures, it is hard to
determine what data is "owned by" the enclosing object.
No inlining.
------------
Thread safety analysis is strictly intra-procedural, just like ordinary type
checking. It relies only on the declared attributes of a function, and will
not attempt to "step inside", or inline any method calls. As a result, code
such as the following will not work:
.. code-block:: c++
template<class T>
class AutoCleanup {
T* object;
void (T::*mp)();
public:
AutoCleanup(T* obj, void (T::*imp)()) : object(obj), mp(imp) { }
~AutoCleanup() { (object->*mp)(); }
};
Mutex mu;
void foo() {
mu.Lock();
AutoCleanup<Mutex>(&mu, &Mutex::Unlock);
...
} // Warning, mu is not unlocked.
In this case, the destructor of ``Autocleanup`` calls ``mu.Unlock()``, so
the warning is bogus. However,
thread safety analysis cannot see the unlock, because it does not attempt to
inline the destructor. Moreover, there is no way to annotate the destructor,
because the destructor is calling a function that is not statically known.
This pattern is simply not supported.
LOCKS_EXCLUDED is not transitive.
---------------------------------
A function which calls a method marked with LOCKS_EXCLUDED is not required to
put LOCKS_EXCLUDED in its own interface. LOCKS_EXCLUDED behaves differently
from LOCKS_REQUIRED in this respect, and it can result in false negatives:
.. code-block:: c++
class Foo {
Mutex mu;
void foo() {
mu.Lock();
bar(); // No warning
mu.Unlock();
}
void bar() { baz(); } // No warning. (Should have LOCKS_EXCLUDED(mu).)
void baz() LOCKS_EXCLUDED(mu);
};
The lack of transitivity is due to the fact that LOCKS_EXCLUDED can easily
break encapsulation; it would be a bad idea to require functions to list the
names private locks which happen to be acquired internally.
No alias analysis.
------------------
The analysis currently does not track pointer aliases. Thus, there can be
false positives if two pointers both point to the same mutex.
.. code-block:: c++
class MutexUnlocker {
Mutex* mu;
public:
MutexUnlocker(Mutex* m) UNLOCK_FUNCTION(m) : mu(m) { mu->Unlock(); }
~MutexUnlocker() EXCLUSIVE_LOCK_FUNCTION(mu) { mu->Lock(); }
};
Mutex mutex;
void test() EXCLUSIVE_LOCKS_REQUIRED(mutex) {
{
MutexUnlocker munl(&mutex); // unlocks mutex
doSomeIO();
} // Warning: locks munl.mu
}
The MutexUnlocker class is intended to be the dual of the MutexLocker class,
defined in :ref:`mutexheader`. However, it doesn't work because the analysis
doesn't know that munl.mu == mutex. The SCOPED_LOCKABLE attribute handles
aliasing
ACQUIRED_BEFORE(...) and ACQUIRED_AFTER(...) are currently unimplemented.
-------------------------------------------------------------------------
To be fixed in a future update.
.. _mutexheader:
mutex.h
=======
Thread safety analysis can be used with any threading library, but it does
require that the threading API be wrapped in classes and methods which have the
appropriate annotations. The following code provides ``mutex.h`` as an example;
these methods should be filled in to call the appropriate underlying
implementation.
.. code-block:: c++
#ifndef THREAD_SAFETY_ANALYSIS_MUTEX_H
#define THREAD_SAFETY_ANALYSIS_MUTEX_H
// Enable thread safety attributes only with clang.
// The attributes can be safely erased when compiling with other compilers.
#if defined(__clang__) && (!defined(SWIG))
#define THREAD_ANNOTATION_ATTRIBUTE__(x) __attribute__((x))
#else
#define THREAD_ANNOTATION_ATTRIBUTE__(x) // no-op
#endif
#define THREAD_ANNOTATION_ATTRIBUTE__(x) __attribute__((x))
#define GUARDED_BY(x) \
THREAD_ANNOTATION_ATTRIBUTE__(guarded_by(x))
#define GUARDED_VAR \
THREAD_ANNOTATION_ATTRIBUTE__(guarded)
#define PT_GUARDED_BY(x) \
THREAD_ANNOTATION_ATTRIBUTE__(pt_guarded_by(x))
#define PT_GUARDED_VAR \
THREAD_ANNOTATION_ATTRIBUTE__(pt_guarded)
#define ACQUIRED_AFTER(...) \
THREAD_ANNOTATION_ATTRIBUTE__(acquired_after(__VA_ARGS__))
#define ACQUIRED_BEFORE(...) \
THREAD_ANNOTATION_ATTRIBUTE__(acquired_before(__VA_ARGS__))
#define EXCLUSIVE_LOCKS_REQUIRED(...) \
THREAD_ANNOTATION_ATTRIBUTE__(exclusive_locks_required(__VA_ARGS__))
#define SHARED_LOCKS_REQUIRED(...) \
THREAD_ANNOTATION_ATTRIBUTE__(shared_locks_required(__VA_ARGS__))
#define LOCKS_EXCLUDED(...) \
THREAD_ANNOTATION_ATTRIBUTE__(locks_excluded(__VA_ARGS__))
#define LOCK_RETURNED(x) \
THREAD_ANNOTATION_ATTRIBUTE__(lock_returned(x))
#define LOCKABLE \
THREAD_ANNOTATION_ATTRIBUTE__(lockable)
#define SCOPED_LOCKABLE \
THREAD_ANNOTATION_ATTRIBUTE__(scoped_lockable)
#define EXCLUSIVE_LOCK_FUNCTION(...) \
THREAD_ANNOTATION_ATTRIBUTE__(exclusive_lock_function(__VA_ARGS__))
#define SHARED_LOCK_FUNCTION(...) \
THREAD_ANNOTATION_ATTRIBUTE__(shared_lock_function(__VA_ARGS__))
#define ASSERT_EXCLUSIVE_LOCK(...) \
THREAD_ANNOTATION_ATTRIBUTE__(assert_exclusive_lock(__VA_ARGS__))
#define ASSERT_SHARED_LOCK(...) \
THREAD_ANNOTATION_ATTRIBUTE__(assert_shared_lock(__VA_ARGS__))
#define EXCLUSIVE_TRYLOCK_FUNCTION(...) \
THREAD_ANNOTATION_ATTRIBUTE__(exclusive_trylock_function(__VA_ARGS__))
#define SHARED_TRYLOCK_FUNCTION(...) \
THREAD_ANNOTATION_ATTRIBUTE__(shared_trylock_function(__VA_ARGS__))
#define UNLOCK_FUNCTION(...) \
THREAD_ANNOTATION_ATTRIBUTE__(unlock_function(__VA_ARGS__))
#define NO_THREAD_SAFETY_ANALYSIS \
THREAD_ANNOTATION_ATTRIBUTE__(no_thread_safety_analysis)
// Defines an annotated interface for mutexes.
// These methods can be implemented to use any internal mutex implementation.
class LOCKABLE Mutex {
public:
// Acquire/lock this mutex exclusively. Only one thread can have exclusive
// access at any one time. Write operations to guarded data require an
// exclusive lock.
void Lock() EXCLUSIVE_LOCK_FUNCTION();
// Acquire/lock this mutex for read operations, which require only a shared
// lock. This assumes a multiple-reader, single writer semantics. Multiple
// threads may acquire the mutex simultaneously as readers, but a writer must
// wait for all of them to release the mutex before it can acquire it
// exclusively.
void ReaderLock() SHARED_LOCK_FUNCTION();
// Release/unlock the mutex, regardless of whether it is exclusive or shared.
void Unlock() UNLOCK_FUNCTION();
// Try to acquire the mutex. Returns true on success, and false on failure.
bool TryLock() EXCLUSIVE_TRYLOCK_FUNCTION(true);
// Try to acquire the mutex for read operations.
bool ReaderTryLock() SHARED_TRYLOCK_FUNCTION(true);
// Assert that this mutex is currently held by the calling thread.
void AssertHeld() ASSERT_EXCLUSIVE_LOCK();
// Assert that is mutex is currently held for read operations.
void AssertReaderHeld() ASSERT_SHARED_LOCK();
};
// MutexLocker is an RAII class that acquires a mutex in its constructor, and
// releases it in its destructor.
class SCOPED_LOCKABLE MutexLocker {
private:
Mutex* mut;
public:
MutexLocker(Mutex *mu) EXCLUSIVE_LOCK_FUNCTION(mu) : mut(mu) {
mu->Lock();
}
~MutexLocker() UNLOCK_FUNCTION() {
mut->Unlock();
}
};
#endif // THREAD_SAFETY_ANALYSIS_MUTEX_H

View File

@ -112,11 +112,11 @@ Options to Control Error and Warning Messages
.. option:: -w
Disable all warnings.
Disable all diagnostics.
.. option:: -Weverything
:ref:`Enable all warnings. <diagnostics_enable_everything>`
:ref:`Enable all diagnostics. <diagnostics_enable_everything>`
.. option:: -pedantic
@ -582,6 +582,7 @@ All diagnostics are mapped into one of these 5 classes:
- Ignored
- Note
- Remark
- Warning
- Error
- Fatal
@ -722,11 +723,12 @@ is treated as a system header.
.. _diagnostics_enable_everything:
Enabling All Warnings
^^^^^^^^^^^^^^^^^^^^^
Enabling All Diagnostics
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
In addition to the traditional ``-W`` flags, one can enable **all**
warnings by passing :option:`-Weverything`. This works as expected with
diagnostics by passing :option:`-Weverything`. This works as expected
with
:option:`-Werror`, and also includes the warnings from :option:`-pedantic`.
Note that when combined with :option:`-w` (which disables all warnings), that

View File

@ -18,7 +18,9 @@ Using Clang as a Compiler
UsersManual
LanguageExtensions
AttributeReference
CrossCompilation
ThreadSafetyAnalysis
AddressSanitizer
ThreadSanitizer
MemorySanitizer
@ -26,6 +28,7 @@ Using Clang as a Compiler
LeakSanitizer
SanitizerSpecialCaseList
Modules
MSVCCompatibility
FAQ
Using Clang as a Library

View File

@ -119,9 +119,9 @@ def add_matcher(result_type, name, args, comment, is_dyncast=False):
# arguments.
elif ('Matcher<' not in args or
name in ['allOf', 'anyOf', 'anything', 'unless']):
narrowing_matchers[result_type + name] = matcher_html
narrowing_matchers[result_type + name + esc(args)] = matcher_html
else:
traversal_matchers[result_type + name] = matcher_html
traversal_matchers[result_type + name + esc(args)] = matcher_html
def act_on_decl(declaration, comment, allowed_types):
"""Parse the matcher out of the given declaration and comment.
@ -242,12 +242,17 @@ def act_on_decl(declaration, comment, allowed_types):
# Parse Variadic operator matchers.
m = re.match(
r"""^.*VariadicOperatorMatcherFunc\s*([a-zA-Z]*)\s*=\s*{.*};$""",
r"""^.*VariadicOperatorMatcherFunc\s*<\s*([^,]+),\s*([^\s>]+)\s*>\s*
([a-zA-Z]*)\s*=\s*{.*};$""",
declaration, flags=re.X)
if m:
name = m.groups()[0]
add_matcher('*', name, 'Matcher<*>, ..., Matcher<*>', comment)
return
min_args, max_args, name = m.groups()[:3]
if max_args == '1':
add_matcher('*', name, 'Matcher<*>', comment)
return
elif max_args == 'UINT_MAX':
add_matcher('*', name, 'Matcher<*>, ..., Matcher<*>', comment)
return
# Parse free standing matcher functions, like:

View File

@ -98,7 +98,7 @@ def read_options(header):
enum = Enum(name, comment)
elif line.endswith(';'):
state = State.InStruct
field_type, field_name = re.match(r'(\w+)\s+(\w+);', line).groups()
field_type, field_name = re.match(r'([:\w]+)\s+(\w+);', line).groups()
option = Option(str(field_name), str(field_type), comment)
options.append(option)
else:
@ -122,7 +122,7 @@ def read_options(header):
raise Exception('Not finished by the end of file')
for option in options:
if not option.type in ['bool', 'unsigned', 'int']:
if not option.type in ['bool', 'unsigned', 'int', 'std::string']:
if enums.has_key(option.type):
option.enum = enums[option.type]
else:

View File

@ -1,5 +1,6 @@
if(NOT CLANG_BUILD_EXAMPLES)
set_property(DIRECTORY PROPERTY EXCLUDE_FROM_ALL ON)
set(EXCLUDE_FROM_ALL ON)
endif()
if(CLANG_ENABLE_STATIC_ANALYZER)

View File

@ -1,7 +1,3 @@
set( LLVM_LINK_COMPONENTS
Support
)
# If we don't need RTTI or EH, there's no reason to export anything
# from the plugin.
if( NOT WIN32 ) # Win32 mangles symbols differently, and
@ -13,24 +9,4 @@ if( NOT WIN32 ) # Win32 mangles symbols differently, and
endif()
endif()
add_clang_library(PrintFunctionNames MODULE PrintFunctionNames.cpp)
add_dependencies(PrintFunctionNames
ClangAttrClasses
ClangAttrList
ClangCommentNodes
ClangDeclNodes
ClangDiagnosticCommon
ClangStmtNodes
)
target_link_libraries(PrintFunctionNames
clangAST
clangBasic
clangFrontend
)
set_target_properties(PrintFunctionNames
PROPERTIES
LINKER_LANGUAGE CXX
PREFIX "")
add_llvm_loadable_module(PrintFunctionNames PrintFunctionNames.cpp)

View File

@ -19,7 +19,7 @@ endif
endif
LINK_LIBS_IN_SHARED = 0
SHARED_LIBRARY = 1
LOADABLE_MODULE = 1
include $(CLANG_LEVEL)/Makefile

View File

@ -1,25 +1 @@
set(LLVM_LINK_COMPONENTS
Support
)
add_clang_library(SampleAnalyzerPlugin MODULE MainCallChecker.cpp)
add_dependencies(SampleAnalyzerPlugin
ClangAttrClasses
ClangAttrList
ClangCommentNodes
ClangDeclNodes
ClangDiagnosticCommon
ClangStmtNodes
)
target_link_libraries(SampleAnalyzerPlugin
clangAST
clangAnalysis
clangStaticAnalyzerCore
)
set_target_properties(SampleAnalyzerPlugin
PROPERTIES
LINKER_LANGUAGE CXX
PREFIX "")
add_llvm_loadable_module(SampleAnalyzerPlugin MainCallChecker.cpp)

View File

@ -35,7 +35,7 @@ void MainCallChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const
return;
if (!BT)
BT.reset(new BugType("call to main", "example analyzer plugin"));
BT.reset(new BugType(this, "call to main", "example analyzer plugin"));
BugReport *report = new BugReport(*BT, BT->getName(), N);
report->addRange(Callee->getSourceRange());

View File

@ -0,0 +1,87 @@
/*==-- clang-c/BuildSysetm.h - Utilities for use by build systems -*- C -*-===*\
|* *|
|* The LLVM Compiler Infrastructure *|
|* *|
|* This file is distributed under the University of Illinois Open Source *|
|* License. See LICENSE.TXT for details. *|
|* *|
|*===----------------------------------------------------------------------===*|
|* *|
|* This header provides various utilities for use by build systems. *|
|* *|
\*===----------------------------------------------------------------------===*/
#ifndef CLANG_C_BUILD_SYSTEM_H
#define CLANG_C_BUILD_SYSTEM_H
#include "clang-c/Platform.h"
#include "clang-c/CXErrorCode.h"
#include "clang-c/CXString.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* \defgroup BUILD_SYSTEM Build system utilities
* @{
*/
/**
* \brief Return the timestamp for use with Clang's
* \c -fbuild-session-timestamp= option.
*/
CINDEX_LINKAGE unsigned long long clang_getBuildSessionTimestamp(void);
/**
* \brief Object encapsulating information about overlaying virtual
* file/directories over the real file system.
*/
typedef struct CXVirtualFileOverlayImpl *CXVirtualFileOverlay;
/**
* \brief Create a \c CXVirtualFileOverlay object.
* Must be disposed with \c clang_VirtualFileOverlay_dispose().
*
* \param options is reserved, always pass 0.
*/
CINDEX_LINKAGE CXVirtualFileOverlay
clang_VirtualFileOverlay_create(unsigned options);
/**
* \brief Map an absolute virtual file path to an absolute real one.
* The virtual path must be canonicalized (not contain "."/"..").
* \returns 0 for success, non-zero to indicate an error.
*/
CINDEX_LINKAGE enum CXErrorCode
clang_VirtualFileOverlay_addFileMapping(CXVirtualFileOverlay,
const char *virtualPath,
const char *realPath);
/**
* \brief Write out the \c CXVirtualFileOverlay object to a char buffer.
*
* \param options is reserved, always pass 0.
* \param out_buffer pointer to receive the CXString object, which should be
* disposed using \c clang_disposeString().
* \returns 0 for success, non-zero to indicate an error.
*/
CINDEX_LINKAGE enum CXErrorCode
clang_VirtualFileOverlay_writeToBuffer(CXVirtualFileOverlay, unsigned options,
CXString *out_buffer);
/**
* \brief Dispose a \c CXVirtualFileOverlay object.
*/
CINDEX_LINKAGE void clang_VirtualFileOverlay_dispose(CXVirtualFileOverlay);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* CLANG_C_BUILD_SYSTEM_H */

View File

@ -0,0 +1,64 @@
/*===-- clang-c/CXErrorCode.h - C Index Error Codes --------------*- C -*-===*\
|* *|
|* The LLVM Compiler Infrastructure *|
|* *|
|* This file is distributed under the University of Illinois Open Source *|
|* License. See LICENSE.TXT for details. *|
|* *|
|*===----------------------------------------------------------------------===*|
|* *|
|* This header provides the CXErrorCode enumerators. *|
|* *|
\*===----------------------------------------------------------------------===*/
#ifndef CLANG_C_CXERRORCODE_H
#define CLANG_C_CXERRORCODE_H
#include "clang-c/Platform.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief Error codes returned by libclang routines.
*
* Zero (\c CXError_Success) is the only error code indicating success. Other
* error codes, including not yet assigned non-zero values, indicate errors.
*/
enum CXErrorCode {
/**
* \brief No error.
*/
CXError_Success = 0,
/**
* \brief A generic error code, no further details are available.
*
* Errors of this kind can get their own specific error codes in future
* libclang versions.
*/
CXError_Failure = 1,
/**
* \brief libclang crashed while performing the requested operation.
*/
CXError_Crashed = 2,
/**
* \brief The function detected that the arguments violate the function
* contract.
*/
CXError_InvalidArguments = 3,
/**
* \brief An AST deserialization error has occurred.
*/
CXError_ASTReadError = 4
};
#ifdef __cplusplus
}
#endif
#endif

View File

@ -19,7 +19,9 @@
#include <time.h>
#include "clang-c/Platform.h"
#include "clang-c/CXErrorCode.h"
#include "clang-c/CXString.h"
#include "clang-c/BuildSystem.h"
/**
* \brief The version constants for the libclang API.
@ -30,7 +32,7 @@
* compatible, thus CINDEX_VERSION_MAJOR is expected to remain stable.
*/
#define CINDEX_VERSION_MAJOR 0
#define CINDEX_VERSION_MINOR 21
#define CINDEX_VERSION_MINOR 24
#define CINDEX_VERSION_ENCODE(major, minor) ( \
((major) * 10000) \
@ -650,6 +652,12 @@ enum CXDiagnosticSeverity {
*/
CXDiagnostic_Note = 1,
/**
* \brief This diagnostic is a remark that provides additional information
* for the user.
*/
CXDiagnostic_Remark = 5,
/**
* \brief This diagnostic indicates suspicious code that may not be
* wrong.
@ -1076,10 +1084,27 @@ CINDEX_LINKAGE CXTranslationUnit clang_createTranslationUnitFromSourceFile(
struct CXUnsavedFile *unsaved_files);
/**
* \brief Create a translation unit from an AST file (-emit-ast).
* \brief Same as \c clang_createTranslationUnit2, but returns
* the \c CXTranslationUnit instead of an error code. In case of an error this
* routine returns a \c NULL \c CXTranslationUnit, without further detailed
* error codes.
*/
CINDEX_LINKAGE CXTranslationUnit clang_createTranslationUnit(CXIndex,
const char *ast_filename);
CINDEX_LINKAGE CXTranslationUnit clang_createTranslationUnit(
CXIndex CIdx,
const char *ast_filename);
/**
* \brief Create a translation unit from an AST file (\c -emit-ast).
*
* \param[out] out_TU A non-NULL pointer to store the created
* \c CXTranslationUnit.
*
* \returns Zero on success, otherwise returns an error code.
*/
CINDEX_LINKAGE enum CXErrorCode clang_createTranslationUnit2(
CXIndex CIdx,
const char *ast_filename,
CXTranslationUnit *out_TU);
/**
* \brief Flags that control the creation of translation units.
@ -1193,7 +1218,22 @@ enum CXTranslationUnit_Flags {
* set of optimizations enabled may change from one version to the next.
*/
CINDEX_LINKAGE unsigned clang_defaultEditingTranslationUnitOptions(void);
/**
* \brief Same as \c clang_parseTranslationUnit2, but returns
* the \c CXTranslationUnit instead of an error code. In case of an error this
* routine returns a \c NULL \c CXTranslationUnit, without further detailed
* error codes.
*/
CINDEX_LINKAGE CXTranslationUnit
clang_parseTranslationUnit(CXIndex CIdx,
const char *source_filename,
const char *const *command_line_args,
int num_command_line_args,
struct CXUnsavedFile *unsaved_files,
unsigned num_unsaved_files,
unsigned options);
/**
* \brief Parse the given source file and the translation unit corresponding
* to that file.
@ -1208,7 +1248,7 @@ CINDEX_LINKAGE unsigned clang_defaultEditingTranslationUnitOptions(void);
* associated.
*
* \param source_filename The name of the source file to load, or NULL if the
* source file is included in \p command_line_args.
* source file is included in \c command_line_args.
*
* \param command_line_args The command-line arguments that would be
* passed to the \c clang executable if it were being invoked out-of-process.
@ -1217,7 +1257,7 @@ CINDEX_LINKAGE unsigned clang_defaultEditingTranslationUnitOptions(void);
* '-emit-ast', '-fsyntax-only' (which is the default), and '-o \<output file>'.
*
* \param num_command_line_args The number of command-line arguments in
* \p command_line_args.
* \c command_line_args.
*
* \param unsaved_files the files that have not yet been saved to disk
* but may be required for parsing, including the contents of
@ -1232,18 +1272,22 @@ CINDEX_LINKAGE unsigned clang_defaultEditingTranslationUnitOptions(void);
* is managed but not its compilation. This should be a bitwise OR of the
* CXTranslationUnit_XXX flags.
*
* \returns A new translation unit describing the parsed code and containing
* any diagnostics produced by the compiler. If there is a failure from which
* the compiler cannot recover, returns NULL.
* \param[out] out_TU A non-NULL pointer to store the created
* \c CXTranslationUnit, describing the parsed code and containing any
* diagnostics produced by the compiler.
*
* \returns Zero on success, otherwise returns an error code.
*/
CINDEX_LINKAGE CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
const char *source_filename,
const char * const *command_line_args,
int num_command_line_args,
struct CXUnsavedFile *unsaved_files,
unsigned num_unsaved_files,
unsigned options);
CINDEX_LINKAGE enum CXErrorCode
clang_parseTranslationUnit2(CXIndex CIdx,
const char *source_filename,
const char *const *command_line_args,
int num_command_line_args,
struct CXUnsavedFile *unsaved_files,
unsigned num_unsaved_files,
unsigned options,
CXTranslationUnit *out_TU);
/**
* \brief Flags that control how translation units are saved.
*
@ -1395,10 +1439,11 @@ CINDEX_LINKAGE unsigned clang_defaultReparseOptions(CXTranslationUnit TU);
* The function \c clang_defaultReparseOptions() produces a default set of
* options recommended for most uses, based on the translation unit.
*
* \returns 0 if the sources could be reparsed. A non-zero value will be
* \returns 0 if the sources could be reparsed. A non-zero error code will be
* returned if reparsing was impossible, such that the translation unit is
* invalid. In such cases, the only valid call for \p TU is
* \c clang_disposeTranslationUnit(TU).
* invalid. In such cases, the only valid call for \c TU is
* \c clang_disposeTranslationUnit(TU). The error codes returned by this
* routine are described by the \c CXErrorCode enum.
*/
CINDEX_LINKAGE int clang_reparseTranslationUnit(CXTranslationUnit TU,
unsigned num_unsaved_files,
@ -2096,7 +2141,11 @@ enum CXCursorKind {
*/
CXCursor_OMPParallelDirective = 232,
CXCursor_LastStmt = CXCursor_OMPParallelDirective,
/** \brief OpenMP simd directive.
*/
CXCursor_OMPSimdDirective = 233,
CXCursor_LastStmt = CXCursor_OMPSimdDirective,
/**
* \brief Cursor that represents the translation unit itself.
@ -3037,6 +3086,24 @@ enum CXRefQualifierKind {
CXRefQualifier_RValue
};
/**
* \brief Returns the number of template arguments for given class template
* specialization, or -1 if type \c T is not a class template specialization.
*
* Variadic argument packs count as only one argument, and can not be inspected
* further.
*/
CINDEX_LINKAGE int clang_Type_getNumTemplateArguments(CXType T);
/**
* \brief Returns the type template argument of a template class specialization
* at given index.
*
* This function only returns template type arguments and does not handle
* template template arguments or variadic packs.
*/
CINDEX_LINKAGE CXType clang_Type_getTemplateArgumentAsType(CXType T, unsigned i);
/**
* \brief Retrieve the ref-qualifier kind of a function or method.
*
@ -5789,11 +5856,12 @@ typedef enum {
* \param index_options A bitmask of options that affects how indexing is
* performed. This should be a bitwise OR of the CXIndexOpt_XXX flags.
*
* \param out_TU [out] pointer to store a CXTranslationUnit that can be reused
* after indexing is finished. Set to NULL if you do not require it.
* \param[out] out_TU pointer to store a \c CXTranslationUnit that can be
* reused after indexing is finished. Set to \c NULL if you do not require it.
*
* \returns If there is a failure from which the there is no recovery, returns
* non-zero, otherwise returns 0.
* \returns 0 on success or if there were errors from which the compiler could
* recover. If there is a failure from which the there is no recovery, returns
* a non-zero \c CXErrorCode.
*
* The rest of the parameters are the same as #clang_parseTranslationUnit.
*/

View File

@ -416,7 +416,7 @@ public:
SelectorTable &Selectors;
Builtin::Context &BuiltinInfo;
mutable DeclarationNameTable DeclarationNames;
OwningPtr<ExternalASTSource> ExternalSource;
IntrusiveRefCntPtr<ExternalASTSource> ExternalSource;
ASTMutationListener *Listener;
/// \brief Contains parents of a node.
@ -811,11 +811,13 @@ public:
/// The external AST source provides the ability to load parts of
/// the abstract syntax tree as needed from some external storage,
/// e.g., a precompiled header.
void setExternalSource(OwningPtr<ExternalASTSource> &Source);
void setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source);
/// \brief Retrieve a pointer to the external AST source associated
/// with this AST context, if any.
ExternalASTSource *getExternalSource() const { return ExternalSource.get(); }
ExternalASTSource *getExternalSource() const {
return ExternalSource.getPtr();
}
/// \brief Attach an AST mutation listener to the AST context.
///

View File

@ -173,12 +173,7 @@ namespace clang {
/// Given that this is a non-zero alignment value, what is the
/// alignment at the given offset?
CharUnits alignmentAtOffset(CharUnits offset) {
// alignment: 0010000
// offset: 1011100
// lowBits: 0001011
// result: 0000100
QuantityType lowBits = (Quantity-1) & (offset.Quantity-1);
return CharUnits((lowBits + 1) & ~lowBits);
return CharUnits(llvm::MinAlign(Quantity, offset.Quantity));
}

View File

@ -424,6 +424,7 @@ private:
bool TraverseFunctionHelper(FunctionDecl *D);
bool TraverseVarHelper(VarDecl *D);
bool TraverseOMPClause(OMPClause *C);
bool TraverseOMPExecutableDirective(OMPExecutableDirective *S);
#define OPENMP_CLAUSE(Name, Class) \
bool Visit##Class(Class *C);
#include "clang/Basic/OpenMPKinds.def"
@ -2331,11 +2332,22 @@ DEF_TRAVERSE_STMT(ObjCDictionaryLiteral, { })
DEF_TRAVERSE_STMT(AsTypeExpr, { })
// OpenMP directives.
DEF_TRAVERSE_STMT(OMPParallelDirective, {
template<typename Derived>
bool DataRecursiveASTVisitor<Derived>::TraverseOMPExecutableDirective(
OMPExecutableDirective *S) {
ArrayRef<OMPClause *> Clauses = S->clauses();
for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
I != E; ++I)
if (!TraverseOMPClause(*I)) return false;
return true;
}
DEF_TRAVERSE_STMT(OMPParallelDirective, {
if (!TraverseOMPExecutableDirective(S)) return false;
})
DEF_TRAVERSE_STMT(OMPSimdDirective, {
if (!TraverseOMPExecutableDirective(S)) return false;
})
// OpenMP clauses.
@ -2352,6 +2364,12 @@ bool DataRecursiveASTVisitor<Derived>::TraverseOMPClause(OMPClause *C) {
return true;
}
template<typename Derived>
bool DataRecursiveASTVisitor<Derived>::VisitOMPIfClause(OMPIfClause *C) {
TraverseStmt(C->getCondition());
return true;
}
template<typename Derived>
bool DataRecursiveASTVisitor<Derived>::VisitOMPDefaultClause(OMPDefaultClause *C) {
return true;

View File

@ -1615,6 +1615,10 @@ public:
(hasDefinition() && isPolymorphic());
}
/// \brief Controls when vtordisps will be emitted if this record is used as a
/// virtual base.
MSVtorDispAttr::Mode getMSVtorDispMode() const;
/// \brief Determine whether this lambda expression was known to be dependent
/// at the time it was created, even if its context does not appear to be
/// dependent.
@ -2303,8 +2307,12 @@ public:
bool isImplicitlyDeclared);
static CXXDestructorDecl *CreateDeserialized(ASTContext & C, unsigned ID);
void setOperatorDelete(FunctionDecl *OD) { OperatorDelete = OD; }
const FunctionDecl *getOperatorDelete() const { return OperatorDelete; }
void setOperatorDelete(FunctionDecl *OD) {
cast<CXXDestructorDecl>(getFirstDecl())->OperatorDelete = OD;
}
const FunctionDecl *getOperatorDelete() const {
return cast<CXXDestructorDecl>(getFirstDecl())->OperatorDelete;
}
// Implement isa/cast/dyncast/etc.
static bool classof(const Decl *D) { return classofKind(D->getKind()); }

View File

@ -53,7 +53,7 @@ enum ExternalLoadResult {
/// sources can resolve types and declarations from abstract IDs into
/// actual type and declaration nodes, and read parts of declaration
/// contexts.
class ExternalASTSource {
class ExternalASTSource : public RefCountedBase<ExternalASTSource> {
/// \brief Whether this AST source also provides information for
/// semantic analysis.
bool SemaSource;

View File

@ -0,0 +1,438 @@
//===- OpenMPClause.h - Classes for OpenMP clauses --------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// \brief This file defines OpenMP AST classes for clauses.
/// There are clauses for executable directives, clauses for declarative
/// directives and clauses which can be used in both kinds of directives.
///
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_AST_OPENMPCLAUSE_H
#define LLVM_CLANG_AST_OPENMPCLAUSE_H
#include "clang/AST/Expr.h"
#include "clang/AST/Stmt.h"
#include "clang/Basic/OpenMPKinds.h"
#include "clang/Basic/SourceLocation.h"
namespace clang {
//===----------------------------------------------------------------------===//
// AST classes for clauses.
//===----------------------------------------------------------------------===//
/// \brief This is a basic class for representing single OpenMP clause.
///
class OMPClause {
/// \brief Starting location of the clause (the clause keyword).
SourceLocation StartLoc;
/// \brief Ending location of the clause.
SourceLocation EndLoc;
/// \brief Kind of the clause.
OpenMPClauseKind Kind;
protected:
OMPClause(OpenMPClauseKind K, SourceLocation StartLoc, SourceLocation EndLoc)
: StartLoc(StartLoc), EndLoc(EndLoc), Kind(K) {}
public:
/// \brief Returns the starting location of the clause.
SourceLocation getLocStart() const { return StartLoc; }
/// \brief Returns the ending location of the clause.
SourceLocation getLocEnd() const { return EndLoc; }
/// \brief Sets the starting location of the clause.
void setLocStart(SourceLocation Loc) { StartLoc = Loc; }
/// \brief Sets the ending location of the clause.
void setLocEnd(SourceLocation Loc) { EndLoc = Loc; }
/// \brief Returns kind of OpenMP clause (private, shared, reduction, etc.).
OpenMPClauseKind getClauseKind() const { return Kind; }
bool isImplicit() const { return StartLoc.isInvalid(); }
StmtRange children();
ConstStmtRange children() const {
return const_cast<OMPClause *>(this)->children();
}
static bool classof(const OMPClause *T) { return true; }
};
/// \brief This represents clauses with the list of variables like 'private',
/// 'firstprivate', 'copyin', 'shared', or 'reduction' clauses in the
/// '#pragma omp ...' directives.
template <class T> class OMPVarListClause : public OMPClause {
friend class OMPClauseReader;
/// \brief Location of '('.
SourceLocation LParenLoc;
/// \brief Number of variables in the list.
unsigned NumVars;
protected:
/// \brief Fetches list of variables associated with this clause.
llvm::MutableArrayRef<Expr *> getVarRefs() {
return llvm::MutableArrayRef<Expr *>(
reinterpret_cast<Expr **>(
reinterpret_cast<char *>(this) +
llvm::RoundUpToAlignment(sizeof(T), llvm::alignOf<Expr *>())),
NumVars);
}
/// \brief Sets the list of variables for this clause.
void setVarRefs(ArrayRef<Expr *> VL) {
assert(VL.size() == NumVars &&
"Number of variables is not the same as the preallocated buffer");
std::copy(
VL.begin(), VL.end(),
reinterpret_cast<Expr **>(
reinterpret_cast<char *>(this) +
llvm::RoundUpToAlignment(sizeof(T), llvm::alignOf<Expr *>())));
}
/// \brief Build clause with number of variables \a N.
///
/// \param K Kind of the clause.
/// \param StartLoc Starting location of the clause (the clause keyword).
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param N Number of the variables in the clause.
///
OMPVarListClause(OpenMPClauseKind K, SourceLocation StartLoc,
SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N)
: OMPClause(K, StartLoc, EndLoc), LParenLoc(LParenLoc), NumVars(N) {}
public:
typedef llvm::MutableArrayRef<Expr *>::iterator varlist_iterator;
typedef ArrayRef<const Expr *>::iterator varlist_const_iterator;
unsigned varlist_size() const { return NumVars; }
bool varlist_empty() const { return NumVars == 0; }
varlist_iterator varlist_begin() { return getVarRefs().begin(); }
varlist_iterator varlist_end() { return getVarRefs().end(); }
varlist_const_iterator varlist_begin() const { return getVarRefs().begin(); }
varlist_const_iterator varlist_end() const { return getVarRefs().end(); }
/// \brief Sets the location of '('.
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// \brief Returns the location of '('.
SourceLocation getLParenLoc() const { return LParenLoc; }
/// \brief Fetches list of all variables in the clause.
ArrayRef<const Expr *> getVarRefs() const {
return ArrayRef<const Expr *>(
reinterpret_cast<const Expr *const *>(
reinterpret_cast<const char *>(this) +
llvm::RoundUpToAlignment(sizeof(T), llvm::alignOf<Expr *>())),
NumVars);
}
};
/// \brief This represents 'if' clause in the '#pragma omp ...' directive.
///
/// \code
/// #pragma omp parallel if(a > 5)
/// \endcode
/// In this example directive '#pragma omp parallel' has simple 'if'
/// clause with condition 'a > 5'.
///
class OMPIfClause : public OMPClause {
friend class OMPClauseReader;
/// \brief Location of '('.
SourceLocation LParenLoc;
/// \brief Condition of the 'if' clause.
Stmt *Condition;
/// \brief Set condition.
///
void setCondition(Expr *Cond) { Condition = Cond; }
public:
/// \brief Build 'if' clause with condition \a Cond.
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param Cond Condition of the clause.
/// \param EndLoc Ending location of the clause.
///
OMPIfClause(Expr *Cond, SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc)
: OMPClause(OMPC_if, StartLoc, EndLoc), LParenLoc(LParenLoc),
Condition(Cond) {}
/// \brief Build an empty clause.
///
OMPIfClause()
: OMPClause(OMPC_if, SourceLocation(), SourceLocation()),
LParenLoc(SourceLocation()), Condition(0) {}
/// \brief Sets the location of '('.
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// \brief Returns the location of '('.
SourceLocation getLParenLoc() const { return LParenLoc; }
/// \brief Returns condition.
Expr *getCondition() const { return cast_or_null<Expr>(Condition); }
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_if;
}
StmtRange children() { return StmtRange(&Condition, &Condition + 1); }
};
/// \brief This represents 'default' clause in the '#pragma omp ...' directive.
///
/// \code
/// #pragma omp parallel default(shared)
/// \endcode
/// In this example directive '#pragma omp parallel' has simple 'default'
/// clause with kind 'shared'.
///
class OMPDefaultClause : public OMPClause {
friend class OMPClauseReader;
/// \brief Location of '('.
SourceLocation LParenLoc;
/// \brief A kind of the 'default' clause.
OpenMPDefaultClauseKind Kind;
/// \brief Start location of the kind in source code.
SourceLocation KindKwLoc;
/// \brief Set kind of the clauses.
///
/// \param K Argument of clause.
///
void setDefaultKind(OpenMPDefaultClauseKind K) { Kind = K; }
/// \brief Set argument location.
///
/// \param KLoc Argument location.
///
void setDefaultKindKwLoc(SourceLocation KLoc) { KindKwLoc = KLoc; }
public:
/// \brief Build 'default' clause with argument \a A ('none' or 'shared').
///
/// \param A Argument of the clause ('none' or 'shared').
/// \param ALoc Starting location of the argument.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
///
OMPDefaultClause(OpenMPDefaultClauseKind A, SourceLocation ALoc,
SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc)
: OMPClause(OMPC_default, StartLoc, EndLoc), LParenLoc(LParenLoc),
Kind(A), KindKwLoc(ALoc) {}
/// \brief Build an empty clause.
///
OMPDefaultClause()
: OMPClause(OMPC_default, SourceLocation(), SourceLocation()),
LParenLoc(SourceLocation()), Kind(OMPC_DEFAULT_unknown),
KindKwLoc(SourceLocation()) {}
/// \brief Sets the location of '('.
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// \brief Returns the location of '('.
SourceLocation getLParenLoc() const { return LParenLoc; }
/// \brief Returns kind of the clause.
OpenMPDefaultClauseKind getDefaultKind() const { return Kind; }
/// \brief Returns location of clause kind.
SourceLocation getDefaultKindKwLoc() const { return KindKwLoc; }
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_default;
}
StmtRange children() { return StmtRange(); }
};
/// \brief This represents clause 'private' in the '#pragma omp ...' directives.
///
/// \code
/// #pragma omp parallel private(a,b)
/// \endcode
/// In this example directive '#pragma omp parallel' has clause 'private'
/// with the variables 'a' and 'b'.
///
class OMPPrivateClause : public OMPVarListClause<OMPPrivateClause> {
/// \brief Build clause with number of variables \a N.
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param N Number of the variables in the clause.
///
OMPPrivateClause(SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc, unsigned N)
: OMPVarListClause<OMPPrivateClause>(OMPC_private, StartLoc, LParenLoc,
EndLoc, N) {}
/// \brief Build an empty clause.
///
/// \param N Number of variables.
///
explicit OMPPrivateClause(unsigned N)
: OMPVarListClause<OMPPrivateClause>(OMPC_private, SourceLocation(),
SourceLocation(), SourceLocation(),
N) {}
public:
/// \brief Creates clause with a list of variables \a VL.
///
/// \param C AST context.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param VL List of references to the variables.
///
static OMPPrivateClause *Create(const ASTContext &C, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc, ArrayRef<Expr *> VL);
/// \brief Creates an empty clause with the place for \a N variables.
///
/// \param C AST context.
/// \param N The number of variables.
///
static OMPPrivateClause *CreateEmpty(const ASTContext &C, unsigned N);
StmtRange children() {
return StmtRange(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_private;
}
};
/// \brief This represents clause 'firstprivate' in the '#pragma omp ...'
/// directives.
///
/// \code
/// #pragma omp parallel firstprivate(a,b)
/// \endcode
/// In this example directive '#pragma omp parallel' has clause 'firstprivate'
/// with the variables 'a' and 'b'.
///
class OMPFirstprivateClause : public OMPVarListClause<OMPFirstprivateClause> {
/// \brief Build clause with number of variables \a N.
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param N Number of the variables in the clause.
///
OMPFirstprivateClause(SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc, unsigned N)
: OMPVarListClause<OMPFirstprivateClause>(OMPC_firstprivate, StartLoc,
LParenLoc, EndLoc, N) {}
/// \brief Build an empty clause.
///
/// \param N Number of variables.
///
explicit OMPFirstprivateClause(unsigned N)
: OMPVarListClause<OMPFirstprivateClause>(
OMPC_firstprivate, SourceLocation(), SourceLocation(),
SourceLocation(), N) {}
public:
/// \brief Creates clause with a list of variables \a VL.
///
/// \param C AST context.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param VL List of references to the variables.
///
static OMPFirstprivateClause *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc, ArrayRef<Expr *> VL);
/// \brief Creates an empty clause with the place for \a N variables.
///
/// \param C AST context.
/// \param N The number of variables.
///
static OMPFirstprivateClause *CreateEmpty(const ASTContext &C, unsigned N);
StmtRange children() {
return StmtRange(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_firstprivate;
}
};
/// \brief This represents clause 'shared' in the '#pragma omp ...' directives.
///
/// \code
/// #pragma omp parallel shared(a,b)
/// \endcode
/// In this example directive '#pragma omp parallel' has clause 'shared'
/// with the variables 'a' and 'b'.
///
class OMPSharedClause : public OMPVarListClause<OMPSharedClause> {
/// \brief Build clause with number of variables \a N.
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param N Number of the variables in the clause.
///
OMPSharedClause(SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc, unsigned N)
: OMPVarListClause<OMPSharedClause>(OMPC_shared, StartLoc, LParenLoc,
EndLoc, N) {}
/// \brief Build an empty clause.
///
/// \param N Number of variables.
///
explicit OMPSharedClause(unsigned N)
: OMPVarListClause<OMPSharedClause>(OMPC_shared, SourceLocation(),
SourceLocation(), SourceLocation(),
N) {}
public:
/// \brief Creates clause with a list of variables \a VL.
///
/// \param C AST context.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param VL List of references to the variables.
///
static OMPSharedClause *Create(const ASTContext &C, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc, ArrayRef<Expr *> VL);
/// \brief Creates an empty clause with \a N variables.
///
/// \param C AST context.
/// \param N The number of variables.
///
static OMPSharedClause *CreateEmpty(const ASTContext &C, unsigned N);
StmtRange children() {
return StmtRange(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_shared;
}
};
} // end namespace clang
#endif

View File

@ -441,6 +441,7 @@ private:
bool TraverseFunctionHelper(FunctionDecl *D);
bool TraverseVarHelper(VarDecl *D);
bool TraverseOMPClause(OMPClause *C);
bool TraverseOMPExecutableDirective(OMPExecutableDirective *S);
#define OPENMP_CLAUSE(Name, Class) \
bool Visit##Class(Class *C);
#include "clang/Basic/OpenMPKinds.def"
@ -2355,11 +2356,22 @@ DEF_TRAVERSE_STMT(ObjCDictionaryLiteral, { })
DEF_TRAVERSE_STMT(AsTypeExpr, { })
// OpenMP directives.
DEF_TRAVERSE_STMT(OMPParallelDirective, {
template<typename Derived>
bool RecursiveASTVisitor<Derived>::TraverseOMPExecutableDirective(
OMPExecutableDirective *S) {
ArrayRef<OMPClause *> Clauses = S->clauses();
for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
I != E; ++I)
if (!TraverseOMPClause(*I)) return false;
return true;
}
DEF_TRAVERSE_STMT(OMPParallelDirective, {
if (!TraverseOMPExecutableDirective(S)) return false;
})
DEF_TRAVERSE_STMT(OMPSimdDirective, {
if (!TraverseOMPExecutableDirective(S)) return false;
})
// OpenMP clauses.
@ -2376,6 +2388,12 @@ bool RecursiveASTVisitor<Derived>::TraverseOMPClause(OMPClause *C) {
return true;
}
template<typename Derived>
bool RecursiveASTVisitor<Derived>::VisitOMPIfClause(OMPIfClause *C) {
TraverseStmt(C->getCondition());
return true;
}
template<typename Derived>
bool RecursiveASTVisitor<Derived>::VisitOMPDefaultClause(OMPDefaultClause *C) {
return true;

View File

@ -1,4 +1,4 @@
//===- StmtOpenMP.h - Classes for OpenMP directives and clauses --*- C++ -*-===//
//===- StmtOpenMP.h - Classes for OpenMP directives ------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
@ -16,357 +16,13 @@
#define LLVM_CLANG_AST_STMTOPENMP_H
#include "clang/AST/Expr.h"
#include "clang/AST/OpenMPClause.h"
#include "clang/AST/Stmt.h"
#include "clang/Basic/OpenMPKinds.h"
#include "clang/Basic/SourceLocation.h"
namespace clang {
//===----------------------------------------------------------------------===//
// AST classes for clauses.
//===----------------------------------------------------------------------===//
/// \brief This is a basic class for representing single OpenMP clause.
///
class OMPClause {
/// \brief Starting location of the clause (the clause keyword).
SourceLocation StartLoc;
/// \brief Ending location of the clause.
SourceLocation EndLoc;
/// \brief Kind of the clause.
OpenMPClauseKind Kind;
protected:
OMPClause(OpenMPClauseKind K, SourceLocation StartLoc, SourceLocation EndLoc)
: StartLoc(StartLoc), EndLoc(EndLoc), Kind(K) {}
public:
/// \brief Returns the starting location of the clause.
SourceLocation getLocStart() const { return StartLoc; }
/// \brief Returns the ending location of the clause.
SourceLocation getLocEnd() const { return EndLoc; }
/// \brief Sets the starting location of the clause.
void setLocStart(SourceLocation Loc) { StartLoc = Loc; }
/// \brief Sets the ending location of the clause.
void setLocEnd(SourceLocation Loc) { EndLoc = Loc; }
/// \brief Returns kind of OpenMP clause (private, shared, reduction, etc.).
OpenMPClauseKind getClauseKind() const { return Kind; }
bool isImplicit() const { return StartLoc.isInvalid();}
StmtRange children();
ConstStmtRange children() const {
return const_cast<OMPClause *>(this)->children();
}
static bool classof(const OMPClause *T) {
return true;
}
};
/// \brief This represents clauses with the list of variables like 'private',
/// 'firstprivate', 'copyin', 'shared', or 'reduction' clauses in the
/// '#pragma omp ...' directives.
template <class T>
class OMPVarList {
friend class OMPClauseReader;
/// \brief Location of '('.
SourceLocation LParenLoc;
/// \brief Number of variables in the list.
unsigned NumVars;
protected:
/// \brief Fetches list of variables associated with this clause.
llvm::MutableArrayRef<Expr *> getVarRefs() {
return llvm::MutableArrayRef<Expr *>(
reinterpret_cast<Expr **>(static_cast<T *>(this) + 1),
NumVars);
}
/// \brief Sets the list of variables for this clause.
void setVarRefs(ArrayRef<Expr *> VL) {
assert(VL.size() == NumVars &&
"Number of variables is not the same as the preallocated buffer");
std::copy(VL.begin(), VL.end(),
reinterpret_cast<Expr **>(static_cast<T *>(this) + 1));
}
/// \brief Build clause with number of variables \a N.
///
/// \param N Number of the variables in the clause.
///
OMPVarList(SourceLocation LParenLoc, unsigned N)
: LParenLoc(LParenLoc), NumVars(N) { }
public:
typedef llvm::MutableArrayRef<Expr *>::iterator varlist_iterator;
typedef ArrayRef<const Expr *>::iterator varlist_const_iterator;
unsigned varlist_size() const { return NumVars; }
bool varlist_empty() const { return NumVars == 0; }
varlist_iterator varlist_begin() { return getVarRefs().begin(); }
varlist_iterator varlist_end() { return getVarRefs().end(); }
varlist_const_iterator varlist_begin() const { return getVarRefs().begin(); }
varlist_const_iterator varlist_end() const { return getVarRefs().end(); }
/// \brief Sets the location of '('.
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// \brief Returns the location of '('.
SourceLocation getLParenLoc() const { return LParenLoc; }
/// \brief Fetches list of all variables in the clause.
ArrayRef<const Expr *> getVarRefs() const {
return ArrayRef<const Expr *>(
reinterpret_cast<const Expr *const *>(static_cast<const T *>(this) + 1),
NumVars);
}
};
/// \brief This represents 'default' clause in the '#pragma omp ...' directive.
///
/// \code
/// #pragma omp parallel default(shared)
/// \endcode
/// In this example directive '#pragma omp parallel' has simple 'default'
/// clause with kind 'shared'.
///
class OMPDefaultClause : public OMPClause {
friend class OMPClauseReader;
/// \brief Location of '('.
SourceLocation LParenLoc;
/// \brief A kind of the 'default' clause.
OpenMPDefaultClauseKind Kind;
/// \brief Start location of the kind in source code.
SourceLocation KindKwLoc;
/// \brief Set kind of the clauses.
///
/// \param K Argument of clause.
///
void setDefaultKind(OpenMPDefaultClauseKind K) { Kind = K; }
/// \brief Set argument location.
///
/// \param KLoc Argument location.
///
void setDefaultKindKwLoc(SourceLocation KLoc) { KindKwLoc = KLoc; }
public:
/// \brief Build 'default' clause with argument \a A ('none' or 'shared').
///
/// \param A Argument of the clause ('none' or 'shared').
/// \param ALoc Starting location of the argument.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
///
OMPDefaultClause(OpenMPDefaultClauseKind A, SourceLocation ALoc,
SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc)
: OMPClause(OMPC_default, StartLoc, EndLoc), LParenLoc(LParenLoc),
Kind(A), KindKwLoc(ALoc) { }
/// \brief Build an empty clause.
///
OMPDefaultClause()
: OMPClause(OMPC_default, SourceLocation(), SourceLocation()),
LParenLoc(SourceLocation()), Kind(OMPC_DEFAULT_unknown),
KindKwLoc(SourceLocation()) { }
/// \brief Sets the location of '('.
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// \brief Returns the location of '('.
SourceLocation getLParenLoc() const { return LParenLoc; }
/// \brief Returns kind of the clause.
OpenMPDefaultClauseKind getDefaultKind() const { return Kind; }
/// \brief Returns location of clause kind.
SourceLocation getDefaultKindKwLoc() const { return KindKwLoc; }
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_default;
}
StmtRange children() {
return StmtRange();
}
};
/// \brief This represents clause 'private' in the '#pragma omp ...' directives.
///
/// \code
/// #pragma omp parallel private(a,b)
/// \endcode
/// In this example directive '#pragma omp parallel' has clause 'private'
/// with the variables 'a' and 'b'.
///
class OMPPrivateClause : public OMPClause, public OMPVarList<OMPPrivateClause> {
/// \brief Build clause with number of variables \a N.
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param N Number of the variables in the clause.
///
OMPPrivateClause(SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc, unsigned N)
: OMPClause(OMPC_private, StartLoc, EndLoc),
OMPVarList<OMPPrivateClause>(LParenLoc, N) { }
/// \brief Build an empty clause.
///
/// \param N Number of variables.
///
explicit OMPPrivateClause(unsigned N)
: OMPClause(OMPC_private, SourceLocation(), SourceLocation()),
OMPVarList<OMPPrivateClause>(SourceLocation(), N) { }
public:
/// \brief Creates clause with a list of variables \a VL.
///
/// \param C AST context.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param VL List of references to the variables.
///
static OMPPrivateClause *Create(const ASTContext &C, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc,
ArrayRef<Expr *> VL);
/// \brief Creates an empty clause with the place for \a N variables.
///
/// \param C AST context.
/// \param N The number of variables.
///
static OMPPrivateClause *CreateEmpty(const ASTContext &C, unsigned N);
StmtRange children() {
return StmtRange(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_private;
}
};
/// \brief This represents clause 'firstprivate' in the '#pragma omp ...'
/// directives.
///
/// \code
/// #pragma omp parallel firstprivate(a,b)
/// \endcode
/// In this example directive '#pragma omp parallel' has clause 'firstprivate'
/// with the variables 'a' and 'b'.
///
class OMPFirstprivateClause : public OMPClause,
public OMPVarList<OMPFirstprivateClause> {
/// \brief Build clause with number of variables \a N.
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param N Number of the variables in the clause.
///
OMPFirstprivateClause(SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc, unsigned N)
: OMPClause(OMPC_firstprivate, StartLoc, EndLoc),
OMPVarList<OMPFirstprivateClause>(LParenLoc, N) { }
/// \brief Build an empty clause.
///
/// \param N Number of variables.
///
explicit OMPFirstprivateClause(unsigned N)
: OMPClause(OMPC_firstprivate, SourceLocation(), SourceLocation()),
OMPVarList<OMPFirstprivateClause>(SourceLocation(), N) { }
public:
/// \brief Creates clause with a list of variables \a VL.
///
/// \param C AST context.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param VL List of references to the variables.
///
static OMPFirstprivateClause *Create(const ASTContext &C,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc,
ArrayRef<Expr *> VL);
/// \brief Creates an empty clause with the place for \a N variables.
///
/// \param C AST context.
/// \param N The number of variables.
///
static OMPFirstprivateClause *CreateEmpty(const ASTContext &C, unsigned N);
StmtRange children() {
return StmtRange(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_firstprivate;
}
};
/// \brief This represents clause 'shared' in the '#pragma omp ...' directives.
///
/// \code
/// #pragma omp parallel shared(a,b)
/// \endcode
/// In this example directive '#pragma omp parallel' has clause 'shared'
/// with the variables 'a' and 'b'.
///
class OMPSharedClause : public OMPClause, public OMPVarList<OMPSharedClause> {
/// \brief Build clause with number of variables \a N.
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param N Number of the variables in the clause.
///
OMPSharedClause(SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc, unsigned N)
: OMPClause(OMPC_shared, StartLoc, EndLoc),
OMPVarList<OMPSharedClause>(LParenLoc, N) { }
/// \brief Build an empty clause.
///
/// \param N Number of variables.
///
explicit OMPSharedClause(unsigned N)
: OMPClause(OMPC_shared, SourceLocation(), SourceLocation()),
OMPVarList<OMPSharedClause>(SourceLocation(), N) { }
public:
/// \brief Creates clause with a list of variables \a VL.
///
/// \param C AST context.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param VL List of references to the variables.
///
static OMPSharedClause *Create(const ASTContext &C, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc, ArrayRef<Expr *> VL);
/// \brief Creates an empty clause with \a N variables.
///
/// \param C AST context.
/// \param N The number of variables.
///
static OMPSharedClause *CreateEmpty(const ASTContext &C, unsigned N);
StmtRange children() {
return StmtRange(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == OMPC_shared;
}
};
//===----------------------------------------------------------------------===//
// AST classes for directives.
//===----------------------------------------------------------------------===//
@ -386,6 +42,7 @@ class OMPExecutableDirective : public Stmt {
llvm::MutableArrayRef<OMPClause *> Clauses;
/// \brief Associated statement (if any) and expressions.
llvm::MutableArrayRef<Stmt *> StmtAndExpressions;
protected:
/// \brief Build instance of directive of class \a K.
///
@ -398,11 +55,14 @@ protected:
OMPExecutableDirective(const T *, StmtClass SC, OpenMPDirectiveKind K,
SourceLocation StartLoc, SourceLocation EndLoc,
unsigned NumClauses, unsigned NumberOfExpressions)
: Stmt(SC), Kind(K), StartLoc(StartLoc), EndLoc(EndLoc),
Clauses(reinterpret_cast<OMPClause **>(static_cast<T *>(this) + 1),
NumClauses),
StmtAndExpressions(reinterpret_cast<Stmt **>(Clauses.end()),
NumberOfExpressions) { }
: Stmt(SC), Kind(K), StartLoc(StartLoc), EndLoc(EndLoc),
Clauses(reinterpret_cast<OMPClause **>(
reinterpret_cast<char *>(this) +
llvm::RoundUpToAlignment(sizeof(T),
llvm::alignOf<OMPClause *>())),
NumClauses),
StmtAndExpressions(reinterpret_cast<Stmt **>(Clauses.end()),
NumberOfExpressions) {}
/// \brief Sets the list of variables for this clause.
///
@ -414,9 +74,7 @@ protected:
///
/// /param S Associated statement.
///
void setAssociatedStmt(Stmt *S) {
StmtAndExpressions[0] = S;
}
void setAssociatedStmt(Stmt *S) { StmtAndExpressions[0] = S; }
public:
/// \brief Returns starting location of directive kind.
@ -448,9 +106,7 @@ public:
}
/// \brief Returns statement associated with the directive.
Stmt *getAssociatedStmt() const {
return StmtAndExpressions[0];
}
Stmt *getAssociatedStmt() const { return StmtAndExpressions[0]; }
OpenMPDirectiveKind getDirectiveKind() const { return Kind; }
@ -484,17 +140,19 @@ class OMPParallelDirective : public OMPExecutableDirective {
/// \param EndLoc Ending Location of the directive.
///
OMPParallelDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned N)
: OMPExecutableDirective(this, OMPParallelDirectiveClass, OMPD_parallel,
StartLoc, EndLoc, N, 1) { }
unsigned NumClauses)
: OMPExecutableDirective(this, OMPParallelDirectiveClass, OMPD_parallel,
StartLoc, EndLoc, NumClauses, 1) {}
/// \brief Build an empty directive.
///
/// \param N Number of clauses.
/// \param NumClauses Number of clauses.
///
explicit OMPParallelDirective(unsigned N)
: OMPExecutableDirective(this, OMPParallelDirectiveClass, OMPD_parallel,
SourceLocation(), SourceLocation(), N, 1) { }
explicit OMPParallelDirective(unsigned NumClauses)
: OMPExecutableDirective(this, OMPParallelDirectiveClass, OMPD_parallel,
SourceLocation(), SourceLocation(),
NumClauses, 1) {}
public:
/// \brief Creates directive with a list of \a Clauses.
///
@ -504,18 +162,17 @@ public:
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement associated with the directive.
///
static OMPParallelDirective *Create(const ASTContext &C,
SourceLocation StartLoc,
SourceLocation EndLoc,
ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt);
static OMPParallelDirective *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt);
/// \brief Creates an empty directive with the place for \a N clauses.
///
/// \param C AST context.
/// \param N The number of clauses.
/// \param NumClauses Number of clauses.
///
static OMPParallelDirective *CreateEmpty(const ASTContext &C, unsigned N,
static OMPParallelDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses,
EmptyShell);
static bool classof(const Stmt *T) {
@ -523,6 +180,76 @@ public:
}
};
} // end namespace clang
/// \brief This represents '#pragma omp simd' directive.
///
/// \code
/// #pragma omp simd private(a,b) linear(i,j:s) reduction(+:c,d)
/// \endcode
/// In this example directive '#pragma omp simd' has clauses 'private'
/// with the variables 'a' and 'b', 'linear' with variables 'i', 'j' and
/// linear step 's', 'reduction' with operator '+' and variables 'c' and 'd'.
///
class OMPSimdDirective : public OMPExecutableDirective {
friend class ASTStmtReader;
/// \brief Number of collapsed loops as specified by 'collapse' clause.
unsigned CollapsedNum;
/// \brief Build directive with the given start and end location.
///
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending location of the directive.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
OMPSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc,
unsigned CollapsedNum, unsigned NumClauses)
: OMPExecutableDirective(this, OMPSimdDirectiveClass, OMPD_simd,
StartLoc, EndLoc, NumClauses, 1),
CollapsedNum(CollapsedNum) { }
/// \brief Build an empty directive.
///
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
explicit OMPSimdDirective(unsigned CollapsedNum, unsigned NumClauses)
: OMPExecutableDirective(this, OMPSimdDirectiveClass, OMPD_simd,
SourceLocation(), SourceLocation(),
NumClauses, 1),
CollapsedNum(CollapsedNum) { }
public:
/// \brief Creates directive with a list of \a Clauses.
///
/// \param C AST context.
/// \param StartLoc Starting location of the directive kind.
/// \param EndLoc Ending Location of the directive.
/// \param Clauses List of clauses.
/// \param AssociatedStmt Statement, associated with the directive.
///
static OMPSimdDirective *Create(const ASTContext &C,
SourceLocation StartLoc,
SourceLocation EndLoc,
ArrayRef<OMPClause *> Clauses,
Stmt *AssociatedStmt);
/// \brief Creates an empty directive with the place
/// for \a NumClauses clauses.
///
/// \param C AST context.
/// \param CollapsedNum Number of collapsed nested loops.
/// \param NumClauses Number of clauses.
///
static OMPSimdDirective *CreateEmpty(const ASTContext &C,
unsigned NumClauses,
unsigned CollapsedNum,
EmptyShell);
unsigned getCollapsedNumber() const { return CollapsedNum; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == OMPSimdDirectiveClass;
}
};
} // end namespace clang
#endif

View File

@ -34,8 +34,7 @@ struct PrintingPolicy;
class TypeSourceInfo;
class ValueDecl;
/// \brief Represents a template argument within a class template
/// specialization.
/// \brief Represents a template argument.
class TemplateArgument {
public:
/// \brief The kind of template argument we're storing.
@ -52,16 +51,19 @@ public:
/// was provided for a non-type template parameter.
NullPtr,
/// The template argument is an integral value stored in an llvm::APSInt
/// that was provided for an integral non-type template parameter.
/// that was provided for an integral non-type template parameter.
Integral,
/// The template argument is a template name that was provided for a
/// The template argument is a template name that was provided for a
/// template template parameter.
Template,
/// The template argument is a pack expansion of a template name that was
/// The template argument is a pack expansion of a template name that was
/// provided for a template template parameter.
TemplateExpansion,
/// The template argument is a value- or type-dependent expression or a
/// non-dependent __uuidof expression stored in an Expr*.
/// The template argument is an expression, and we've not resolved it to one
/// of the other forms yet, either because it's dependent or because we're
/// representing a non-canonical template argument (for instance, in a
/// TemplateSpecializationType). Also used to represent a non-dependent
/// __uuidof expression (a Microsoft extension).
Expression,
/// The template argument is actually a parameter pack. Arguments are stored
/// in the Args struct.

View File

@ -366,76 +366,37 @@ public:
}
};
struct VFPtrInfo {
/// Holds information about the inheritance path to a virtual base or function
/// table pointer. A record may contain as many vfptrs or vbptrs as there are
/// base subobjects.
struct VPtrInfo {
typedef SmallVector<const CXXRecordDecl *, 1> BasePath;
// Don't pass the PathToMangle as it should be calculated later.
VFPtrInfo(CharUnits VFPtrOffset, const BasePath &PathToBaseWithVFPtr)
: VBTableIndex(0), LastVBase(0), VFPtrOffset(VFPtrOffset),
PathToBaseWithVFPtr(PathToBaseWithVFPtr), VFPtrFullOffset(VFPtrOffset) {
}
// Don't pass the PathToMangle as it should be calculated later.
VFPtrInfo(uint64_t VBTableIndex, const CXXRecordDecl *LastVBase,
CharUnits VFPtrOffset, const BasePath &PathToBaseWithVFPtr,
CharUnits VFPtrFullOffset)
: VBTableIndex(VBTableIndex), LastVBase(LastVBase),
VFPtrOffset(VFPtrOffset), PathToBaseWithVFPtr(PathToBaseWithVFPtr),
VFPtrFullOffset(VFPtrFullOffset) {
assert(VBTableIndex && "The full constructor should only be used "
"for vfptrs in virtual bases");
assert(LastVBase);
}
/// If nonzero, holds the vbtable index of the virtual base with the vfptr.
uint64_t VBTableIndex;
/// Stores the last vbase on the path from the complete type to the vfptr.
const CXXRecordDecl *LastVBase;
/// This is the offset of the vfptr from the start of the last vbase,
/// or the complete type if there are no virtual bases.
CharUnits VFPtrOffset;
/// This holds the base classes path from the complete type to the first base
/// with the given vfptr offset, in the base-to-derived order.
BasePath PathToBaseWithVFPtr;
/// This holds the subset of records that need to be mangled into the vftable
/// symbol name in order to get a unique name, in the derived-to-base order.
BasePath PathToMangle;
/// This is the full offset of the vfptr from the start of the complete type.
CharUnits VFPtrFullOffset;
};
/// Holds information for a virtual base table for a single subobject. A record
/// may contain as many vbptrs as there are base subobjects.
struct VBTableInfo {
VBTableInfo(const CXXRecordDecl *RD)
: ReusingBase(RD), BaseWithVBPtr(RD), NextBaseToMangle(RD) {}
VPtrInfo(const CXXRecordDecl *RD)
: ReusingBase(RD), BaseWithVPtr(RD), NextBaseToMangle(RD) {}
// Copy constructor.
// FIXME: Uncomment when we've moved to C++11.
//VBTableInfo(const VBTableInfo &) = default;
// VPtrInfo(const VPtrInfo &) = default;
/// The vbtable will hold all of the virtual bases of ReusingBase. This may
/// or may not be the same class as VBPtrSubobject.Base. A derived class will
/// reuse the vbptr of the first non-virtual base subobject that has one.
/// The vtable will hold all of the virtual bases or virtual methods of
/// ReusingBase. This may or may not be the same class as VPtrSubobject.Base.
/// A derived class will reuse the vptr of the first non-virtual base
/// subobject that has one.
const CXXRecordDecl *ReusingBase;
/// BaseWithVBPtr is at this offset from its containing complete object or
/// BaseWithVPtr is at this offset from its containing complete object or
/// virtual base.
CharUnits NonVirtualOffset;
/// The vbptr is stored inside this subobject.
const CXXRecordDecl *BaseWithVBPtr;
/// The vptr is stored inside this subobject.
const CXXRecordDecl *BaseWithVPtr;
/// The bases from the inheritance path that got used to mangle the vbtable
/// name. This is not really a full path like a CXXBasePath. It holds the
/// subset of records that need to be mangled into the vbtable symbol name in
/// order to get a unique name.
SmallVector<const CXXRecordDecl *, 1> MangledPath;
BasePath MangledPath;
/// The next base to push onto the mangled path if this path is ambiguous in a
/// derived class. If it's null, then it's already been pushed onto the path.
@ -443,22 +404,31 @@ struct VBTableInfo {
/// The set of possibly indirect vbases that contain this vbtable. When a
/// derived class indirectly inherits from the same vbase twice, we only keep
/// vbtables and their paths from the first instance.
SmallVector<const CXXRecordDecl *, 1> ContainingVBases;
/// vtables and their paths from the first instance.
BasePath ContainingVBases;
/// The vbptr is stored inside the non-virtual component of this virtual base.
const CXXRecordDecl *getVBaseWithVBPtr() const {
/// This holds the base classes path from the complete type to the first base
/// with the given vfptr offset, in the base-to-derived order. Only used for
/// vftables.
BasePath PathToBaseWithVPtr;
/// Static offset from the top of the most derived class to this vfptr,
/// including any virtual base offset. Only used for vftables.
CharUnits FullOffsetInMDC;
/// The vptr is stored inside the non-virtual component of this virtual base.
const CXXRecordDecl *getVBaseWithVPtr() const {
return ContainingVBases.empty() ? 0 : ContainingVBases.front();
}
};
typedef SmallVector<VBTableInfo *, 2> VBTableVector;
typedef SmallVector<VPtrInfo *, 2> VPtrInfoVector;
/// All virtual base related information about a given record decl. Includes
/// information on all virtual base tables and the path components that are used
/// to mangle them.
struct VirtualBaseInfo {
~VirtualBaseInfo() { llvm::DeleteContainerPointers(VBTables); }
~VirtualBaseInfo() { llvm::DeleteContainerPointers(VBPtrPaths); }
/// A map from virtual base to vbtable index for doing a conversion from the
/// the derived class to the a base.
@ -466,7 +436,7 @@ struct VirtualBaseInfo {
/// Information on all virtual base tables used when this record is the most
/// derived class.
VBTableVector VBTables;
VPtrInfoVector VBPtrPaths;
};
class MicrosoftVTableContext : public VTableContextBase {
@ -508,8 +478,6 @@ public:
}
};
typedef SmallVector<VFPtrInfo, 1> VFPtrListTy;
private:
ASTContext &Context;
@ -517,7 +485,7 @@ private:
MethodVFTableLocationsTy;
MethodVFTableLocationsTy MethodVFTableLocations;
typedef llvm::DenseMap<const CXXRecordDecl *, VFPtrListTy>
typedef llvm::DenseMap<const CXXRecordDecl *, VPtrInfoVector *>
VFPtrLocationsMapTy;
VFPtrLocationsMapTy VFPtrLocations;
@ -527,16 +495,7 @@ private:
llvm::DenseMap<const CXXRecordDecl *, VirtualBaseInfo *> VBaseInfo;
typedef llvm::SmallSetVector<const CXXRecordDecl *, 8> BasesSetVectorTy;
void enumerateVFPtrs(const CXXRecordDecl *MostDerivedClass,
const ASTRecordLayout &MostDerivedClassLayout,
BaseSubobject Base, const CXXRecordDecl *LastVBase,
const VFPtrInfo::BasePath &PathFromCompleteClass,
BasesSetVectorTy &VisitedVBases,
MicrosoftVTableContext::VFPtrListTy &Result);
void enumerateVFPtrs(const CXXRecordDecl *ForClass,
MicrosoftVTableContext::VFPtrListTy &Result);
void enumerateVFPtrs(const CXXRecordDecl *ForClass, VPtrInfoVector &Result);
void computeVTableRelatedInformation(const CXXRecordDecl *RD);
@ -547,7 +506,8 @@ private:
const VirtualBaseInfo *
computeVBTableRelatedInformation(const CXXRecordDecl *RD);
void computeVBTablePaths(const CXXRecordDecl *RD, VBTableVector &Paths);
void computeVTablePaths(bool ForVBTables, const CXXRecordDecl *RD,
VPtrInfoVector &Paths);
public:
MicrosoftVTableContext(ASTContext &Context)
@ -555,7 +515,7 @@ public:
~MicrosoftVTableContext();
const VFPtrListTy &getVFPtrOffsets(const CXXRecordDecl *RD);
const VPtrInfoVector &getVFPtrOffsets(const CXXRecordDecl *RD);
const VTableLayout &getVFTableLayout(const CXXRecordDecl *RD,
CharUnits VFPtrOffset);
@ -577,7 +537,7 @@ public:
unsigned getVBTableIndex(const CXXRecordDecl *Derived,
const CXXRecordDecl *VBase);
const VBTableVector &enumerateVBTables(const CXXRecordDecl *RD);
const VPtrInfoVector &enumerateVBTables(const CXXRecordDecl *RD);
static bool classof(const VTableContextBase *VT) { return VT->isMicrosoft(); }
};

View File

@ -323,9 +323,13 @@ AST_MATCHER(Decl, isPrivate) {
/// classTemplateSpecializationDecl(hasAnyTemplateArgument(
/// refersToType(asString("int"))))
/// matches the specialization \c A<int>
AST_MATCHER_P(ClassTemplateSpecializationDecl, hasAnyTemplateArgument,
internal::Matcher<TemplateArgument>, InnerMatcher) {
llvm::ArrayRef<TemplateArgument> List = Node.getTemplateArgs().asArray();
AST_POLYMORPHIC_MATCHER_P(
hasAnyTemplateArgument,
AST_POLYMORPHIC_SUPPORTED_TYPES_2(ClassTemplateSpecializationDecl,
TemplateSpecializationType),
internal::Matcher<TemplateArgument>, InnerMatcher) {
llvm::ArrayRef<TemplateArgument> List =
internal::getTemplateSpecializationArgs(Node);
return matchesFirstInRange(InnerMatcher, List.begin(), List.end(), Finder,
Builder);
}
@ -419,12 +423,16 @@ AST_MATCHER_P(Expr, ignoringParenImpCasts,
/// classTemplateSpecializationDecl(hasTemplateArgument(
/// 1, refersToType(asString("int"))))
/// matches the specialization \c A<bool, int>
AST_MATCHER_P2(ClassTemplateSpecializationDecl, hasTemplateArgument,
unsigned, N, internal::Matcher<TemplateArgument>, InnerMatcher) {
const TemplateArgumentList &List = Node.getTemplateArgs();
AST_POLYMORPHIC_MATCHER_P2(
hasTemplateArgument,
AST_POLYMORPHIC_SUPPORTED_TYPES_2(ClassTemplateSpecializationDecl,
TemplateSpecializationType),
unsigned, N, internal::Matcher<TemplateArgument>, InnerMatcher) {
llvm::ArrayRef<TemplateArgument> List =
internal::getTemplateSpecializationArgs(Node);
if (List.size() <= N)
return false;
return InnerMatcher.matches(List.get(N), Finder, Builder);
return InnerMatcher.matches(List[N], Finder, Builder);
}
/// \brief Matches a TemplateArgument that refers to a certain type.
@ -445,7 +453,8 @@ AST_MATCHER_P(TemplateArgument, refersToType,
return InnerMatcher.matches(Node.getAsType(), Finder, Builder);
}
/// \brief Matches a TemplateArgument that refers to a certain declaration.
/// \brief Matches a canonical TemplateArgument that refers to a certain
/// declaration.
///
/// Given
/// \code
@ -464,6 +473,24 @@ AST_MATCHER_P(TemplateArgument, refersToDeclaration,
return false;
}
/// \brief Matches a sugar TemplateArgument that refers to a certain expression.
///
/// Given
/// \code
/// template<typename T> struct A {};
/// struct B { B* next; };
/// A<&B::next> a;
/// \endcode
/// templateSpecializationType(hasAnyTemplateArgument(
/// isExpr(hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))
/// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
/// \c B::next
AST_MATCHER_P(TemplateArgument, isExpr, internal::Matcher<Expr>, InnerMatcher) {
if (Node.getKind() == TemplateArgument::Expression)
return InnerMatcher.matches(*Node.getAsExpr(), Finder, Builder);
return false;
}
/// \brief Matches C++ constructor declarations.
///
/// Example matches Foo::Foo() and Foo::Foo(int)
@ -518,7 +545,7 @@ const internal::VariadicDynCastAllOfMatcher<
///
/// Example matches y
/// \code
/// class X { void y() };
/// class X { void y(); };
/// \endcode
const internal::VariadicDynCastAllOfMatcher<Decl, CXXMethodDecl> methodDecl;
@ -2283,16 +2310,6 @@ AST_POLYMORPHIC_MATCHER_P(
InnerMatcher.matches(*Condition, Finder, Builder));
}
namespace internal {
struct NotEqualsBoundNodePredicate {
bool operator()(const internal::BoundNodesMap &Nodes) const {
return Nodes.getNode(ID) != Node;
}
std::string ID;
ast_type_traits::DynTypedNode Node;
};
} // namespace internal
/// \brief Matches if a node equals a previously bound node.
///
/// Matches a node if it equals the node previously bound to \p ID.
@ -2619,6 +2636,20 @@ AST_MATCHER(CXXMethodDecl, isVirtual) {
return Node.isVirtual();
}
/// \brief Matches if the given method declaration is pure.
///
/// Given
/// \code
/// class A {
/// public:
/// virtual void x() = 0;
/// };
/// \endcode
/// matches A::x
AST_MATCHER(CXXMethodDecl, isPure) {
return Node.isPure();
}
/// \brief Matches if the given method declaration is const.
///
/// Given

View File

@ -1579,6 +1579,26 @@ TypeTraversePolymorphicMatcher<
return Self(InnerMatchers);
}
// FIXME: unify ClassTemplateSpecializationDecl and TemplateSpecializationType's
// APIs for accessing the template argument list.
inline llvm::ArrayRef<TemplateArgument>
getTemplateSpecializationArgs(const ClassTemplateSpecializationDecl &D) {
return D.getTemplateArgs().asArray();
}
inline llvm::ArrayRef<TemplateArgument>
getTemplateSpecializationArgs(const TemplateSpecializationType &T) {
return llvm::ArrayRef<TemplateArgument>(T.getArgs(), T.getNumArgs());
}
struct NotEqualsBoundNodePredicate {
bool operator()(const internal::BoundNodesMap &Nodes) const {
return Nodes.getNode(ID) != Node;
}
std::string ID;
ast_type_traits::DynTypedNode Node;
};
} // end namespace internal
} // end namespace ast_matchers
} // end namespace clang

View File

@ -412,9 +412,64 @@ class CFGBlock {
/// of the CFG.
unsigned BlockID;
public:
/// This class represents a potential adjacent block in the CFG. It encodes
/// whether or not the block is actually reachable, or can be proved to be
/// trivially unreachable. For some cases it allows one to encode scenarios
/// where a block was substituted because the original (now alternate) block
/// is unreachable.
class AdjacentBlock {
enum Kind {
AB_Normal,
AB_Unreachable,
AB_Alternate
};
CFGBlock *ReachableBlock;
llvm::PointerIntPair<CFGBlock*, 2> UnreachableBlock;
public:
/// Construct an AdjacentBlock with a possibly unreachable block.
AdjacentBlock(CFGBlock *B, bool IsReachable);
/// Construct an AdjacentBlock with a reachable block and an alternate
/// unreachable block.
AdjacentBlock(CFGBlock *B, CFGBlock *AlternateBlock);
/// Get the reachable block, if one exists.
CFGBlock *getReachableBlock() const {
return ReachableBlock;
}
/// Get the potentially unreachable block.
CFGBlock *getPossiblyUnreachableBlock() const {
return UnreachableBlock.getPointer();
}
/// Provide an implicit conversion to CFGBlock* so that
/// AdjacentBlock can be substituted for CFGBlock*.
operator CFGBlock*() const {
return getReachableBlock();
}
CFGBlock& operator *() const {
return *getReachableBlock();
}
CFGBlock* operator ->() const {
return getReachableBlock();
}
bool isReachable() const {
Kind K = (Kind) UnreachableBlock.getInt();
return K == AB_Normal || K == AB_Alternate;
}
};
private:
/// Predecessors/Successors - Keep track of the predecessor / successor
/// CFG blocks.
typedef BumpVector<CFGBlock*> AdjacentBlocks;
typedef BumpVector<AdjacentBlock> AdjacentBlocks;
AdjacentBlocks Preds;
AdjacentBlocks Succs;
@ -504,9 +559,11 @@ public:
class FilterOptions {
public:
FilterOptions() {
IgnoreNullPredecessors = 1;
IgnoreDefaultsWithCoveredEnums = 0;
}
unsigned IgnoreNullPredecessors : 1;
unsigned IgnoreDefaultsWithCoveredEnums : 1;
};
@ -519,11 +576,14 @@ public:
IMPL I, E;
const FilterOptions F;
const CFGBlock *From;
public:
public:
explicit FilteredCFGBlockIterator(const IMPL &i, const IMPL &e,
const CFGBlock *from,
const FilterOptions &f)
: I(i), E(e), F(f), From(from) {}
const CFGBlock *from,
const FilterOptions &f)
: I(i), E(e), F(f), From(from) {
while (hasMore() && Filter(*I))
++I;
}
bool hasMore() const { return I != E; }
@ -588,11 +648,8 @@ public:
OS << "BB#" << getBlockID();
}
void addSuccessor(CFGBlock *Block, BumpVectorContext &C) {
if (Block)
Block->Preds.push_back(this, C);
Succs.push_back(Block, C);
}
/// Adds a (potentially unreachable) successor block to the current block.
void addSuccessor(AdjacentBlock Succ, BumpVectorContext &C);
void appendStmt(Stmt *statement, BumpVectorContext &C) {
Elements.push_back(CFGStmt(statement), C);

View File

@ -658,11 +658,11 @@ protected:
private:
const void *TagKind;
};
class SimpleProgramPointTag : public ProgramPointTag {
std::string desc;
std::string Desc;
public:
SimpleProgramPointTag(StringRef description);
SimpleProgramPointTag(StringRef MsgProvider, StringRef Msg);
StringRef getTagDescription() const;
};

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,939 @@
//==--- AttrDocs.td - Attribute documentation ----------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===---------------------------------------------------------------------===//
def GlobalDocumentation {
code Intro =[{..
-------------------------------------------------------------------
NOTE: This file is automatically generated by running clang-tblgen
-gen-attr-docs. Do not edit this file by hand!!
-------------------------------------------------------------------
===================
Attributes in Clang
===================
.. contents::
:local:
Introduction
============
This page lists the attributes currently supported by Clang.
}];
}
def TLSModelDocs : Documentation {
let Category = DocCatVariable;
let Content = [{
The ``tls_model`` attribute allows you to specify which thread-local storage
model to use. It accepts the following strings:
* global-dynamic
* local-dynamic
* initial-exec
* local-exec
TLS models are mutually exclusive.
}];
}
def CarriesDependencyDocs : Documentation {
let Category = DocCatFunction;
let Content = [{
The ``carries_dependency`` attribute specifies dependency propagation into and
out of functions.
When specified on a function or Objective-C method, the ``carries_depedency``
attribute means that the return value carries a dependency out of the function,
so that the implementation need not constrain ordering upon return from that
function. Implementations of the function and its caller may choose to preserve
dependencies instead of emitting memory ordering instructions such as fences.
Note, this attribute does not change the meaning of the program, but may result
in generatation of more efficient code.
}];
}
def C11NoReturnDocs : Documentation {
let Category = DocCatFunction;
let Content = [{
A function declared as ``_Noreturn`` shall not return to its caller. The
compiler will generate a diagnostic for a function declared as ``_Noreturn``
that appears to be capable of returning to its caller.
}];
}
def CXX11NoReturnDocs : Documentation {
let Category = DocCatFunction;
let Content = [{
A function declared as ``[[noreturn]]`` shall not return to its caller. The
compiler will generate a diagnostic for a function declared as ``[[noreturn]]``
that appears to be capable of returning to its caller.
}];
}
def AssertCapabilityDocs : Documentation {
let Category = DocCatFunction;
let Heading = "assert_capability (assert_shared_capability, clang::assert_capability, clang::assert_shared_capability)";
let Content = [{
Marks a function that dynamically tests whether a capability is held, and halts
the program if it is not held.
}];
}
def AcquireCapabilityDocs : Documentation {
let Category = DocCatFunction;
let Heading = "acquire_capability (acquire_shared_capability, clang::acquire_capability, clang::acquire_shared_capability)";
let Content = [{
Marks a function as acquiring a capability.
}];
}
def TryAcquireCapabilityDocs : Documentation {
let Category = DocCatFunction;
let Heading = "try_acquire_capability (try_acquire_shared_capability, clang::try_acquire_capability, clang::try_acquire_shared_capability)";
let Content = [{
Marks a function that attempts to acquire a capability. This function may fail to
actually acquire the capability; they accept a Boolean value determining
whether acquiring the capability means success (true), or failing to acquire
the capability means success (false).
}];
}
def ReleaseCapabilityDocs : Documentation {
let Category = DocCatFunction;
let Heading = "release_capability (release_shared_capability, clang::release_capability, clang::release_shared_capability)";
let Content = [{
Marks a function as releasing a capability.
}];
}
def EnableIfDocs : Documentation {
let Category = DocCatFunction;
let Content = [{
The ``enable_if`` attribute can be placed on function declarations to control
which overload is selected based on the values of the function's arguments.
When combined with the ``overloadable`` attribute, this feature is also
available in C.
.. code-block:: c++
int isdigit(int c);
int isdigit(int c) __attribute__((enable_if(c <= -1 || c > 255, "chosen when 'c' is out of range"))) __attribute__((unavailable("'c' must have the value of an unsigned char or EOF")));
void foo(char c) {
isdigit(c);
isdigit(10);
isdigit(-10); // results in a compile-time error.
}
The enable_if attribute takes two arguments, the first is an expression written
in terms of the function parameters, the second is a string explaining why this
overload candidate could not be selected to be displayed in diagnostics. The
expression is part of the function signature for the purposes of determining
whether it is a redeclaration (following the rules used when determining
whether a C++ template specialization is ODR-equivalent), but is not part of
the type.
The enable_if expression is evaluated as if it were the body of a
bool-returning constexpr function declared with the arguments of the function
it is being applied to, then called with the parameters at the callsite. If the
result is false or could not be determined through constant expression
evaluation, then this overload will not be chosen and the provided string may
be used in a diagnostic if the compile fails as a result.
Because the enable_if expression is an unevaluated context, there are no global
state changes, nor the ability to pass information from the enable_if
expression to the function body. For example, suppose we want calls to
strnlen(strbuf, maxlen) to resolve to strnlen_chk(strbuf, maxlen, size of
strbuf) only if the size of strbuf can be determined:
.. code-block:: c++
__attribute__((always_inline))
static inline size_t strnlen(const char *s, size_t maxlen)
__attribute__((overloadable))
__attribute__((enable_if(__builtin_object_size(s, 0) != -1))),
"chosen when the buffer size is known but 'maxlen' is not")))
{
return strnlen_chk(s, maxlen, __builtin_object_size(s, 0));
}
Multiple enable_if attributes may be applied to a single declaration. In this
case, the enable_if expressions are evaluated from left to right in the
following manner. First, the candidates whose enable_if expressions evaluate to
false or cannot be evaluated are discarded. If the remaining candidates do not
share ODR-equivalent enable_if expressions, the overload resolution is
ambiguous. Otherwise, enable_if overload resolution continues with the next
enable_if attribute on the candidates that have not been discarded and have
remaining enable_if attributes. In this way, we pick the most specific
overload out of a number of viable overloads using enable_if.
.. code-block:: c++
void f() __attribute__((enable_if(true, ""))); // #1
void f() __attribute__((enable_if(true, ""))) __attribute__((enable_if(true, ""))); // #2
void g(int i, int j) __attribute__((enable_if(i, ""))); // #1
void g(int i, int j) __attribute__((enable_if(j, ""))) __attribute__((enable_if(true))); // #2
In this example, a call to f() is always resolved to #2, as the first enable_if
expression is ODR-equivalent for both declarations, but #1 does not have another
enable_if expression to continue evaluating, so the next round of evaluation has
only a single candidate. In a call to g(1, 1), the call is ambiguous even though
#2 has more enable_if attributes, because the first enable_if expressions are
not ODR-equivalent.
Query for this feature with ``__has_attribute(enable_if)``.
}];
}
def OverloadableDocs : Documentation {
let Category = DocCatFunction;
let Content = [{
Clang provides support for C++ function overloading in C. Function overloading
in C is introduced using the ``overloadable`` attribute. For example, one
might provide several overloaded versions of a ``tgsin`` function that invokes
the appropriate standard function computing the sine of a value with ``float``,
``double``, or ``long double`` precision:
.. code-block:: c
#include <math.h>
float __attribute__((overloadable)) tgsin(float x) { return sinf(x); }
double __attribute__((overloadable)) tgsin(double x) { return sin(x); }
long double __attribute__((overloadable)) tgsin(long double x) { return sinl(x); }
Given these declarations, one can call ``tgsin`` with a ``float`` value to
receive a ``float`` result, with a ``double`` to receive a ``double`` result,
etc. Function overloading in C follows the rules of C++ function overloading
to pick the best overload given the call arguments, with a few C-specific
semantics:
* Conversion from ``float`` or ``double`` to ``long double`` is ranked as a
floating-point promotion (per C99) rather than as a floating-point conversion
(as in C++).
* A conversion from a pointer of type ``T*`` to a pointer of type ``U*`` is
considered a pointer conversion (with conversion rank) if ``T`` and ``U`` are
compatible types.
* A conversion from type ``T`` to a value of type ``U`` is permitted if ``T``
and ``U`` are compatible types. This conversion is given "conversion" rank.
The declaration of ``overloadable`` functions is restricted to function
declarations and definitions. Most importantly, if any function with a given
name is given the ``overloadable`` attribute, then all function declarations
and definitions with that name (and in that scope) must have the
``overloadable`` attribute. This rule even applies to redeclarations of
functions whose original declaration had the ``overloadable`` attribute, e.g.,
.. code-block:: c
int f(int) __attribute__((overloadable));
float f(float); // error: declaration of "f" must have the "overloadable" attribute
int g(int) __attribute__((overloadable));
int g(int) { } // error: redeclaration of "g" must also have the "overloadable" attribute
Functions marked ``overloadable`` must have prototypes. Therefore, the
following code is ill-formed:
.. code-block:: c
int h() __attribute__((overloadable)); // error: h does not have a prototype
However, ``overloadable`` functions are allowed to use a ellipsis even if there
are no named parameters (as is permitted in C++). This feature is particularly
useful when combined with the ``unavailable`` attribute:
.. code-block:: c++
void honeypot(...) __attribute__((overloadable, unavailable)); // calling me is an error
Functions declared with the ``overloadable`` attribute have their names mangled
according to the same rules as C++ function names. For example, the three
``tgsin`` functions in our motivating example get the mangled names
``_Z5tgsinf``, ``_Z5tgsind``, and ``_Z5tgsine``, respectively. There are two
caveats to this use of name mangling:
* Future versions of Clang may change the name mangling of functions overloaded
in C, so you should not depend on an specific mangling. To be completely
safe, we strongly urge the use of ``static inline`` with ``overloadable``
functions.
* The ``overloadable`` attribute has almost no meaning when used in C++,
because names will already be mangled and functions are already overloadable.
However, when an ``overloadable`` function occurs within an ``extern "C"``
linkage specification, it's name *will* be mangled in the same way as it
would in C.
Query for this feature with ``__has_extension(attribute_overloadable)``.
}];
}
def ObjCMethodFamilyDocs : Documentation {
let Category = DocCatFunction;
let Content = [{
Many methods in Objective-C have conventional meanings determined by their
selectors. It is sometimes useful to be able to mark a method as having a
particular conventional meaning despite not having the right selector, or as
not having the conventional meaning that its selector would suggest. For these
use cases, we provide an attribute to specifically describe the "method family"
that a method belongs to.
**Usage**: ``__attribute__((objc_method_family(X)))``, where ``X`` is one of
``none``, ``alloc``, ``copy``, ``init``, ``mutableCopy``, or ``new``. This
attribute can only be placed at the end of a method declaration:
.. code-block:: objc
- (NSString *)initMyStringValue __attribute__((objc_method_family(none)));
Users who do not wish to change the conventional meaning of a method, and who
merely want to document its non-standard retain and release semantics, should
use the retaining behavior attributes (``ns_returns_retained``,
``ns_returns_not_retained``, etc).
Query for this feature with ``__has_attribute(objc_method_family)``.
}];
}
def NoDuplicateDocs : Documentation {
let Category = DocCatFunction;
let Content = [{
The ``noduplicate`` attribute can be placed on function declarations to control
whether function calls to this function can be duplicated or not as a result of
optimizations. This is required for the implementation of functions with
certain special requirements, like the OpenCL "barrier" function, that might
need to be run concurrently by all the threads that are executing in lockstep
on the hardware. For example this attribute applied on the function
"nodupfunc" in the code below avoids that:
.. code-block:: c
void nodupfunc() __attribute__((noduplicate));
// Setting it as a C++11 attribute is also valid
// void nodupfunc() [[clang::noduplicate]];
void foo();
void bar();
nodupfunc();
if (a > n) {
foo();
} else {
bar();
}
gets possibly modified by some optimizations into code similar to this:
.. code-block:: c
if (a > n) {
nodupfunc();
foo();
} else {
nodupfunc();
bar();
}
where the call to "nodupfunc" is duplicated and sunk into the two branches
of the condition.
}];
}
def ObjCRequiresSuperDocs : Documentation {
let Category = DocCatFunction;
let Content = [{
Some Objective-C classes allow a subclass to override a particular method in a
parent class but expect that the overriding method also calls the overridden
method in the parent class. For these cases, we provide an attribute to
designate that a method requires a "call to ``super``" in the overriding
method in the subclass.
**Usage**: ``__attribute__((objc_requires_super))``. This attribute can only
be placed at the end of a method declaration:
.. code-block:: objc
- (void)foo __attribute__((objc_requires_super));
This attribute can only be applied the method declarations within a class, and
not a protocol. Currently this attribute does not enforce any placement of
where the call occurs in the overriding method (such as in the case of
``-dealloc`` where the call must appear at the end). It checks only that it
exists.
Note that on both OS X and iOS that the Foundation framework provides a
convenience macro ``NS_REQUIRES_SUPER`` that provides syntactic sugar for this
attribute:
.. code-block:: objc
- (void)foo NS_REQUIRES_SUPER;
This macro is conditionally defined depending on the compiler's support for
this attribute. If the compiler does not support the attribute the macro
expands to nothing.
Operationally, when a method has this annotation the compiler will warn if the
implementation of an override in a subclass does not call super. For example:
.. code-block:: objc
warning: method possibly missing a [super AnnotMeth] call
- (void) AnnotMeth{};
^
}];
}
def AvailabilityDocs : Documentation {
let Category = DocCatFunction;
let Content = [{
The ``availability`` attribute can be placed on declarations to describe the
lifecycle of that declaration relative to operating system versions. Consider
the function declaration for a hypothetical function ``f``:
.. code-block:: c++
void f(void) __attribute__((availability(macosx,introduced=10.4,deprecated=10.6,obsoleted=10.7)));
The availability attribute states that ``f`` was introduced in Mac OS X 10.4,
deprecated in Mac OS X 10.6, and obsoleted in Mac OS X 10.7. This information
is used by Clang to determine when it is safe to use ``f``: for example, if
Clang is instructed to compile code for Mac OS X 10.5, a call to ``f()``
succeeds. If Clang is instructed to compile code for Mac OS X 10.6, the call
succeeds but Clang emits a warning specifying that the function is deprecated.
Finally, if Clang is instructed to compile code for Mac OS X 10.7, the call
fails because ``f()`` is no longer available.
The availability attribute is a comma-separated list starting with the
platform name and then including clauses specifying important milestones in the
declaration's lifetime (in any order) along with additional information. Those
clauses can be:
introduced=\ *version*
The first version in which this declaration was introduced.
deprecated=\ *version*
The first version in which this declaration was deprecated, meaning that
users should migrate away from this API.
obsoleted=\ *version*
The first version in which this declaration was obsoleted, meaning that it
was removed completely and can no longer be used.
unavailable
This declaration is never available on this platform.
message=\ *string-literal*
Additional message text that Clang will provide when emitting a warning or
error about use of a deprecated or obsoleted declaration. Useful to direct
users to replacement APIs.
Multiple availability attributes can be placed on a declaration, which may
correspond to different platforms. Only the availability attribute with the
platform corresponding to the target platform will be used; any others will be
ignored. If no availability attribute specifies availability for the current
target platform, the availability attributes are ignored. Supported platforms
are:
``ios``
Apple's iOS operating system. The minimum deployment target is specified by
the ``-mios-version-min=*version*`` or ``-miphoneos-version-min=*version*``
command-line arguments.
``macosx``
Apple's Mac OS X operating system. The minimum deployment target is
specified by the ``-mmacosx-version-min=*version*`` command-line argument.
A declaration can be used even when deploying back to a platform version prior
to when the declaration was introduced. When this happens, the declaration is
`weakly linked
<https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPFrameworks/Concepts/WeakLinking.html>`_,
as if the ``weak_import`` attribute were added to the declaration. A
weakly-linked declaration may or may not be present a run-time, and a program
can determine whether the declaration is present by checking whether the
address of that declaration is non-NULL.
If there are multiple declarations of the same entity, the availability
attributes must either match on a per-platform basis or later
declarations must not have availability attributes for that
platform. For example:
.. code-block:: c
void g(void) __attribute__((availability(macosx,introduced=10.4)));
void g(void) __attribute__((availability(macosx,introduced=10.4))); // okay, matches
void g(void) __attribute__((availability(ios,introduced=4.0))); // okay, adds a new platform
void g(void); // okay, inherits both macosx and ios availability from above.
void g(void) __attribute__((availability(macosx,introduced=10.5))); // error: mismatch
When one method overrides another, the overriding method can be more widely available than the overridden method, e.g.,:
.. code-block:: objc
@interface A
- (id)method __attribute__((availability(macosx,introduced=10.4)));
- (id)method2 __attribute__((availability(macosx,introduced=10.4)));
@end
@interface B : A
- (id)method __attribute__((availability(macosx,introduced=10.3))); // okay: method moved into base class later
- (id)method __attribute__((availability(macosx,introduced=10.5))); // error: this method was available via the base class in 10.4
@end
}];
}
def FallthroughDocs : Documentation {
let Category = DocCatStmt;
let Content = [{
The ``clang::fallthrough`` attribute is used along with the
``-Wimplicit-fallthrough`` argument to annotate intentional fall-through
between switch labels. It can only be applied to a null statement placed at a
point of execution between any statement and the next switch label. It is
common to mark these places with a specific comment, but this attribute is
meant to replace comments with a more strict annotation, which can be checked
by the compiler. This attribute doesn't change semantics of the code and can
be used wherever an intended fall-through occurs. It is designed to mimic
control-flow statements like ``break;``, so it can be placed in most places
where ``break;`` can, but only if there are no statements on the execution path
between it and the next switch label.
Here is an example:
.. code-block:: c++
// compile with -Wimplicit-fallthrough
switch (n) {
case 22:
case 33: // no warning: no statements between case labels
f();
case 44: // warning: unannotated fall-through
g();
[[clang::fallthrough]];
case 55: // no warning
if (x) {
h();
break;
}
else {
i();
[[clang::fallthrough]];
}
case 66: // no warning
p();
[[clang::fallthrough]]; // warning: fallthrough annotation does not
// directly precede case label
q();
case 77: // warning: unannotated fall-through
r();
}
}];
}
def ARMInterruptDocs : Documentation {
let Category = DocCatFunction;
let Content = [{
Clang supports the GNU style ``__attribute__((interrupt("TYPE")))`` attribute on
ARM targets. This attribute may be attached to a function definition and
instructs the backend to generate appropriate function entry/exit code so that
it can be used directly as an interrupt service routine.
The parameter passed to the interrupt attribute is optional, but if
provided it must be a string literal with one of the following values: "IRQ",
"FIQ", "SWI", "ABORT", "UNDEF".
The semantics are as follows:
- If the function is AAPCS, Clang instructs the backend to realign the stack to
8 bytes on entry. This is a general requirement of the AAPCS at public
interfaces, but may not hold when an exception is taken. Doing this allows
other AAPCS functions to be called.
- If the CPU is M-class this is all that needs to be done since the architecture
itself is designed in such a way that functions obeying the normal AAPCS ABI
constraints are valid exception handlers.
- If the CPU is not M-class, the prologue and epilogue are modified to save all
non-banked registers that are used, so that upon return the user-mode state
will not be corrupted. Note that to avoid unnecessary overhead, only
general-purpose (integer) registers are saved in this way. If VFP operations
are needed, that state must be saved manually.
Specifically, interrupt kinds other than "FIQ" will save all core registers
except "lr" and "sp". "FIQ" interrupts will save r0-r7.
- If the CPU is not M-class, the return instruction is changed to one of the
canonical sequences permitted by the architecture for exception return. Where
possible the function itself will make the necessary "lr" adjustments so that
the "preferred return address" is selected.
Unfortunately the compiler is unable to make this guarantee for an "UNDEF"
handler, where the offset from "lr" to the preferred return address depends on
the execution state of the code which generated the exception. In this case
a sequence equivalent to "movs pc, lr" will be used.
}];
}
def DocCatConsumed : DocumentationCategory<"Consumed Annotation Checking"> {
let Content = [{
Clang supports additional attributes for checking basic resource management
properties, specifically for unique objects that have a single owning reference.
The following attributes are currently supported, although **the implementation
for these annotations is currently in development and are subject to change.**
}];
}
def SetTypestateDocs : Documentation {
let Category = DocCatConsumed;
let Content = [{
Annotate methods that transition an object into a new state with
``__attribute__((set_typestate(new_state)))``. The new new state must be
unconsumed, consumed, or unknown.
}];
}
def CallableWhenDocs : Documentation {
let Category = DocCatConsumed;
let Content = [{
Use ``__attribute__((callable_when(...)))`` to indicate what states a method
may be called in. Valid states are unconsumed, consumed, or unknown. Each
argument to this attribute must be a quoted string. E.g.:
``__attribute__((callable_when("unconsumed", "unknown")))``
}];
}
def TestTypestateDocs : Documentation {
let Category = DocCatConsumed;
let Content = [{
Use ``__attribute__((test_typestate(tested_state)))`` to indicate that a method
returns true if the object is in the specified state..
}];
}
def ParamTypestateDocs : Documentation {
let Category = DocCatConsumed;
let Content = [{
This attribute specifies expectations about function parameters. Calls to an
function with annotated parameters will issue a warning if the corresponding
argument isn't in the expected state. The attribute is also used to set the
initial state of the parameter when analyzing the function's body.
}];
}
def ReturnTypestateDocs : Documentation {
let Category = DocCatConsumed;
let Content = [{
The ``return_typestate`` attribute can be applied to functions or parameters.
When applied to a function the attribute specifies the state of the returned
value. The function's body is checked to ensure that it always returns a value
in the specified state. On the caller side, values returned by the annotated
function are initialized to the given state.
When applied to a function parameter it modifies the state of an argument after
a call to the function returns. The function's body is checked to ensure that
the parameter is in the expected state before returning.
}];
}
def ConsumableDocs : Documentation {
let Category = DocCatConsumed;
let Content = [{
Each ``class`` that uses any of the typestate annotations must first be marked
using the ``consumable`` attribute. Failure to do so will result in a warning.
This attribute accepts a single parameter that must be one of the following:
``unknown``, ``consumed``, or ``unconsumed``.
}];
}
def NoSanitizeAddressDocs : Documentation {
let Category = DocCatFunction;
// This function has multiple distinct spellings, and so it requires a custom
// heading to be specified. The most common spelling is sufficient.
let Heading = "no_sanitize_address (no_address_safety_analysis, gnu::no_address_safety_analysis, gnu::no_sanitize_address)";
let Content = [{
Use ``__attribute__((no_sanitize_address))`` on a function declaration to
specify that address safety instrumentation (e.g. AddressSanitizer) should
not be applied to that function.
}];
}
def NoSanitizeThreadDocs : Documentation {
let Category = DocCatFunction;
let Content = [{
Use ``__attribute__((no_sanitize_thread))`` on a function declaration to
specify that checks for data races on plain (non-atomic) memory accesses should
not be inserted by ThreadSanitizer. The function is still instrumented by the
tool to avoid false positives and provide meaningful stack traces.
}];
}
def NoSanitizeMemoryDocs : Documentation {
let Category = DocCatFunction;
let Content = [{
Use ``__attribute__((no_sanitize_memory))`` on a function declaration to
specify that checks for uninitialized memory should not be inserted
(e.g. by MemorySanitizer). The function may still be instrumented by the tool
to avoid false positives in other places.
}];
}
def DocCatTypeSafety : DocumentationCategory<"Type Safety Checking"> {
let Content = [{
Clang supports additional attributes to enable checking type safety properties
that can't be enforced by the C type system. Use cases include:
* MPI library implementations, where these attributes enable checking that
the buffer type matches the passed ``MPI_Datatype``;
* for HDF5 library there is a similar use case to MPI;
* checking types of variadic functions' arguments for functions like
``fcntl()`` and ``ioctl()``.
You can detect support for these attributes with ``__has_attribute()``. For
example:
.. code-block:: c++
#if defined(__has_attribute)
# if __has_attribute(argument_with_type_tag) && \
__has_attribute(pointer_with_type_tag) && \
__has_attribute(type_tag_for_datatype)
# define ATTR_MPI_PWT(buffer_idx, type_idx) __attribute__((pointer_with_type_tag(mpi,buffer_idx,type_idx)))
/* ... other macros ... */
# endif
#endif
#if !defined(ATTR_MPI_PWT)
# define ATTR_MPI_PWT(buffer_idx, type_idx)
#endif
int MPI_Send(void *buf, int count, MPI_Datatype datatype /*, other args omitted */)
ATTR_MPI_PWT(1,3);
}];
}
def ArgumentWithTypeTagDocs : Documentation {
let Category = DocCatTypeSafety;
let Heading = "argument_with_type_tag";
let Content = [{
Use ``__attribute__((argument_with_type_tag(arg_kind, arg_idx,
type_tag_idx)))`` on a function declaration to specify that the function
accepts a type tag that determines the type of some other argument.
``arg_kind`` is an identifier that should be used when annotating all
applicable type tags.
This attribute is primarily useful for checking arguments of variadic functions
(``pointer_with_type_tag`` can be used in most non-variadic cases).
For example:
.. code-block:: c++
int fcntl(int fd, int cmd, ...)
__attribute__(( argument_with_type_tag(fcntl,3,2) ));
}];
}
def PointerWithTypeTagDocs : Documentation {
let Category = DocCatTypeSafety;
let Heading = "pointer_with_type_tag";
let Content = [{
Use ``__attribute__((pointer_with_type_tag(ptr_kind, ptr_idx, type_tag_idx)))``
on a function declaration to specify that the function accepts a type tag that
determines the pointee type of some other pointer argument.
For example:
.. code-block:: c++
int MPI_Send(void *buf, int count, MPI_Datatype datatype /*, other args omitted */)
__attribute__(( pointer_with_type_tag(mpi,1,3) ));
}];
}
def TypeTagForDatatypeDocs : Documentation {
let Category = DocCatTypeSafety;
let Content = [{
Clang supports annotating type tags of two forms.
* **Type tag that is an expression containing a reference to some declared
identifier.** Use ``__attribute__((type_tag_for_datatype(kind, type)))`` on a
declaration with that identifier:
.. code-block:: c++
extern struct mpi_datatype mpi_datatype_int
__attribute__(( type_tag_for_datatype(mpi,int) ));
#define MPI_INT ((MPI_Datatype) &mpi_datatype_int)
* **Type tag that is an integral literal.** Introduce a ``static const``
variable with a corresponding initializer value and attach
``__attribute__((type_tag_for_datatype(kind, type)))`` on that declaration,
for example:
.. code-block:: c++
#define MPI_INT ((MPI_Datatype) 42)
static const MPI_Datatype mpi_datatype_int
__attribute__(( type_tag_for_datatype(mpi,int) )) = 42
The attribute also accepts an optional third argument that determines how the
expression is compared to the type tag. There are two supported flags:
* ``layout_compatible`` will cause types to be compared according to
layout-compatibility rules (C++11 [class.mem] p 17, 18). This is
implemented to support annotating types like ``MPI_DOUBLE_INT``.
For example:
.. code-block:: c++
/* In mpi.h */
struct internal_mpi_double_int { double d; int i; };
extern struct mpi_datatype mpi_datatype_double_int
__attribute__(( type_tag_for_datatype(mpi, struct internal_mpi_double_int, layout_compatible) ));
#define MPI_DOUBLE_INT ((MPI_Datatype) &mpi_datatype_double_int)
/* In user code */
struct my_pair { double a; int b; };
struct my_pair *buffer;
MPI_Send(buffer, 1, MPI_DOUBLE_INT /*, ... */); // no warning
struct my_int_pair { int a; int b; }
struct my_int_pair *buffer2;
MPI_Send(buffer2, 1, MPI_DOUBLE_INT /*, ... */); // warning: actual buffer element
// type 'struct my_int_pair'
// doesn't match specified MPI_Datatype
* ``must_be_null`` specifies that the expression should be a null pointer
constant, for example:
.. code-block:: c++
/* In mpi.h */
extern struct mpi_datatype mpi_datatype_null
__attribute__(( type_tag_for_datatype(mpi, void, must_be_null) ));
#define MPI_DATATYPE_NULL ((MPI_Datatype) &mpi_datatype_null)
/* In user code */
MPI_Send(buffer, 1, MPI_DATATYPE_NULL /*, ... */); // warning: MPI_DATATYPE_NULL
// was specified but buffer
// is not a null pointer
}];
}
def FormatDocs : Documentation {
let Category = DocCatFunction;
let Content = [{
Clang supports the ``format`` attribute, which indicates that the function
accepts a ``printf`` or ``scanf``-like format string and corresponding
arguments or a ``va_list`` that contains these arguments.
Please see `GCC documentation about format attribute
<http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_ to find details
about attribute syntax.
Clang implements two kinds of checks with this attribute.
#. Clang checks that the function with the ``format`` attribute is called with
a format string that uses format specifiers that are allowed, and that
arguments match the format string. This is the ``-Wformat`` warning, it is
on by default.
#. Clang checks that the format string argument is a literal string. This is
the ``-Wformat-nonliteral`` warning, it is off by default.
Clang implements this mostly the same way as GCC, but there is a difference
for functions that accept a ``va_list`` argument (for example, ``vprintf``).
GCC does not emit ``-Wformat-nonliteral`` warning for calls to such
fuctions. Clang does not warn if the format string comes from a function
parameter, where the function is annotated with a compatible attribute,
otherwise it warns. For example:
.. code-block:: c
__attribute__((__format__ (__scanf__, 1, 3)))
void foo(const char* s, char *buf, ...) {
va_list ap;
va_start(ap, buf);
vprintf(s, ap); // warning: format string is not a string literal
}
In this case we warn because ``s`` contains a format string for a
``scanf``-like function, but it is passed to a ``printf``-like function.
If the attribute is removed, clang still warns, because the format string is
not a string literal.
Another example:
.. code-block:: c
__attribute__((__format__ (__printf__, 1, 3)))
void foo(const char* s, char *buf, ...) {
va_list ap;
va_start(ap, buf);
vprintf(s, ap); // warning
}
In this case Clang does not warn because the format string ``s`` and
the corresponding arguments are annotated. If the arguments are
incorrect, the caller of ``foo`` will receive a warning.
}];
}
def MSInheritanceDocs : Documentation {
let Category = DocCatType;
let Heading = "__single_inhertiance, __multiple_inheritance, __virtual_inheritance";
let Content = [{
This collection of keywords is enabled under ``-fms-extensions`` and controls
the pointer-to-member representation used on ``*-*-win32`` targets.
The ``*-*-win32`` targets utilize a pointer-to-member representation which
varies in size and alignment depending on the definition of the underlying
class.
However, this is problematic when a forward declaration is only available and
no definition has been made yet. In such cases, Clang is forced to utilize the
most general representation that is available to it.
These keywords make it possible to use a pointer-to-member representation other
than the most general one regardless of whether or not the definition will ever
be present in the current translation unit.
This family of keywords belong between the ``class-key`` and ``class-name``:
.. code-block:: c++
struct __single_inheritance S;
int S::*i;
struct S {};
This keyword can be applied to class templates but only has an effect when used
on full specializations:
.. code-block:: c++
template <typename T, typename U> struct __single_inheritance A; // warning: inheritance model ignored on primary template
template <typename T> struct __multiple_inheritance A<T, T>; // warning: inheritance model ignored on partial specialization
template <> struct __single_inheritance A<int, float>;
Note that choosing an inheritance model less general than strictly necessary is
an error:
.. code-block:: c++
struct __multiple_inheritance S; // error: inheritance model does not match definition
int S::*i;
struct S {};
}];
}

View File

@ -50,6 +50,7 @@
// L -> long (e.g. Li for 'long int')
// LL -> long long
// LLL -> __int128_t (e.g. LLLi)
// W -> int64_t
// S -> signed
// U -> unsigned
// I -> Required to constant fold to an integer constant expression.
@ -679,6 +680,10 @@ LANGBUILTIN(_alloca, "v*z", "n", ALL_MS_LANGUAGES)
LANGBUILTIN(__assume, "vb", "n", ALL_MS_LANGUAGES)
LANGBUILTIN(__noop, "v.", "n", ALL_MS_LANGUAGES)
LANGBUILTIN(__debugbreak, "v", "n", ALL_MS_LANGUAGES)
LANGBUILTIN(_InterlockedCompareExchange, "LiLiD*LiLi", "n", ALL_MS_LANGUAGES)
LANGBUILTIN(_InterlockedIncrement, "LiLiD*", "n", ALL_MS_LANGUAGES)
LANGBUILTIN(_InterlockedDecrement, "LiLiD*", "n", ALL_MS_LANGUAGES)
LANGBUILTIN(_InterlockedExchangeAdd, "LiLiD*Li", "n", ALL_MS_LANGUAGES)
// C99 library functions
// C99 stdlib.h

View File

@ -59,6 +59,7 @@ BUILTIN(__builtin_ia32_pswapdsi, "V2iV2i", "nc")
// All MMX instructions will be generated via builtins. Any MMX vector
// types (<1 x i64>, <2 x i32>, etc.) that aren't used by these builtins will be
// expanded by the back-end.
BUILTIN(_mm_prefetch, "vcC*i", "nc")
BUILTIN(__builtin_ia32_emms, "v", "")
BUILTIN(__builtin_ia32_paddb, "V8cV8cV8c", "")
BUILTIN(__builtin_ia32_paddw, "V4sV4sV4s", "")

View File

@ -142,6 +142,7 @@ public:
enum Level {
Ignored = DiagnosticIDs::Ignored,
Note = DiagnosticIDs::Note,
Remark = DiagnosticIDs::Remark,
Warning = DiagnosticIDs::Warning,
Error = DiagnosticIDs::Error,
Fatal = DiagnosticIDs::Fatal

View File

@ -15,6 +15,7 @@
// Define the diagnostic mappings.
class DiagMapping;
def MAP_IGNORE : DiagMapping;
def MAP_REMARK : DiagMapping;
def MAP_WARNING : DiagMapping;
def MAP_ERROR : DiagMapping;
def MAP_FATAL : DiagMapping;
@ -22,6 +23,7 @@ def MAP_FATAL : DiagMapping;
// Define the diagnostic classes.
class DiagClass;
def CLASS_NOTE : DiagClass;
def CLASS_REMARK : DiagClass;
def CLASS_WARNING : DiagClass;
def CLASS_EXTENSION : DiagClass;
def CLASS_ERROR : DiagClass;
@ -84,6 +86,7 @@ class AccessControl {
// FIXME: ExtWarn and Extension should also be SFINAEFailure by default.
class Error<string str> : Diagnostic<str, CLASS_ERROR, MAP_ERROR>, SFINAEFailure;
class Warning<string str> : Diagnostic<str, CLASS_WARNING, MAP_WARNING>;
class Remark<string str> : Diagnostic<str, CLASS_REMARK, MAP_IGNORE>;
class Extension<string str> : Diagnostic<str, CLASS_EXTENSION, MAP_IGNORE>;
class ExtWarn<string str> : Diagnostic<str, CLASS_EXTENSION, MAP_WARNING>;
class Note<string str> : Diagnostic<str, CLASS_NOTE, MAP_FATAL/*ignored*/>;

View File

@ -166,4 +166,11 @@ def err_analyzer_config_no_value : Error<
"analyzer-config option '%0' has a key but no value">;
def err_analyzer_config_multiple_values : Error<
"analyzer-config option '%0' should contain only one '='">;
def err_drv_modules_validate_once_requires_timestamp : Error<
"option '-fmodules-validate-once-per-build-session' requires "
"'-fbuild-session-timestamp=<seconds since Epoch>'">;
def warn_drv_invoking_fallback : Warning<"falling back to %0">,
InGroup<DiagGroup<"fallback">>;
}

View File

@ -29,6 +29,7 @@ def note_fe_backend_frame_larger_than: Note<"%0">, CatBackend;
def warn_fe_backend_plugin: Warning<"%0">, CatBackend, InGroup<BackendPlugin>;
def err_fe_backend_plugin: Error<"%0">, CatBackend;
def remark_fe_backend_plugin: Remark<"%0">, CatBackend, InGroup<RemarkBackendPlugin>;
def note_fe_backend_plugin: Note<"%0">, CatBackend;
def err_fe_invalid_code_complete_file : Error<
@ -158,4 +159,9 @@ def warn_module_config_macro_undef : Warning<
InGroup<ConfigMacros>;
def note_module_def_undef_here : Note<
"macro was %select{defined|#undef'd}0 here">;
def err_missing_vfs_overlay_file : Error<
"virtual filesystem overlay file '%0' not found">, DefaultFatal;
def err_invalid_vfs_overlay : Error<
"invalid virtual filesystem overlay file '%0'">, DefaultFatal;
}

View File

@ -18,6 +18,7 @@ def Implicit : DiagGroup<"implicit", [
// Empty DiagGroups are recognized by clang but ignored.
def : DiagGroup<"abi">;
def AbsoluteValue : DiagGroup<"absolute-value">;
def : DiagGroup<"address">;
def AddressOfTemporary : DiagGroup<"address-of-temporary">;
def : DiagGroup<"aggregate-return">;
@ -174,6 +175,7 @@ def InfiniteRecursion : DiagGroup<"infinite-recursion">;
def GNUImaginaryConstant : DiagGroup<"gnu-imaginary-constant">;
def IgnoredQualifiers : DiagGroup<"ignored-qualifiers">;
def : DiagGroup<"import">;
def IncompatibleMSStruct : DiagGroup<"incompatible-ms-struct">;
def IncompatiblePointerTypesDiscardsQualifiers
: DiagGroup<"incompatible-pointer-types-discards-qualifiers">;
def IncompatiblePointerTypes
@ -217,6 +219,7 @@ def NullDereference : DiagGroup<"null-dereference">;
def InitializerOverrides : DiagGroup<"initializer-overrides">;
def NonNull : DiagGroup<"nonnull">;
def NonPODVarargs : DiagGroup<"non-pod-varargs">;
def ClassVarargs : DiagGroup<"class-varargs", [NonPODVarargs]>;
def : DiagGroup<"nonportable-cfstrings">;
def NonVirtualDtor : DiagGroup<"non-virtual-dtor">;
def OveralignedType : DiagGroup<"over-aligned">;
@ -284,8 +287,10 @@ def StringPlusInt : DiagGroup<"string-plus-int">;
def StringPlusChar : DiagGroup<"string-plus-char">;
def StrncatSize : DiagGroup<"strncat-size">;
def TautologicalOutOfRangeCompare : DiagGroup<"tautological-constant-out-of-range-compare">;
def TautologicalPointerCompare : DiagGroup<"tautological-pointer-compare">;
def TautologicalCompare : DiagGroup<"tautological-compare",
[TautologicalOutOfRangeCompare]>;
[TautologicalOutOfRangeCompare,
TautologicalPointerCompare]>;
def HeaderHygiene : DiagGroup<"header-hygiene">;
def DuplicateDeclSpecifier : DiagGroup<"duplicate-decl-specifier">;
def CompareDistinctPointerType : DiagGroup<"compare-distinct-pointer-types">;
@ -471,7 +476,7 @@ def Format : DiagGroup<"format",
[FormatExtraArgs, FormatZeroLength, NonNull,
FormatSecurity, FormatY2K, FormatInvalidSpecifier]>,
DiagCategory<"Format String Issue">;
def FormatNonLiteral : DiagGroup<"format-nonliteral", [FormatSecurity]>;
def FormatNonLiteral : DiagGroup<"format-nonliteral">;
def Format2 : DiagGroup<"format=2",
[FormatNonLiteral, FormatSecurity, FormatY2K]>;
@ -632,3 +637,4 @@ def SourceUsesOpenMP : DiagGroup<"source-uses-openmp">;
def BackendInlineAsm : DiagGroup<"inline-asm">;
def BackendFrameLargerThan : DiagGroup<"frame-larger-than">;
def BackendPlugin : DiagGroup<"backend-plugin">;
def RemarkBackendPlugin : DiagGroup<"remark-backend-plugin">;

View File

@ -56,16 +56,17 @@ namespace clang {
};
/// Enum values that allow the client to map NOTEs, WARNINGs, and EXTENSIONs
/// to either MAP_IGNORE (nothing), MAP_WARNING (emit a warning), MAP_ERROR
/// (emit as an error). It allows clients to map errors to
/// MAP_ERROR/MAP_DEFAULT or MAP_FATAL (stop emitting diagnostics after this
/// one).
/// to either MAP_IGNORE (nothing), MAP_REMARK (emit a remark), MAP_WARNING
/// (emit a warning), MAP_ERROR (emit as an error). It allows clients to
/// map errors to MAP_ERROR/MAP_DEFAULT or MAP_FATAL (stop emitting
/// diagnostics after this one).
enum Mapping {
// NOTE: 0 means "uncomputed".
MAP_IGNORE = 1, ///< Map this diagnostic to nothing, ignore it.
MAP_WARNING = 2, ///< Map this diagnostic to a warning.
MAP_ERROR = 3, ///< Map this diagnostic to an error.
MAP_FATAL = 4 ///< Map this diagnostic to a fatal error.
MAP_REMARK = 2, ///< Map this diagnostic to a remark.
MAP_WARNING = 3, ///< Map this diagnostic to a warning.
MAP_ERROR = 4, ///< Map this diagnostic to an error.
MAP_FATAL = 5 ///< Map this diagnostic to a fatal error.
};
}
@ -113,7 +114,7 @@ class DiagnosticIDs : public RefCountedBase<DiagnosticIDs> {
public:
/// \brief The level of the diagnostic, after it has been through mapping.
enum Level {
Ignored, Note, Warning, Error, Fatal
Ignored, Note, Remark, Warning, Error, Fatal
};
private:

View File

@ -494,7 +494,7 @@ def err_too_few_args_in_macro_invoc : Error<
"too few arguments provided to function-like macro invocation">;
def err_pp_bad_paste : Error<
"pasting formed '%0', an invalid preprocessing token">;
def err_pp_bad_paste_ms : Warning<
def ext_pp_bad_paste_ms : ExtWarn<
"pasting formed '%0', an invalid preprocessing token">, DefaultError,
InGroup<DiagGroup<"invalid-token-paste">>;
def err_pp_operator_used_as_macro_name : Error<

View File

@ -770,6 +770,9 @@ def warn_pragma_expected_rparen : Warning<
"missing ')' after '#pragma %0' - ignoring">, InGroup<IgnoredPragmas>;
def warn_pragma_expected_identifier : Warning<
"expected identifier in '#pragma %0' - ignored">, InGroup<IgnoredPragmas>;
def warn_pragma_expected_integer : Warning<
"expected integer between %0 and %1 inclusive in '#pragma %2' - ignored">,
InGroup<IgnoredPragmas>;
def warn_pragma_ms_struct : Warning<
"incorrect use of '#pragma ms_struct on|off' - ignored">,
InGroup<IgnoredPragmas>;
@ -789,8 +792,8 @@ def warn_pragma_align_invalid_option : Warning<
"invalid alignment option in '#pragma %select{align|options align}0' - ignored">,
InGroup<IgnoredPragmas>;
// - #pragma pack
def warn_pragma_pack_invalid_action : Warning<
"unknown action for '#pragma pack' - ignored">,
def warn_pragma_invalid_action : Warning<
"unknown action for '#pragma %0' - ignored">,
InGroup<IgnoredPragmas>;
def warn_pragma_pack_malformed : Warning<
"expected integer or identifier in '#pragma pack' - ignored">,

View File

@ -30,6 +30,21 @@ def warn_duplicate_enum_values : Warning<
"been assigned">, InGroup<DiagGroup<"duplicate-enum">>, DefaultIgnore;
def note_duplicate_element : Note<"element %0 also has value %1">;
// Absolute value functions
def warn_unsigned_abs : Warning<
"taking the absolute value of unsigned type %0 has no effect">,
InGroup<AbsoluteValue>;
def note_remove_abs : Note<
"remove the call to %0 since unsigned values cannot be negative">;
def warn_abs_too_small : Warning<
"absolute value function %0 given an argument of type %1 but has parameter "
"of type %2 which may cause truncation of value">, InGroup<AbsoluteValue>;
def warn_wrong_absolute_value_type : Warning<
"using %select{integer|floating point|complex}1 absolute value function %0 "
"when argument is of %select{integer|floating point|complex}2 type">,
InGroup<AbsoluteValue>;
def note_replace_abs_function : Note<"use function '%0' instead">;
def warn_infinite_recursive_function : Warning<
"all paths through this function will call itself">,
InGroup<InfiniteRecursion>, DefaultIgnore;
@ -222,7 +237,10 @@ def note_function_suggestion : Note<"did you mean %0?">;
def err_ellipsis_first_arg : Error<
"ISO C requires a named argument before '...'">;
def err_declarator_need_ident : Error<"declarator requires an identifier">;
def err_bad_language : Error<"unknown linkage language">;
def err_language_linkage_spec_unknown : Error<"unknown linkage language">;
def err_language_linkage_spec_not_ascii : Error<
"string literal in language linkage specifier cannot have an "
"encoding-prefix">;
def warn_use_out_of_scope_declaration : Warning<
"use of out-of-scope declaration of %0">;
def err_inline_non_function : Error<
@ -480,10 +498,12 @@ def warn_pragma_pack_invalid_alignment : Warning<
def warn_pragma_pack_show : Warning<"value of #pragma pack(show) == %0">;
def warn_pragma_pack_pop_identifer_and_alignment : Warning<
"specifying both a name and alignment to 'pop' is undefined">;
def warn_pragma_pack_pop_failed : Warning<"#pragma pack(pop, ...) failed: %0">,
InGroup<IgnoredPragmas>;
def warn_pragma_ms_struct_failed : Warning<"#pramga ms_struct can not be used with dynamic classes or structures">,
def warn_pragma_pop_failed : Warning<"#pragma %0(pop, ...) failed: %1">,
InGroup<IgnoredPragmas>;
def warn_cxx_ms_struct :
Warning<"ms_struct may not produce MSVC-compatible layouts for classes "
"with base classes or virtual functions">,
DefaultError, InGroup<IncompatibleMSStruct>;
def warn_pragma_unused_undeclared_var : Warning<
"undeclared variable %0 used as an argument for '#pragma unused'">,
@ -1527,7 +1547,10 @@ def err_auto_var_init_multiple_expressions : Error<
def err_auto_new_ctor_multiple_expressions : Error<
"new expression for type %0 contains multiple constructor arguments">;
def err_auto_missing_trailing_return : Error<
"'auto' return without trailing return type">;
"'auto' return without trailing return type; deduced return types are a "
"C++1y extension">;
def err_deduced_return_type : Error<
"deduced return types are a C++1y extension">;
def err_trailing_return_without_auto : Error<
"function with trailing return type must specify return type 'auto', not %0">;
def err_trailing_return_in_parens : Error<
@ -1982,8 +2005,8 @@ def error_cannot_find_suitable_accessor : Error<
def err_attribute_aligned_not_power_of_two : Error<
"requested alignment is not a power of 2">;
def err_attribute_aligned_greater_than_8192 : Error<
"requested alignment must be 8192 bytes or smaller">;
def err_attribute_aligned_too_great : Error<
"requested alignment must be %0 bytes or smaller">;
def warn_redeclaration_without_attribute_prev_attribute_ignored : Warning<
"%0 redeclared without %1 attribute: previous %1 ignored">;
def warn_attribute_ignored : Warning<"%0 attribute ignored">,
@ -2034,6 +2057,8 @@ def err_attribute_selectany_non_extern_data : Error<
def warn_attribute_invalid_on_definition : Warning<
"'%0' attribute cannot be specified on a definition">,
InGroup<IgnoredAttributes>;
def err_attribute_dllimport_data_definition : Error<
"definition of dllimport data">;
def err_attribute_weakref_not_static : Error<
"weakref declaration must have internal linkage">;
def err_attribute_weakref_not_global_context : Error<
@ -2133,7 +2158,7 @@ def warn_thread_attribute_ignored : Warning<
InGroup<ThreadSafetyAttributes>, DefaultIgnore;
def warn_thread_attribute_argument_not_lockable : Warning<
"%0 attribute requires arguments whose type is annotated "
"with 'lockable' attribute; type here is %1">,
"with 'capability' attribute; type here is %1">,
InGroup<ThreadSafetyAttributes>, DefaultIgnore;
def warn_thread_attribute_argument_not_class : Warning<
"%0 attribute requires arguments that are class type or point to"
@ -2141,7 +2166,7 @@ def warn_thread_attribute_argument_not_class : Warning<
InGroup<ThreadSafetyAttributes>, DefaultIgnore;
def warn_thread_attribute_decl_not_lockable : Warning<
"%0 attribute can only be applied in a context annotated "
"with 'lockable' attribute">,
"with 'capability(\"mutex\")' attribute">,
InGroup<ThreadSafetyAttributes>, DefaultIgnore;
def warn_thread_attribute_decl_not_pointer : Warning<
"%0 only applies to pointer types; type here is %1">,
@ -2301,12 +2326,19 @@ def warn_impcast_null_pointer_to_integer : Warning<
def warn_impcast_floating_point_to_bool : Warning<
"implicit conversion turns floating-point number into bool: %0 to %1">,
InGroup<ImplicitConversionFloatingPointToBool>;
def warn_impcast_function_to_bool : Warning<
"address of function %q0 will always evaluate to 'true'">,
def warn_impcast_pointer_to_bool : Warning<
"address of%select{| function| array}0 '%1' will always evaluate to "
"'true'">,
InGroup<BoolConversion>;
def note_function_to_bool_silence : Note<
def warn_null_pointer_compare : Warning<
"comparison of %select{address of|function|array}0 '%1' %select{not |}2"
"equal to a null pointer is always %select{true|false}2">,
InGroup<TautologicalPointerCompare>;
def note_function_warning_silence : Note<
"prefix with the address-of operator to silence this warning">;
def note_function_to_bool_call : Note<
def note_function_to_function_call : Note<
"suffix with parentheses to turn this into a function call">;
def warn_impcast_objective_c_literal_to_bool : Warning<
"implicit boolean conversion of Objective-C object literal always "
@ -2493,7 +2525,10 @@ def err_objc_bridged_related_invalid_class_name : Error<
def err_objc_bridged_related_known_method : Error<
"%0 must be explicitly converted to %1; use %select{%objcclass2|%objcinstance2}3 "
"method for this conversion">;
def err_objc_attr_protocol_requires_definition : Error<
"attribute %0 can only be applied to @protocol definitions, not forward declarations">;
// Function Parameter Semantic Analysis.
def err_param_with_void_type : Error<"argument may not have 'void' type">;
def err_void_only_param : Error<
@ -2504,8 +2539,6 @@ def err_ident_list_in_fn_declaration : Error<
"a parameter list without types is only allowed in a function definition">;
def ext_param_not_declared : Extension<
"parameter %0 was not declared, defaulting to type 'int'">;
def err_param_typedef_of_void : Error<
"empty parameter list defined with a %select{typedef|type alias}0 of 'void' not allowed%select{ in C++|}0">;
def err_param_default_argument : Error<
"C does not support default arguments">;
def err_param_default_argument_redefinition : Error<
@ -3213,8 +3246,6 @@ def note_dependent_non_type_default_arg_in_partial_spec : Note<
def err_dependent_typed_non_type_arg_in_partial_spec : Error<
"non-type template argument specializes a template parameter with "
"dependent type %0">;
def note_dependent_typed_non_type_default_arg_in_partial_spec : Note<
"template parameter is declared here">;
def err_partial_spec_args_match_primary_template : Error<
"%select{class|variable}0 template partial specialization does not "
"specialize any template argument; to %select{declare|define}1 the "
@ -3783,6 +3814,9 @@ def warn_typecheck_negative_array_new_size : Warning<"array size is negative">,
InGroup<BadArrayNewLength>;
def warn_typecheck_function_qualifiers : Warning<
"qualifier on function type %0 has unspecified behavior">;
def warn_typecheck_reference_qualifiers : Warning<
"'%0' qualifier on reference type %1 has no effect">,
InGroup<IgnoredQualifiers>;
def err_typecheck_invalid_restrict_not_pointer : Error<
"restrict requires a pointer or reference (%0 is invalid)">;
def err_typecheck_invalid_restrict_not_pointer_noarg : Error<
@ -5691,6 +5725,11 @@ def warn_cxx98_compat_pass_non_pod_arg_to_vararg : Warning<
"passing object of trivial but non-POD type %0 through variadic"
" %select{function|block|method|constructor}1 is incompatible with C++98">,
InGroup<CXX98Compat>, DefaultIgnore;
def warn_pass_class_arg_to_vararg : Warning<
"passing object of class type %0 through variadic "
"%select{function|block|method|constructor}1"
"%select{|; did you mean to call '%3'?}2">,
InGroup<ClassVarargs>, DefaultIgnore;
def err_cannot_pass_to_vararg : Error<
"cannot pass %select{expression of type %1|initializer list}0 to variadic "
"%select{function|block|method|constructor}2">;
@ -5839,6 +5878,12 @@ def err_invalid_conversion_between_vector_and_integer : Error<
"invalid conversion between vector type %0 and integer type %1 "
"of different size">;
def err_opencl_function_pointer_variable : Error<
"pointers to functions are not allowed">;
def err_opencl_taking_function_address : Error<
"taking address of function is not allowed">;
def err_invalid_conversion_between_vector_and_scalar : Error<
"invalid conversion between vector type %0 and scalar type %1">;
@ -6212,6 +6257,8 @@ def warn_format_string_is_wide_literal : Warning<
"format string should not be a wide string">, InGroup<Format>;
def warn_printf_format_string_contains_null_char : Warning<
"format string contains '\\0' within the string body">, InGroup<Format>;
def warn_printf_format_string_not_null_terminated : Warning<
"format string is not null-terminated">, InGroup<Format>;
def warn_printf_asterisk_missing_arg : Warning<
"'%select{*|.*}0' specified field %select{width|precision}0 is missing a matching 'int' argument">,
InGroup<Format>;
@ -6795,24 +6842,26 @@ def err_omp_private_incomplete_type : Error<
"a private variable with incomplete type %0">;
def err_omp_firstprivate_incomplete_type : Error<
"a firstprivate variable with incomplete type %0">;
def err_omp_unexpected_clause_value : Error <
def err_omp_unexpected_clause_value : Error<
"expected %0 in OpenMP clause '%1'">;
def err_omp_expected_var_name : Error <
def err_omp_expected_var_name : Error<
"expected variable name">;
def err_omp_required_method : Error <
def err_omp_required_method : Error<
"%0 variable must have an accessible, unambiguous %select{default constructor|copy constructor|copy assignment operator|'%2'|destructor}1">;
def err_omp_clause_ref_type_arg : Error<
"arguments of OpenMP clause '%0' cannot be of reference type %1">;
def err_omp_threadprivate_incomplete_type : Error<
"threadprivate variable with incomplete type %0">;
def err_omp_no_dsa_for_variable : Error <
def err_omp_no_dsa_for_variable : Error<
"variable %0 must have explicitly specified data sharing attributes">;
def err_omp_wrong_dsa : Error<
"%0 variable cannot be %1">;
def note_omp_explicit_dsa : Note <
def note_omp_explicit_dsa : Note<
"defined as %0">;
def note_omp_predetermined_dsa : Note <
def note_omp_predetermined_dsa : Note<
"predetermined as %0">;
def err_omp_not_for : Error<
"statement after '#pragma omp %0' must be a for loop">;
} // end of OpenMP category
let CategoryName = "Related Result Type Issue" in {

View File

@ -8,6 +8,7 @@
//===----------------------------------------------------------------------===//
let Component = "Serialization" in {
let CategoryName = "AST Deserialization Issue" in {
def err_fe_unable_to_read_pch_file : Error<
"unable to read PCH file %0: '%1'">;
@ -78,4 +79,6 @@ def note_module_odr_violation_no_possible_decls : Note<
def note_module_odr_violation_possible_decl : Note<
"declaration of %0 does not match">;
}
} // let CategoryName
} // let Component

View File

@ -17,6 +17,7 @@
#include "clang/Basic/FileSystemOptions.h"
#include "clang/Basic/LLVM.h"
#include "clang/Basic/VirtualFileSystem.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/IntrusiveRefCntPtr.h"
#include "llvm/ADT/OwningPtr.h"
@ -24,9 +25,9 @@
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Allocator.h"
#include "llvm/Support/FileSystem.h"
// FIXME: Enhance libsystem to support inode and other fields in stat.
#include <sys/types.h>
#include <map>
#ifdef _MSC_VER
typedef unsigned short mode_t;
@ -55,10 +56,10 @@ public:
/// \brief Cached information about one file (either on disk
/// or in the virtual file system).
///
/// If the 'FD' member is valid, then this FileEntry has an open file
/// If the 'File' member is valid, then this FileEntry has an open file
/// descriptor for the file.
class FileEntry {
const char *Name; // Name of the file.
std::string Name; // Name of the file.
off_t Size; // File size in bytes.
time_t ModTime; // Modification time of file.
const DirectoryEntry *Dir; // Directory file lives in.
@ -66,33 +67,34 @@ class FileEntry {
llvm::sys::fs::UniqueID UniqueID;
bool IsNamedPipe;
bool InPCH;
bool IsValid; // Is this \c FileEntry initialized and valid?
/// FD - The file descriptor for the file entry if it is opened and owned
/// by the FileEntry. If not, this is set to -1.
mutable int FD;
/// \brief The open file, if it is owned by the \p FileEntry.
mutable OwningPtr<vfs::File> File;
friend class FileManager;
void closeFile() const {
File.reset(0); // rely on destructor to close File
}
void operator=(const FileEntry &) LLVM_DELETED_FUNCTION;
public:
FileEntry(llvm::sys::fs::UniqueID UniqueID, bool IsNamedPipe, bool InPCH)
: Name(0), UniqueID(UniqueID), IsNamedPipe(IsNamedPipe), InPCH(InPCH),
FD(-1) {}
// Add a default constructor for use with llvm::StringMap
FileEntry()
: Name(0), UniqueID(0, 0), IsNamedPipe(false), InPCH(false), FD(-1) {}
: UniqueID(0, 0), IsNamedPipe(false), InPCH(false), IsValid(false)
{}
FileEntry(const FileEntry &FE) {
memcpy(this, &FE, sizeof(FE));
assert(FD == -1 && "Cannot copy a file-owning FileEntry");
// FIXME: this is here to allow putting FileEntry in std::map. Once we have
// emplace, we shouldn't need a copy constructor anymore.
/// Intentionally does not copy fields that are not set in an uninitialized
/// \c FileEntry.
FileEntry(const FileEntry &FE) : UniqueID(FE.UniqueID),
IsNamedPipe(FE.IsNamedPipe), InPCH(FE.InPCH), IsValid(FE.IsValid) {
assert(!isValid() && "Cannot copy an initialized FileEntry");
}
void operator=(const FileEntry &FE) {
memcpy(this, &FE, sizeof(FE));
assert(FD == -1 && "Cannot assign a file-owning FileEntry");
}
~FileEntry();
const char *getName() const { return Name; }
const char *getName() const { return Name.c_str(); }
bool isValid() const { return IsValid; }
off_t getSize() const { return Size; }
unsigned getUID() const { return UID; }
const llvm::sys::fs::UniqueID &getUniqueID() const { return UniqueID; }
@ -119,16 +121,14 @@ struct FileData;
/// as a single file.
///
class FileManager : public RefCountedBase<FileManager> {
IntrusiveRefCntPtr<vfs::FileSystem> FS;
FileSystemOptions FileSystemOpts;
class UniqueDirContainer;
class UniqueFileContainer;
/// \brief Cache for existing real directories.
UniqueDirContainer &UniqueRealDirs;
std::map<llvm::sys::fs::UniqueID, DirectoryEntry> UniqueRealDirs;
/// \brief Cache for existing real files.
UniqueFileContainer &UniqueRealFiles;
std::map<llvm::sys::fs::UniqueID, FileEntry> UniqueRealFiles;
/// \brief The virtual directories that we have allocated.
///
@ -172,14 +172,15 @@ class FileManager : public RefCountedBase<FileManager> {
OwningPtr<FileSystemStatCache> StatCache;
bool getStatValue(const char *Path, FileData &Data, bool isFile,
int *FileDescriptor);
vfs::File **F);
/// Add all ancestors of the given path (pointing to either a file
/// or a directory) as virtual directories.
void addAncestorsAsVirtualDirs(StringRef Path);
public:
FileManager(const FileSystemOptions &FileSystemOpts);
FileManager(const FileSystemOptions &FileSystemOpts,
IntrusiveRefCntPtr<vfs::FileSystem> FS = 0);
~FileManager();
/// \brief Installs the provided FileSystemStatCache object within
@ -226,6 +227,10 @@ public:
/// \brief Returns the current file system options
const FileSystemOptions &getFileSystemOptions() { return FileSystemOpts; }
IntrusiveRefCntPtr<vfs::FileSystem> getVirtualFileSystem() const {
return FS;
}
/// \brief Retrieve a file entry for a "virtual" file that acts as
/// if there were a file with the given name on disk.
///
@ -248,7 +253,7 @@ public:
///
/// \returns false on success, true on error.
bool getNoncachedStatValue(StringRef Path,
llvm::sys::fs::file_status &Result);
vfs::Status &Result);
/// \brief Remove the real file \p Entry from the cache.
void invalidateCache(const FileEntry *Entry);

View File

@ -24,7 +24,14 @@
namespace clang {
namespace vfs {
class File;
class FileSystem;
}
// FIXME: should probably replace this with vfs::Status
struct FileData {
std::string Name;
uint64_t Size;
time_t ModTime;
llvm::sys::fs::UniqueID UniqueID;
@ -57,10 +64,11 @@ public:
/// If isFile is true, then this lookup should only return success for files
/// (not directories). If it is false this lookup should only return
/// success for directories (not files). On a successful file lookup, the
/// implementation can optionally fill in FileDescriptor with a valid
/// descriptor and the client guarantees that it will close it.
/// implementation can optionally fill in \p F with a valid \p File object and
/// the client guarantees that it will close it.
static bool get(const char *Path, FileData &Data, bool isFile,
int *FileDescriptor, FileSystemStatCache *Cache);
vfs::File **F, FileSystemStatCache *Cache,
vfs::FileSystem &FS);
/// \brief Sets the next stat call cache in the chain of stat caches.
/// Takes ownership of the given stat cache.
@ -78,17 +86,16 @@ public:
protected:
virtual LookupResult getStat(const char *Path, FileData &Data, bool isFile,
int *FileDescriptor) = 0;
vfs::File **F, vfs::FileSystem &FS) = 0;
LookupResult statChained(const char *Path, FileData &Data, bool isFile,
int *FileDescriptor) {
vfs::File **F, vfs::FileSystem &FS) {
if (FileSystemStatCache *Next = getNextStatCache())
return Next->getStat(Path, Data, isFile, FileDescriptor);
return Next->getStat(Path, Data, isFile, F, FS);
// If we hit the end of the list of stat caches to try, just compute and
// return it without a cache.
return get(Path, Data, isFile, FileDescriptor, 0) ? CacheMissing
: CacheExists;
return get(Path, Data, isFile, F, 0, FS) ? CacheMissing : CacheExists;
}
};
@ -107,7 +114,7 @@ public:
iterator end() const { return StatCalls.end(); }
virtual LookupResult getStat(const char *Path, FileData &Data, bool isFile,
int *FileDescriptor);
vfs::File **F, vfs::FileSystem &FS);
};
} // end namespace clang

View File

@ -113,6 +113,7 @@ BENIGN_LANGOPT(ObjCGCBitmapPrint , 1, 0, "printing of GC's bitmap layout for __w
BENIGN_LANGOPT(AccessControl , 1, 1, "C++ access control")
LANGOPT(CharIsSigned , 1, 1, "signed char")
LANGOPT(ShortWChar , 1, 0, "unsigned short wchar_t")
ENUM_LANGOPT(MSPointerToMemberRepresentationMethod, PragmaMSPointersToMembersKind, 2, PPTMK_BestCase, "member-pointer representation method")
LANGOPT(ShortEnums , 1, 0, "short enum types")
@ -175,6 +176,7 @@ BENIGN_LANGOPT(NumLargeByValueCopy, 32, 0,
"if non-zero, warn about parameter or return Warn if parameter/return value is larger in bytes than this setting. 0 is no check.")
VALUE_LANGOPT(MSCVersion, 32, 0,
"version of Microsoft Visual C/C++")
VALUE_LANGOPT(VtorDispMode, 2, 1, "How many vtordisps to insert")
LANGOPT(ApplePragmaPack, 1, 0, "Apple gcc-compatible #pragma pack handling")

View File

@ -66,6 +66,13 @@ public:
SOB_Trapping // -ftrapv
};
enum PragmaMSPointersToMembersKind {
PPTMK_BestCase,
PPTMK_FullGeneralitySingleInheritance,
PPTMK_FullGeneralityMultipleInheritance,
PPTMK_FullGeneralityVirtualInheritance
};
enum AddrSpaceMapMangling { ASMM_Target, ASMM_On, ASMM_Off };
public:

View File

@ -160,11 +160,14 @@ public:
MacrosVisible,
/// \brief All of the names in this module are visible.
AllVisible
};
///\ brief The visibility of names within this particular module.
};
/// \brief The visibility of names within this particular module.
NameVisibilityKind NameVisibility;
/// \brief The location at which macros within this module became visible.
SourceLocation MacroVisibilityLoc;
/// \brief The location of the inferred submodule.
SourceLocation InferredSubmoduleLoc;

View File

@ -21,6 +21,9 @@
#ifndef OPENMP_PARALLEL_CLAUSE
# define OPENMP_PARALLEL_CLAUSE(Name)
#endif
#ifndef OPENMP_SIMD_CLAUSE
# define OPENMP_SIMD_CLAUSE(Name)
#endif
#ifndef OPENMP_DEFAULT_KIND
# define OPENMP_DEFAULT_KIND(Name)
#endif
@ -29,19 +32,24 @@
OPENMP_DIRECTIVE(threadprivate)
OPENMP_DIRECTIVE(parallel)
OPENMP_DIRECTIVE(task)
OPENMP_DIRECTIVE(simd)
// OpenMP clauses.
OPENMP_CLAUSE(if, OMPIfClause)
OPENMP_CLAUSE(default, OMPDefaultClause)
OPENMP_CLAUSE(private, OMPPrivateClause)
OPENMP_CLAUSE(firstprivate, OMPFirstprivateClause)
OPENMP_CLAUSE(shared, OMPSharedClause)
// Clauses allowed for OpenMP directives.
OPENMP_PARALLEL_CLAUSE(if)
OPENMP_PARALLEL_CLAUSE(default)
OPENMP_PARALLEL_CLAUSE(private)
OPENMP_PARALLEL_CLAUSE(firstprivate)
OPENMP_PARALLEL_CLAUSE(shared)
// FIXME: clauses allowed for directive 'omp simd'.
// Static attributes for 'default' clause.
OPENMP_DEFAULT_KIND(none)
OPENMP_DEFAULT_KIND(shared)
@ -50,3 +58,5 @@ OPENMP_DEFAULT_KIND(shared)
#undef OPENMP_DIRECTIVE
#undef OPENMP_CLAUSE
#undef OPENMP_PARALLEL_CLAUSE
#undef OPENMP_SIMD_CLAUSE

View File

@ -188,7 +188,7 @@ inline bool operator<(const SourceLocation &LHS, const SourceLocation &RHS) {
return LHS.getRawEncoding() < RHS.getRawEncoding();
}
/// \brief A trival tuple used to represent a source range.
/// \brief A trivial tuple used to represent a source range.
class SourceRange {
SourceLocation B;
SourceLocation E;

View File

@ -178,3 +178,4 @@ def AsTypeExpr : DStmt<Expr>;
// OpenMP Directives.
def OMPExecutableDirective : Stmt<1>;
def OMPParallelDirective : DStmt<OMPExecutableDirective>;
def OMPSimdDirective : DStmt<OMPExecutableDirective>;

View File

@ -455,7 +455,7 @@ KEYWORD(__cdecl , KEYALL)
KEYWORD(__stdcall , KEYALL)
KEYWORD(__fastcall , KEYALL)
KEYWORD(__thiscall , KEYALL)
KEYWORD(__forceinline , KEYALL)
KEYWORD(__forceinline , KEYMS)
KEYWORD(__unaligned , KEYMS)
// OpenCL address space qualifiers
@ -678,6 +678,11 @@ ANNOTATION(pragma_fp_contract)
// handles them.
ANNOTATION(pragma_ms_pointers_to_members)
// Annotation for #pragma vtordisp...
// The lexer produces these so that they only take effect when the parser
// handles them.
ANNOTATION(pragma_ms_vtordisp)
// Annotation for #pragma OPENCL EXTENSION...
// The lexer produces these so that they only take effect when the parser
// handles them.

View File

@ -0,0 +1,170 @@
//===- VirtualFileSystem.h - Virtual File System Layer ----------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// \brief Defines the virtual file system interface vfs::FileSystem.
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_BASIC_VIRTUAL_FILE_SYSTEM_H
#define LLVM_CLANG_BASIC_VIRTUAL_FILE_SYSTEM_H
#include "clang/Basic/LLVM.h"
#include "llvm/ADT/IntrusiveRefCntPtr.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/ErrorOr.h"
#include "llvm/Support/SourceMgr.h"
namespace llvm {
class MemoryBuffer;
}
namespace clang {
namespace vfs {
/// \brief The result of a \p status operation.
class Status {
std::string Name;
llvm::sys::fs::UniqueID UID;
llvm::sys::TimeValue MTime;
uint32_t User;
uint32_t Group;
uint64_t Size;
llvm::sys::fs::file_type Type;
llvm::sys::fs::perms Perms;
public:
Status() : Type(llvm::sys::fs::file_type::status_error) {}
Status(const llvm::sys::fs::file_status &Status);
Status(StringRef Name, StringRef RealName, llvm::sys::fs::UniqueID UID,
llvm::sys::TimeValue MTime, uint32_t User, uint32_t Group,
uint64_t Size, llvm::sys::fs::file_type Type,
llvm::sys::fs::perms Perms);
/// \brief Returns the name that should be used for this file or directory.
StringRef getName() const { return Name; }
void setName(StringRef N) { Name = N; }
/// @name Status interface from llvm::sys::fs
/// @{
llvm::sys::fs::file_type getType() const { return Type; }
llvm::sys::fs::perms getPermissions() const { return Perms; }
llvm::sys::TimeValue getLastModificationTime() const { return MTime; }
llvm::sys::fs::UniqueID getUniqueID() const { return UID; }
uint32_t getUser() const { return User; }
uint32_t getGroup() const { return Group; }
uint64_t getSize() const { return Size; }
void setType(llvm::sys::fs::file_type v) { Type = v; }
void setPermissions(llvm::sys::fs::perms p) { Perms = p; }
/// @}
/// @name Status queries
/// These are static queries in llvm::sys::fs.
/// @{
bool equivalent(const Status &Other) const;
bool isDirectory() const;
bool isRegularFile() const;
bool isOther() const;
bool isSymlink() const;
bool isStatusKnown() const;
bool exists() const;
/// @}
};
/// \brief Represents an open file.
class File {
public:
/// \brief Destroy the file after closing it (if open).
/// Sub-classes should generally call close() inside their destructors. We
/// cannot do that from the base class, since close is virtual.
virtual ~File();
/// \brief Get the status of the file.
virtual llvm::ErrorOr<Status> status() = 0;
/// \brief Get the contents of the file as a \p MemoryBuffer.
virtual llvm::error_code getBuffer(const Twine &Name,
OwningPtr<llvm::MemoryBuffer> &Result,
int64_t FileSize = -1,
bool RequiresNullTerminator = true) = 0;
/// \brief Closes the file.
virtual llvm::error_code close() = 0;
/// \brief Sets the name to use for this file.
virtual void setName(StringRef Name) = 0;
};
/// \brief The virtual file system interface.
class FileSystem : public RefCountedBase<FileSystem> {
public:
virtual ~FileSystem();
/// \brief Get the status of the entry at \p Path, if one exists.
virtual llvm::ErrorOr<Status> status(const Twine &Path) = 0;
/// \brief Get a \p File object for the file at \p Path, if one exists.
virtual llvm::error_code openFileForRead(const Twine &Path,
OwningPtr<File> &Result) = 0;
/// This is a convenience method that opens a file, gets its content and then
/// closes the file.
llvm::error_code getBufferForFile(const Twine &Name,
OwningPtr<llvm::MemoryBuffer> &Result,
int64_t FileSize = -1,
bool RequiresNullTerminator = true);
};
/// \brief Gets an \p vfs::FileSystem for the 'real' file system, as seen by
/// the operating system.
IntrusiveRefCntPtr<FileSystem> getRealFileSystem();
/// \brief A file system that allows overlaying one \p AbstractFileSystem on top
/// of another.
///
/// Consists of a stack of >=1 \p FileSystem objects, which are treated as being
/// one merged file system. When there is a directory that exists in more than
/// one file system, the \p OverlayFileSystem contains a directory containing
/// the union of their contents. The attributes (permissions, etc.) of the
/// top-most (most recently added) directory are used. When there is a file
/// that exists in more than one file system, the file in the top-most file
/// system overrides the other(s).
class OverlayFileSystem : public FileSystem {
typedef SmallVector<IntrusiveRefCntPtr<FileSystem>, 1> FileSystemList;
typedef FileSystemList::reverse_iterator iterator;
/// \brief The stack of file systems, implemented as a list in order of
/// their addition.
FileSystemList FSList;
/// \brief Get an iterator pointing to the most recently added file system.
iterator overlays_begin() { return FSList.rbegin(); }
/// \brief Get an iterator pointing one-past the least recently added file
/// system.
iterator overlays_end() { return FSList.rend(); }
public:
OverlayFileSystem(IntrusiveRefCntPtr<FileSystem> Base);
/// \brief Pushes a file system on top of the stack.
void pushOverlay(IntrusiveRefCntPtr<FileSystem> FS);
llvm::ErrorOr<Status> status(const Twine &Path) LLVM_OVERRIDE;
llvm::error_code openFileForRead(const Twine &Path,
OwningPtr<File> &Result) LLVM_OVERRIDE;
};
/// \brief Get a globally unique ID for a virtual file or directory.
llvm::sys::fs::UniqueID getNextVirtualUniqueID();
/// \brief Gets a \p FileSystem for a virtual file system described in YAML
/// format.
///
/// Takes ownership of \p Buffer.
IntrusiveRefCntPtr<FileSystem>
getVFSFromYAML(llvm::MemoryBuffer *Buffer,
llvm::SourceMgr::DiagHandlerTy DiagHandler,
void *DiagContext = 0,
IntrusiveRefCntPtr<FileSystem> ExternalFS = getRealFileSystem());
} // end namespace vfs
} // end namespace clang
#endif // LLVM_CLANG_BASIC_VIRTUAL_FILE_SYSTEM_H

View File

@ -141,13 +141,17 @@ class Inst <string n, string p, string t, Op o> {
string Name = n;
string Prototype = p;
string Types = t;
string ArchGuard = "";
Op Operand = o;
bit isShift = 0;
bit isScalarShift = 0;
bit isScalarNarrowShift = 0;
bit isVCVT_N = 0;
bit isA64 = 0;
bit isCrypto = 0;
// For immediate checks: the immediate will be assumed to specify the lane of
// a Q register. Only used for intrinsics which end up calling polymorphic
// builtins.
bit isLaneQ = 0;
// Certain intrinsics have different names than their representative
// instructions. This field allows us to handle this correctly when we
@ -406,9 +410,11 @@ def VCREATE : NoTestOpInst<"vcreate", "dl", "csihfUcUsUiUlPcPsl", OP_CAST>;
// E.3.19 Set all lanes to same value
let InstName = "vmov" in {
def VDUP_N : WOpInst<"vdup_n", "ds",
"UcUsUicsiPcPsfQUcQUsQUiQcQsQiQPcQPsQflUlQlQUl", OP_DUP>;
"UcUsUicsiPcPshfQUcQUsQUiQcQsQiQPcQPsQhQflUlQlQUl",
OP_DUP>;
def VMOV_N : WOpInst<"vmov_n", "ds",
"UcUsUicsiPcPsfQUcQUsQUiQcQsQiQPcQPsQflUlQlQUl", OP_DUP>;
"UcUsUicsiPcPshfQUcQUsQUiQcQsQiQPcQPsQhQflUlQlQUl",
OP_DUP>;
}
let InstName = "" in
def VDUP_LANE: WOpInst<"vdup_lane", "dgi",
@ -542,90 +548,66 @@ def VFMA : SInst<"vfma", "dddd", "fQf">;
////////////////////////////////////////////////////////////////////////////////
// AArch64 Intrinsics
let isA64 = 1 in {
let ArchGuard = "defined(__aarch64__)" in {
////////////////////////////////////////////////////////////////////////////////
// Load/Store
// With additional QUl, Ql, d, Qd, Pl, QPl type.
def LD1 : WInst<"vld1", "dc",
"QUcQUsQUiQUlQcQsQiQlQhQfQdQPcQPsUcUsUiUlcsilhfdPcPsPlQPl">;
def LD2 : WInst<"vld2", "2c",
"QUcQUsQUiQUlQcQsQiQlQhQfQdQPcQPsUcUsUiUlcsilhfdPcPsPlQPl">;
def LD3 : WInst<"vld3", "3c",
"QUcQUsQUiQUlQcQsQiQlQhQfQdQPcQPsUcUsUiUlcsilhfdPcPsPlQPl">;
def LD4 : WInst<"vld4", "4c",
"QUcQUsQUiQUlQcQsQiQlQhQfQdQPcQPsUcUsUiUlcsilhfdPcPsPlQPl">;
def ST1 : WInst<"vst1", "vpd",
"QUcQUsQUiQUlQcQsQiQlQhQfQdQPcQPsUcUsUiUlcsilhfdPcPsPlQPl">;
def ST2 : WInst<"vst2", "vp2",
"QUcQUsQUiQUlQcQsQiQlQhQfQdQPcQPsUcUsUiUlcsilhfdPcPsPlQPl">;
def ST3 : WInst<"vst3", "vp3",
"QUcQUsQUiQUlQcQsQiQlQhQfQdQPcQPsUcUsUiUlcsilhfdPcPsPlQPl">;
def ST4 : WInst<"vst4", "vp4",
"QUcQUsQUiQUlQcQsQiQlQhQfQdQPcQPsUcUsUiUlcsilhfdPcPsPlQPl">;
def LD1 : WInst<"vld1", "dc", "dQdPlQPl">;
def LD2 : WInst<"vld2", "2c", "QUlQldQdPlQPl">;
def LD3 : WInst<"vld3", "3c", "QUlQldQdPlQPl">;
def LD4 : WInst<"vld4", "4c", "QUlQldQdPlQPl">;
def ST1 : WInst<"vst1", "vpd", "dQdPlQPl">;
def ST2 : WInst<"vst2", "vp2", "QUlQldQdPlQPl">;
def ST3 : WInst<"vst3", "vp3", "QUlQldQdPlQPl">;
def ST4 : WInst<"vst4", "vp4", "QUlQldQdPlQPl">;
def LD1_X2 : WInst<"vld1_x2", "2c",
"QUcQUsQUiQUlQcQsQiQlQhQfQdQPcQPsQPlUcUsUiUlcsilhfdPcPsPl">;
"QUcQUsQUiQcQsQiQhQfQPcQPsUcUsUiUlcsilhfPcPsQUlQldQdPlQPl">;
def LD3_x3 : WInst<"vld1_x3", "3c",
"QUcQUsQUiQUlQcQsQiQlQhQfQdQPcQPsQPlUcUsUiUlcsilhfdPcPsPl">;
"QUcQUsQUiQcQsQiQhQfQPcQPsUcUsUiUlcsilhfPcPsQUlQldQdPlQPl">;
def LD4_x4 : WInst<"vld1_x4", "4c",
"QUcQUsQUiQUlQcQsQiQlQhQfQdQPcQPsQPlUcUsUiUlcsilhfdPcPsPl">;
"QUcQUsQUiQcQsQiQhQfQPcQPsUcUsUiUlcsilhfPcPsQUlQldQdPlQPl">;
def ST1_X2 : WInst<"vst1_x2", "vp2",
"QUcQUsQUiQUlQcQsQiQlQhQfQdQPcQPsQPlUcUsUiUlcsilhfdPcPsPl">;
"QUcQUsQUiQcQsQiQhQfQPcQPsUcUsUiUlcsilhfPcPsQUlQldQdPlQPl">;
def ST1_X3 : WInst<"vst1_x3", "vp3",
"QUcQUsQUiQUlQcQsQiQlQhQfQdQPcQPsQPlUcUsUiUlcsilhfdPcPsPl">;
"QUcQUsQUiQcQsQiQhQfQPcQPsUcUsUiUlcsilhfPcPsQUlQldQdPlQPl">;
def ST1_X4 : WInst<"vst1_x4", "vp4",
"QUcQUsQUiQUlQcQsQiQlQhQfQdQPcQPsQPlUcUsUiUlcsilhfdPcPsPl">;
"QUcQUsQUiQcQsQiQhQfQPcQPsUcUsUiUlcsilhfPcPsQUlQldQdPlQPl">;
// With additional QUl, Ql, d, Qd, Pl, QPl type.
def LD1_LANE : WInst<"vld1_lane", "dcdi",
"QUcQUsQUiQUlQcQsQiQlQhQfQdQPcQPsQPlUcUsUiUlcsilhfdPcPsPl">;
def LD2_LANE : WInst<"vld2_lane", "2c2i",
"QUcQUsQUiQUlQcQsQiQlQhQfQdQPcQPsQPlUcUsUiUlcsilhfdPcPsPl">;
def LD3_LANE : WInst<"vld3_lane", "3c3i",
"QUcQUsQUiQUlQcQsQiQlQhQfQdQPcQPsQPlUcUsUiUlcsilhfdPcPsPl">;
def LD4_LANE : WInst<"vld4_lane", "4c4i",
"QUcQUsQUiQUlQcQsQiQlQhQfQdQPcQPsQPlUcUsUiUlcsilhfdPcPsPl">;
def ST1_LANE : WInst<"vst1_lane", "vpdi",
"QUcQUsQUiQUlQcQsQiQlQhQfQdQPcQPsQPlUcUsUiUlcsilhfdPcPsPl">;
def ST2_LANE : WInst<"vst2_lane", "vp2i",
"QUcQUsQUiQUlQcQsQiQlQhQfQdQPcQPsQPlUcUsUiUlcsilhfdPcPsPl">;
def ST3_LANE : WInst<"vst3_lane", "vp3i",
"QUcQUsQUiQUlQcQsQiQlQhQfQdQPcQPsQPlUcUsUiUlcsilhfdPcPsPl">;
def ST4_LANE : WInst<"vst4_lane", "vp4i",
"QUcQUsQUiQUlQcQsQiQlQhQfQdQPcQPsQPlUcUsUiUlcsilhfdPcPsPl">;
def LD1_LANE : WInst<"vld1_lane", "dcdi", "dQdPlQPl">;
def LD2_LANE : WInst<"vld2_lane", "2c2i", "lUlQcQUcQPcQlQUldQdPlQPl">;
def LD3_LANE : WInst<"vld3_lane", "3c3i", "lUlQcQUcQPcQlQUldQdPlQPl">;
def LD4_LANE : WInst<"vld4_lane", "4c4i", "lUlQcQUcQPcQlQUldQdPlQPl">;
def ST1_LANE : WInst<"vst1_lane", "vpdi", "dQdPlQPl">;
def ST2_LANE : WInst<"vst2_lane", "vp2i", "lUlQcQUcQPcQlQUldQdPlQPl">;
def ST3_LANE : WInst<"vst3_lane", "vp3i", "lUlQcQUcQPcQlQUldQdPlQPl">;
def ST4_LANE : WInst<"vst4_lane", "vp4i", "lUlQcQUcQPcQlQUldQdPlQPl">;
def LD1_DUP : WInst<"vld1_dup", "dc",
"QUcQUsQUiQUlQcQsQiQlQhQfQdQPcQPsQPlUcUsUiUlcsilhfdPcPsPl">;
def LD1_DUP : WInst<"vld1_dup", "dc", "dQdPlQPl">;
def LD2_DUP : WInst<"vld2_dup", "2c",
"QUcQUsQUiQUlQcQsQiQlQhQfQdQPcQPsQPlUcUsUiUlcsilhfdPcPsPl">;
"QUcQUsQUiQUlQcQsQiQlQhQfQdQPcQPsQPldPl">;
def LD3_DUP : WInst<"vld3_dup", "3c",
"QUcQUsQUiQUlQcQsQiQlQhQfQdQPcQPsQPlUcUsUiUlcsilhfdPcPsPl">;
"QUcQUsQUiQUlQcQsQiQlQhQfQdQPcQPsQPldPl">;
def LD4_DUP : WInst<"vld4_dup", "4c",
"QUcQUsQUiQUlQcQsQiQlQhQfQdQPcQPsQPlUcUsUiUlcsilhfdPcPsPl">;
"QUcQUsQUiQUlQcQsQiQlQhQfQdQPcQPsQPldPl">;
def VLDRQ : WInst<"vldrq", "sc", "Pk">;
def VSTRQ : WInst<"vstrq", "vps", "Pk">;
////////////////////////////////////////////////////////////////////////////////
// Addition
// With additional d, Qd type.
def ADD : IOpInst<"vadd", "ddd", "csilfdUcUsUiUlQcQsQiQlQfQUcQUsQUiQUlQd",
OP_ADD>;
def ADD : IOpInst<"vadd", "ddd", "dQd", OP_ADD>;
////////////////////////////////////////////////////////////////////////////////
// Subtraction
// With additional Qd type.
def SUB : IOpInst<"vsub", "ddd", "csildfUcUsUiUlQcQsQiQlQfQUcQUsQUiQUlQd",
OP_SUB>;
def SUB : IOpInst<"vsub", "ddd", "dQd", OP_SUB>;
////////////////////////////////////////////////////////////////////////////////
// Multiplication
// With additional Qd type.
def MUL : IOpInst<"vmul", "ddd", "csifdUcUsUiQcQsQiQfQUcQUsQUiQd", OP_MUL>;
def MLA : IOpInst<"vmla", "dddd", "csifdUcUsUiQcQsQiQfQUcQUsQUiQd", OP_MLA>;
def MLS : IOpInst<"vmls", "dddd", "csifdUcUsUiQcQsQiQfQUcQUsQUiQd", OP_MLS>;
def MUL : IOpInst<"vmul", "ddd", "dQd", OP_MUL>;
def MLA : IOpInst<"vmla", "dddd", "dQd", OP_MLA>;
def MLS : IOpInst<"vmls", "dddd", "dQd", OP_MLS>;
////////////////////////////////////////////////////////////////////////////////
// Multiplication Extended
@ -637,34 +619,33 @@ def FDIV : IOpInst<"vdiv", "ddd", "fdQfQd", OP_DIV>;
////////////////////////////////////////////////////////////////////////////////
// Vector fused multiply-add operations
// With additional d, Qd type.
def FMLA : SInst<"vfma", "dddd", "fdQfQd">;
def FMLA : SInst<"vfma", "dddd", "dQd">;
def FMLS : SInst<"vfms", "dddd", "fdQfQd">;
////////////////////////////////////////////////////////////////////////////////
// MUL, FMA, FMS definitions with scalar argument
// MUL, MLA, MLS, FMA, FMS definitions with scalar argument
def VMUL_N_A64 : IOpInst<"vmul_n", "dds", "Qd", OP_MUL_N>;
def FMLA_N : SOpInst<"vfma_n", "ddds", "fQf", OP_FMLA_N>;
def FMLS_N : SOpInst<"vfms_n", "ddds", "fQf", OP_FMLS_N>;
def FMLA_N : SOpInst<"vfma_n", "ddds", "fQfQd", OP_FMLA_N>;
def FMLS_N : SOpInst<"vfms_n", "ddds", "fQfQd", OP_FMLS_N>;
def MLA_N : SOpInst<"vmla_n", "ddds", "Qd", OP_MLA_N>;
def MLS_N : SOpInst<"vmls_n", "ddds", "Qd", OP_MLS_N>;
////////////////////////////////////////////////////////////////////////////////
// Logical operations
// With additional Qd, Ql, QPl type.
def BSL : SInst<"vbsl", "dudd",
"csilUcUsUiUlfdPcPsQcQsQiQlQUcQUsQUiQUlQfQPcQPsQdPlQPl">;
def BSL : SInst<"vbsl", "dudd", "dPlQdQPl">;
////////////////////////////////////////////////////////////////////////////////
// Absolute Difference
// With additional Qd type.
def ABD : SInst<"vabd", "ddd", "csiUcUsUifdQcQsQiQUcQUsQUiQfQd">;
def ABD : SInst<"vabd", "ddd", "dQd">;
////////////////////////////////////////////////////////////////////////////////
// saturating absolute/negate
// With additional Qd/Ql type.
def ABS : SInst<"vabs", "dd", "csilfdQcQsQiQfQlQd">;
def QABS : SInst<"vqabs", "dd", "csilQcQsQiQl">;
def NEG : SOpInst<"vneg", "dd", "csilfdQcQsQiQfQdQl", OP_NEG>;
def QNEG : SInst<"vqneg", "dd", "csilQcQsQiQl">;
def ABS : SInst<"vabs", "dd", "dQdlQl">;
def QABS : SInst<"vqabs", "dd", "lQl">;
def NEG : SOpInst<"vneg", "dd", "dlQdQl", OP_NEG>;
def QNEG : SInst<"vqneg", "dd", "lQl">;
////////////////////////////////////////////////////////////////////////////////
// Signed Saturating Accumulated of Unsigned Value
@ -676,9 +657,8 @@ def USQADD : SInst<"vsqadd", "ddd", "UcUsUiUlQUcQUsQUiQUl">;
////////////////////////////////////////////////////////////////////////////////
// Reciprocal/Sqrt
// With additional d, Qd type.
def FRECPS : IInst<"vrecps", "ddd", "fdQfQd">;
def FRSQRTS : IInst<"vrsqrts", "ddd", "fdQfQd">;
def FRECPS : IInst<"vrecps", "ddd", "dQd">;
def FRSQRTS : IInst<"vrsqrts", "ddd", "dQd">;
////////////////////////////////////////////////////////////////////////////////
// bitwise reverse
@ -700,7 +680,7 @@ def QXTN2 : SOpInst<"vqmovn_high", "qhk", "silUsUiUl", OP_QXTN>;
// Converting vectors
def VCVT_HIGH_F16 : SOpInst<"vcvt_high_f16", "qhj", "f", OP_VCVT_NA_HI>;
def VCVT_HIGH_F32_F16 : SOpInst<"vcvt_high_f32", "wk", "h", OP_VCVT_EX_HI>;
def VCVT_F32_F64 : SInst<"vcvt_f32_f64", "fj", "d">;
def VCVT_F32_F64 : SInst<"vcvt_f32_f64", "mj", "d">;
def VCVT_HIGH_F32_F64 : SOpInst<"vcvt_high_f32", "qfj", "d", OP_VCVT_NA_HI>;
def VCVT_F64_F32 : SInst<"vcvt_f64_f32", "wd", "f">;
def VCVT_F64 : SInst<"vcvt_f64", "Fd", "lUlQlQUl">;
@ -716,47 +696,22 @@ def FRINTZ : SInst<"vrnd", "dd", "fdQfQd">;
def FRINTI : SInst<"vrndi", "dd", "fdQfQd">;
def VCVT_S64 : SInst<"vcvt_s64", "xd", "dQd">;
def VCVT_U64 : SInst<"vcvt_u64", "ud", "dQd">;
def FCVTNS_S32 : SInst<"vcvtn_s32", "xd", "fQf">;
def FCVTNS_S64 : SInst<"vcvtn_s64", "xd", "dQd">;
def FCVTNU_S32 : SInst<"vcvtn_u32", "ud", "fQf">;
def FCVTNU_S64 : SInst<"vcvtn_u64", "ud", "dQd">;
def FCVTPS_S32 : SInst<"vcvtp_s32", "xd", "fQf">;
def FCVTPS_S64 : SInst<"vcvtp_s64", "xd", "dQd">;
def FCVTPU_S32 : SInst<"vcvtp_u32", "ud", "fQf">;
def FCVTPU_S64 : SInst<"vcvtp_u64", "ud", "dQd">;
def FCVTMS_S32 : SInst<"vcvtm_s32", "xd", "fQf">;
def FCVTMS_S64 : SInst<"vcvtm_s64", "xd", "dQd">;
def FCVTMU_S32 : SInst<"vcvtm_u32", "ud", "fQf">;
def FCVTMU_S64 : SInst<"vcvtm_u64", "ud", "dQd">;
def FCVTAS_S32 : SInst<"vcvta_s32", "xd", "fQf">;
def FCVTAS_S64 : SInst<"vcvta_s64", "xd", "dQd">;
def FCVTAU_S32 : SInst<"vcvta_u32", "ud", "fQf">;
def FCVTAU_S64 : SInst<"vcvta_u64", "ud", "dQd">;
def FRECPE : SInst<"vrecpe", "dd", "fdUiQfQUiQd">;
def FRSQRTE : SInst<"vrsqrte", "dd", "fdUiQfQUiQd">;
def FRECPE : SInst<"vrecpe", "dd", "dQd">;
def FRSQRTE : SInst<"vrsqrte", "dd", "dQd">;
def FSQRT : SInst<"vsqrt", "dd", "fdQfQd">;
////////////////////////////////////////////////////////////////////////////////
// Comparison
// With additional Qd, Ql, QPl type.
def FCAGE : IInst<"vcage", "udd", "fdQfQd">;
def FCAGT : IInst<"vcagt", "udd", "fdQfQd">;
def FCALE : IInst<"vcale", "udd", "fdQfQd">;
def FCALT : IInst<"vcalt", "udd", "fdQfQd">;
// With additional Ql, QUl, Qd types.
def CMTST : WInst<"vtst", "udd",
"csiUcUsUiPcPsQcQsQiQUcQUsQUiQPcQPslUlQlQUlPlQPl">;
// With additional l, Ul,d, Qd, Ql, QUl, Qd types.
def CFMEQ : SOpInst<"vceq", "udd",
"csilfUcUsUiUlPcQcdQdQsQiQfQUcQUsQUiQUlQlQPcPlQPl", OP_EQ>;
def CFMGE : SOpInst<"vcge", "udd",
"csilfUcUsUiUlQcQsQiQlQfQUcQUsQUiQUldQd", OP_GE>;
def CFMLE : SOpInst<"vcle", "udd",
"csilfUcUsUiUlQcQsQiQlQfQUcQUsQUiQUldQd", OP_LE>;
def CFMGT : SOpInst<"vcgt", "udd",
"csilfUcUsUiUlQcQsQiQlQfQUcQUsQUiQUldQd", OP_GT>;
def CFMLT : SOpInst<"vclt", "udd",
"csilfUcUsUiUlQcQsQiQlQfQUcQUsQUiQUldQd", OP_LT>;
def FCAGE : IInst<"vcage", "udd", "dQd">;
def FCAGT : IInst<"vcagt", "udd", "dQd">;
def FCALE : IInst<"vcale", "udd", "dQd">;
def FCALT : IInst<"vcalt", "udd", "dQd">;
def CMTST : WInst<"vtst", "udd", "lUlPlQlQUlQPl">;
def CFMEQ : SOpInst<"vceq", "udd", "lUldQdQlQUlPlQPl", OP_EQ>;
def CFMGE : SOpInst<"vcge", "udd", "lUldQdQlQUl", OP_GE>;
def CFMLE : SOpInst<"vcle", "udd", "lUldQdQlQUl", OP_LE>;
def CFMGT : SOpInst<"vcgt", "udd", "lUldQdQlQUl", OP_GT>;
def CFMLT : SOpInst<"vclt", "udd", "lUldQdQlQUl", OP_LT>;
def CMEQ : SInst<"vceqz", "ud",
"csilfUcUsUiUlPcPsPlQcQsQiQlQfQUcQUsQUiQUlQPcQPsdQdQPl">;
@ -767,9 +722,8 @@ def CMLT : SInst<"vcltz", "ud", "csilfdQcQsQiQlQfQd">;
////////////////////////////////////////////////////////////////////////////////
// Max/Min Integer
// With additional Qd type.
def MAX : SInst<"vmax", "ddd", "csiUcUsUifdQcQsQiQUcQUsQUiQfQd">;
def MIN : SInst<"vmin", "ddd", "csiUcUsUifdQcQsQiQUcQUsQUiQfQd">;
def MAX : SInst<"vmax", "ddd", "dQd">;
def MIN : SInst<"vmin", "ddd", "dQd">;
////////////////////////////////////////////////////////////////////////////////
// MaxNum/MinNum Floating Point
@ -778,9 +732,8 @@ def FMINNM : SInst<"vminnm", "ddd", "fdQfQd">;
////////////////////////////////////////////////////////////////////////////////
// Pairwise Max/Min
// With additional Qc Qs Qi QUc QUs QUi Qf Qd types.
def MAXP : SInst<"vpmax", "ddd", "csiUcUsUifQcQsQiQUcQUsQUiQfQd">;
def MINP : SInst<"vpmin", "ddd", "csiUcUsUifQcQsQiQUcQUsQUiQfQd">;
def MAXP : SInst<"vpmax", "ddd", "QcQsQiQUcQUsQUiQfQd">;
def MINP : SInst<"vpmin", "ddd", "QcQsQiQUcQUsQUiQfQd">;
////////////////////////////////////////////////////////////////////////////////
// Pairwise MaxNum/MinNum Floating Point
@ -789,8 +742,7 @@ def FMINNMP : SInst<"vpminnm", "ddd", "fQfQd">;
////////////////////////////////////////////////////////////////////////////////
// Pairwise Addition
// With additional Qc Qs Qi QUc QUs QUi Qf Qd types.
def ADDP : IInst<"vpadd", "ddd", "csiUcUsUifQcQsQiQlQUcQUsQUiQUlQfQd">;
def ADDP : IInst<"vpadd", "ddd", "QcQsQiQlQUcQUsQUiQUlQfQd">;
////////////////////////////////////////////////////////////////////////////////
// Shifts by constant
@ -800,11 +752,8 @@ def SHLL_HIGH_N : SOpInst<"vshll_high_n", "ndi", "HcHsHiHUcHUsHUi",
OP_LONG_HI>;
////////////////////////////////////////////////////////////////////////////////
// Shifts with insert, with additional Ql, QPl type.
def SRI_N : WInst<"vsri_n", "dddi",
"csilUcUsUiUlPcPsQcQsQiQlQUcQUsQUiQUlQPcQPsPlQPl">;
def SLI_N : WInst<"vsli_n", "dddi",
"csilUcUsUiUlPcPsQcQsQiQlQUcQUsQUiQUlQPcQPsPlQPl">;
def SRI_N : WInst<"vsri_n", "dddi", "PlQPl">;
def SLI_N : WInst<"vsli_n", "dddi", "PlQPl">;
// Right shift narrow high
def SHRN_HIGH_N : IOpInst<"vshrn_high_n", "hmdi",
@ -865,12 +814,10 @@ def VMULL_HIGH_P64 : SOpInst<"vmull_high", "rdd", "HPl", OP_MULLHi_P64>;
////////////////////////////////////////////////////////////////////////////////
// Extract or insert element from vector
def GET_LANE : IInst<"vget_lane", "sdi",
"csilPcPsUcUsUiUlQcQsQiQlQUcQUsQUiQUlPcPsQPcQPsfdQfQdPlQPl">;
def SET_LANE : IInst<"vset_lane", "dsdi",
"csilPcPsUcUsUiUlQcQsQiQlQUcQUsQUiQUlPcPsQPcQPsfdQfQdPlQPl">;
def GET_LANE : IInst<"vget_lane", "sdi", "dQdPlQPl">;
def SET_LANE : IInst<"vset_lane", "dsdi", "dQdPlQPl">;
def COPY_LANE : IOpInst<"vcopy_lane", "ddidi",
"csilPcPsUcUsUiUlPcPsPlfd", OP_COPY_LN>;
"csilUcUsUiUlPcPsPlfd", OP_COPY_LN>;
def COPYQ_LANE : IOpInst<"vcopy_lane", "ddigi",
"QcQsQiQlQUcQUsQUiQUlQPcQPsQfQdQPl", OP_COPYQ_LN>;
def COPY_LANEQ : IOpInst<"vcopy_laneq", "ddiki",
@ -880,26 +827,19 @@ def COPYQ_LANEQ : IOpInst<"vcopy_laneq", "ddidi",
////////////////////////////////////////////////////////////////////////////////
// Set all lanes to same value
def VDUP_LANE1: WOpInst<"vdup_lane", "dgi",
"csilPcPsUcUsUiUlhfdQcQsQiQlQPcQPsQUcQUsQUiQUlQhQfQdPlQPl",
OP_DUP_LN>;
def VDUP_LANE1: WOpInst<"vdup_lane", "dgi", "hdQhQdPlQPl", OP_DUP_LN>;
def VDUP_LANE2: WOpInst<"vdup_laneq", "dki",
"csilPcPsUcUsUiUlhfdQcQsQiQlQPcQPsQUcQUsQUiQUlQhQfQdPlQPl",
"csilUcUsUiUlPcPshfdQcQsQiQlQPcQPsQUcQUsQUiQUlQhQfQdPlQPl",
OP_DUP_LN>;
def DUP_N : WOpInst<"vdup_n", "ds",
"UcUsUicsiPcPsfQUcQUsQUiQcQsQiQPcQPsQflUlQlQUldQdPlQPl",
OP_DUP>;
def MOV_N : WOpInst<"vmov_n", "ds",
"UcUsUicsiPcPsfQUcQUsQUiQcQsQiQPcQPsQflUlQlQUldQd",
OP_DUP>;
def DUP_N : WOpInst<"vdup_n", "ds", "dQdPlQPl", OP_DUP>;
def MOV_N : WOpInst<"vmov_n", "ds", "dQd", OP_DUP>;
////////////////////////////////////////////////////////////////////////////////
// Combining vectors, with additional Pl
def COMBINE : NoTestOpInst<"vcombine", "kdd", "csilhfdUcUsUiUlPcPsPl", OP_CONC>;
def COMBINE : NoTestOpInst<"vcombine", "kdd", "dPl", OP_CONC>;
////////////////////////////////////////////////////////////////////////////////
//Initialize a vector from bit pattern, with additional Pl
def CREATE : NoTestOpInst<"vcreate", "dl", "csihfdUcUsUiUlPcPslPl", OP_CAST>;
//Initialize a vector from bit pattern
def CREATE : NoTestOpInst<"vcreate", "dl", "dPl", OP_CAST>;
////////////////////////////////////////////////////////////////////////////////
@ -909,7 +849,9 @@ def VMLS_LANEQ : IOpInst<"vmls_laneq", "dddji",
"siUsUifQsQiQUsQUiQf", OP_MLS_LN>;
def VFMA_LANE : IInst<"vfma_lane", "dddgi", "fdQfQd">;
def VFMA_LANEQ : IInst<"vfma_laneq", "dddji", "fdQfQd">;
def VFMA_LANEQ : IInst<"vfma_laneq", "dddji", "fdQfQd"> {
let isLaneQ = 1;
}
def VFMS_LANE : IOpInst<"vfms_lane", "dddgi", "fdQfQd", OP_FMS_LN>;
def VFMS_LANEQ : IOpInst<"vfms_laneq", "dddji", "fdQfQd", OP_FMS_LNQ>;
@ -941,7 +883,7 @@ def VMUL_LANE_A64 : IOpInst<"vmul_lane", "ddgi", "Qd", OP_MUL_LN>;
// Note: d type is handled by SCALAR_VMUL_LANEQ
def VMUL_LANEQ : IOpInst<"vmul_laneq", "ddji",
"sifUsUiQsQiQfQUsQUiQfQd", OP_MUL_LN>;
"sifUsUiQsQiQUsQUiQfQd", OP_MUL_LN>;
def VMULL_LANEQ : SOpInst<"vmull_laneq", "wdki", "siUsUi", OP_MULL_LN>;
def VMULL_HIGH_LANE : SOpInst<"vmull_high_lane", "wkdi", "siUsUi",
OP_MULLHi_LN>;
@ -973,12 +915,11 @@ def FMINNMV : SInst<"vminnmv", "sd", "fQfQd">;
////////////////////////////////////////////////////////////////////////////////
// Newly added Vector Extract for f64
def VEXT_A64 : WInst<"vext", "dddi",
"cUcPcsUsPsiUilUlfdQcQUcQPcQsQUsQPsQiQUiQlQUlQfQdPlQPl">;
def VEXT_A64 : WInst<"vext", "dddi", "dQdPlQPl">;
////////////////////////////////////////////////////////////////////////////////
// Crypto
let isCrypto = 1 in {
let ArchGuard = "__ARM_FEATURE_CRYPTO" in {
def AESE : SInst<"vaese", "ddd", "QUc">;
def AESD : SInst<"vaesd", "ddd", "QUc">;
def AESMC : SInst<"vaesmc", "dd", "QUc">;
@ -997,6 +938,31 @@ def SHA256H2 : SInst<"vsha256h2", "dddd", "QUi">;
def SHA256SU1 : SInst<"vsha256su1", "dddd", "QUi">;
}
////////////////////////////////////////////////////////////////////////////////
// Float -> Int conversions with explicit rounding mode
let ArchGuard = "__ARM_ARCH >= 8" in {
def FCVTNS_S32 : SInst<"vcvtn_s32", "xd", "fQf">;
def FCVTNU_S32 : SInst<"vcvtn_u32", "ud", "fQf">;
def FCVTPS_S32 : SInst<"vcvtp_s32", "xd", "fQf">;
def FCVTPU_S32 : SInst<"vcvtp_u32", "ud", "fQf">;
def FCVTMS_S32 : SInst<"vcvtm_s32", "xd", "fQf">;
def FCVTMU_S32 : SInst<"vcvtm_u32", "ud", "fQf">;
def FCVTAS_S32 : SInst<"vcvta_s32", "xd", "fQf">;
def FCVTAU_S32 : SInst<"vcvta_u32", "ud", "fQf">;
}
let ArchGuard = "__ARM_ARCH >= 8 && defined(__aarch64__)" in {
def FCVTNS_S64 : SInst<"vcvtn_s64", "xd", "dQd">;
def FCVTNU_S64 : SInst<"vcvtn_u64", "ud", "dQd">;
def FCVTPS_S64 : SInst<"vcvtp_s64", "xd", "dQd">;
def FCVTPU_S64 : SInst<"vcvtp_u64", "ud", "dQd">;
def FCVTMS_S64 : SInst<"vcvtm_s64", "xd", "dQd">;
def FCVTMU_S64 : SInst<"vcvtm_u64", "ud", "dQd">;
def FCVTAS_S64 : SInst<"vcvta_s64", "xd", "dQd">;
def FCVTAU_S64 : SInst<"vcvta_u64", "ud", "dQd">;
}
////////////////////////////////////////////////////////////////////////////////
// Permutation
def VTRN1 : SOpInst<"vtrn1", "ddd",
@ -1029,10 +995,17 @@ def VQTBX4_A64 : WInst<"vqtbx4", "ddDt", "UccPcQUcQcQPc">;
////////////////////////////////////////////////////////////////////////////////
// Vector reinterpret cast operations
// With additional d, Qd, pl, Qpl types
def REINTERPRET
// NeonEmitter implicitly takes the cartesian product of the type string with
// itself during generation so, unlike all other intrinsics, this one should
// include *all* types, not just additional ones.
//
// We also rely on NeonEmitter handling the 32-bit vreinterpret before the
// 64-bit one so that the common casts don't get guarded as AArch64-only
// (FIXME).
def VVREINTERPRET
: NoTestOpInst<"vreinterpret", "dd",
"csilUcUsUiUlhfdPcPsPlQcQsQiQlQUcQUsQUiQUlQhQfQdQPcQPsQPlQPk", OP_REINT>;
"csilUcUsUiUlhfdPcPsPlQcQsQiQlQUcQUsQUiQUlQhQfQdQPcQPsQPlQPk", OP_REINT>;
////////////////////////////////////////////////////////////////////////////////
@ -1050,10 +1023,8 @@ def SCALAR_SUB : SInst<"vsub", "sss", "SlSUl">;
def SCALAR_QSUB : SInst<"vqsub", "sss", "ScSsSiSlSUcSUsSUiSUl">;
let InstName = "vmov" in {
def VGET_HIGH_A64 : NoTestOpInst<"vget_high", "dk", "csilhfdUcUsUiUlPcPsPl",
OP_HI>;
def VGET_LOW_A64 : NoTestOpInst<"vget_low", "dk", "csilhfdUcUsUiUlPcPsPl",
OP_LO>;
def VGET_HIGH_A64 : NoTestOpInst<"vget_high", "dk", "dPl", OP_HI>;
def VGET_LOW_A64 : NoTestOpInst<"vget_low", "dk", "dPl", OP_LO>;
}
////////////////////////////////////////////////////////////////////////////////
@ -1302,7 +1273,9 @@ def SCALAR_VMUL_N : IInst<"vmul_n", "dds", "d">;
def SCALAR_VMUL_LANE : IInst<"vmul_lane", "ddgi", "d">;
// VMUL_LANEQ d type implemented using scalar mul lane
def SCALAR_VMUL_LANEQ : IInst<"vmul_laneq", "ddji", "d">;
def SCALAR_VMUL_LANEQ : IInst<"vmul_laneq", "ddji", "d"> {
let isLaneQ = 1;
}
// VMULX_LANE d type implemented using scalar vmulx_lane
def SCALAR_VMULX_LANE : IOpInst<"vmulx_lane", "ddgi", "d", OP_SCALAR_VMULX_LN>;

View File

@ -191,6 +191,18 @@ public:
return UIntData;
}
/// \brief Return true if this field of an inalloca struct should be returned
/// to implement a struct return calling convention.
bool getInAllocaSRet() const {
assert(TheKind == InAlloca && "Invalid kind!");
return BoolData0;
}
void setInAllocaSRet(bool SRet) {
assert(TheKind == InAlloca && "Invalid kind!");
BoolData0 = SRet;
}
void dump() const;
};

View File

@ -138,6 +138,8 @@ def split_dwarf : Flag<["-"], "split-dwarf">,
HelpText<"Split out the dwarf .dwo sections">;
def gnu_pubnames : Flag<["-"], "gnu-pubnames">,
HelpText<"Emit newer GNU style pubnames">;
def arange_sections : Flag<["-"], "arange_sections">,
HelpText<"Emit DWARF .debug_arange sections">;
def fforbid_guard_variables : Flag<["-"], "fforbid-guard-variables">,
HelpText<"Emit an error if a C++ static local initializer would need a guard variable">;
def no_implicit_float : Flag<["-"], "no-implicit-float">,
@ -474,6 +476,8 @@ def fsized_deallocation : Flag<["-"], "fsized-deallocation">,
HelpText<"Enable C++1y sized global deallocation functions">;
def fobjc_subscripting_legacy_runtime : Flag<["-"], "fobjc-subscripting-legacy-runtime">,
HelpText<"Allow Objective-C array and dictionary subscripting in legacy runtime">;
def vtordisp_mode_EQ : Joined<["-"], "vtordisp-mode=">,
HelpText<"Control vtordisp placement on win32 targets">;
//===----------------------------------------------------------------------===//
// Header Search Options

View File

@ -96,6 +96,16 @@ def _SLASH_showIncludes : CLFlag<"showIncludes">,
Alias<show_includes>;
def _SLASH_U : CLJoinedOrSeparate<"U">, HelpText<"Undefine macro">,
MetaVarName<"<macro>">, Alias<U>;
def _SLASH_vmb : CLFlag<"vmb">,
HelpText<"Use a best-case representation method for member pointers">;
def _SLASH_vmg : CLFlag<"vmg">,
HelpText<"Use a most-general representation for member pointers">;
def _SLASH_vms : CLFlag<"vms">,
HelpText<"Set the default most-general representation to single inheritance">;
def _SLASH_vmm : CLFlag<"vmm">,
HelpText<"Set the default most-general representation to multiple inheritance">;
def _SLASH_vmv : CLFlag<"vmv">,
HelpText<"Set the default most-general representation to virtual inheritance">;
def _SLASH_W0 : CLFlag<"W0">, HelpText<"Disable all warnings">, Alias<w>;
def _SLASH_W1 : CLFlag<"W1">, HelpText<"Enable -Wall">, Alias<Wall>;
def _SLASH_W2 : CLFlag<"W2">, HelpText<"Enable -Wall">, Alias<Wall>;
@ -107,6 +117,8 @@ def _SLASH_WX : CLFlag<"WX">, HelpText<"Treat warnings as errors">,
def _SLASH_WX_ : CLFlag<"WX-">, HelpText<"Do not treat warnings as errors">,
Alias<W_Joined>, AliasArgs<["no-error"]>;
def _SLASH_w_flag : CLFlag<"w">, HelpText<"Disable all warnings">, Alias<w>;
def _SLASH_vd : CLJoined<"vd">, HelpText<"Control vtordisp placement">,
Alias<vtordisp_mode_EQ>;
def _SLASH_Z7 : CLFlag<"Z7">, Alias<gline_tables_only>;
def _SLASH_Zi : CLFlag<"Zi">, HelpText<"Enable debug information">,
Alias<gline_tables_only>;
@ -168,7 +180,6 @@ def _SLASH_Ob2 : CLIgnoredFlag<"Ob2">;
def _SLASH_RTC : CLIgnoredJoined<"RTC">;
def _SLASH_sdl : CLIgnoredFlag<"sdl">;
def _SLASH_sdl_ : CLIgnoredFlag<"sdl-">;
def _SLASH_vmg : CLIgnoredFlag<"vmg">;
def _SLASH_w : CLIgnoredJoined<"w">;
def _SLASH_Zc_forScope : CLIgnoredFlag<"Zc:forScope">;
def _SLASH_Zc_wchar_t : CLIgnoredFlag<"Zc:wchar_t">;
@ -181,6 +192,7 @@ def _SLASH_AI : CLJoined<"AI">;
def _SLASH_arch : CLJoined<"arch:">;
def _SLASH_bigobj : CLFlag<"bigobj">;
def _SLASH_clr : CLJoined<"clr">;
def _SLASH_d2Zi_PLUS : CLFlag<"d2Zi+">;
def _SLASH_doc : CLJoined<"doc">;
def _SLASH_EH : CLJoined<"EH">;
def _SLASH_EP : CLFlag<"EP">;
@ -232,11 +244,6 @@ def _SLASH_Qpar : CLFlag<"Qpar">;
def _SLASH_Qvec_report : CLJoined<"Qvec-report">;
def _SLASH_u : CLFlag<"u">;
def _SLASH_V : CLFlag<"V">;
def _SLASH_vd : CLJoined<"vd">;
def _SLASH_vmb : CLFlag<"vmb">;
def _SLASH_vmm : CLFlag<"vmm">;
def _SLASH_vms : CLFlag<"vms">;
def _SLASH_vmv : CLFlag<"vmv">;
def _SLASH_volatile : CLFlag<"volatile">;
def _SLASH_WL : CLFlag<"WL">;
def _SLASH_Wp64 : CLFlag<"Wp64">;

View File

@ -88,6 +88,8 @@ public:
/// getCreator - Return the Tool which caused the creation of this job.
const Tool &getCreator() const { return Creator; }
const char *getExecutable() const { return Executable; }
const llvm::opt::ArgStringList &getArguments() const { return Arguments; }
static bool classof(const Job *J) {

View File

@ -0,0 +1,167 @@
//===--- Multilib.h ---------------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef CLANG_LIB_DRIVER_MULTILIB_H_
#define CLANG_LIB_DRIVER_MULTILIB_H_
#include "clang/Basic/LLVM.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Option/Option.h"
#include <string>
#include <vector>
namespace clang {
namespace driver {
/// This corresponds to a single GCC Multilib, or a segment of one controlled
/// by a command line flag
class Multilib {
public:
typedef std::vector<std::string> flags_list;
private:
std::string GCCSuffix;
std::string OSSuffix;
std::string IncludeSuffix;
flags_list Flags;
public:
Multilib(StringRef GCCSuffix = "", StringRef OSSuffix = "",
StringRef IncludeSuffix = "");
/// \brief Get the detected GCC installation path suffix for the multi-arch
/// target variant. Always starts with a '/', unless empty
const std::string &gccSuffix() const {
assert(GCCSuffix.empty() ||
(StringRef(GCCSuffix).front() == '/' && GCCSuffix.size() > 1));
return GCCSuffix;
}
/// Set the GCC installation path suffix.
Multilib &gccSuffix(StringRef S);
/// \brief Get the detected os path suffix for the multi-arch
/// target variant. Always starts with a '/', unless empty
const std::string &osSuffix() const {
assert(OSSuffix.empty() ||
(StringRef(OSSuffix).front() == '/' && OSSuffix.size() > 1));
return OSSuffix;
}
/// Set the os path suffix.
Multilib &osSuffix(StringRef S);
/// \brief Get the include directory suffix. Always starts with a '/', unless
/// empty
const std::string &includeSuffix() const {
assert(IncludeSuffix.empty() ||
(StringRef(IncludeSuffix).front() == '/' && IncludeSuffix.size() > 1));
return IncludeSuffix;
}
/// Set the include directory suffix
Multilib &includeSuffix(StringRef S);
/// \brief Get the flags that indicate or contraindicate this multilib's use
/// All elements begin with either '+' or '-'
const flags_list &flags() const { return Flags; }
flags_list &flags() { return Flags; }
/// Add a flag to the flags list
Multilib &flag(StringRef F) {
assert(F.front() == '+' || F.front() == '-');
Flags.push_back(F);
return *this;
}
/// \brief print summary of the Multilib
void print(raw_ostream &OS) const;
/// Check whether any of the 'against' flags contradict the 'for' flags.
bool isValid() const;
/// Check whether the default is selected
bool isDefault() const
{ return GCCSuffix.empty() && OSSuffix.empty() && IncludeSuffix.empty(); }
bool operator==(const Multilib &Other) const;
};
raw_ostream &operator<<(raw_ostream &OS, const Multilib &M);
class MultilibSet {
public:
typedef std::vector<Multilib> multilib_list;
typedef multilib_list::iterator iterator;
typedef multilib_list::const_iterator const_iterator;
struct FilterCallback {
virtual ~FilterCallback() {};
/// \return true iff the filter should remove the Multilib from the set
virtual bool operator()(const Multilib &M) const = 0;
};
private:
multilib_list Multilibs;
public:
MultilibSet() {}
/// Add an optional Multilib segment
MultilibSet &Maybe(const Multilib &M);
/// Add a set of mutually incompatible Multilib segments
MultilibSet &Either(const Multilib &M1, const Multilib &M2);
MultilibSet &Either(const Multilib &M1, const Multilib &M2,
const Multilib &M3);
MultilibSet &Either(const Multilib &M1, const Multilib &M2,
const Multilib &M3, const Multilib &M4);
MultilibSet &Either(const Multilib &M1, const Multilib &M2,
const Multilib &M3, const Multilib &M4,
const Multilib &M5);
MultilibSet &Either(const std::vector<Multilib> &Ms);
/// Filter out some subset of the Multilibs using a user defined callback
MultilibSet &FilterOut(const FilterCallback &F);
/// Filter out those Multilibs whose gccSuffix matches the given expression
MultilibSet &FilterOut(std::string Regex);
/// Add a completed Multilib to the set
void push_back(const Multilib &M);
/// Union this set of multilibs with another
void combineWith(const MultilibSet &MS);
/// Remove all of thie multilibs from the set
void clear() { Multilibs.clear(); }
iterator begin() { return Multilibs.begin(); }
const_iterator begin() const { return Multilibs.begin(); }
iterator end() { return Multilibs.end(); }
const_iterator end() const { return Multilibs.end(); }
/// Pick the best multilib in the set, \returns false if none are compatible
bool select(const Multilib::flags_list &Flags, Multilib &M) const;
unsigned size() const { return Multilibs.size(); }
void print(raw_ostream &OS) const;
private:
/// Apply the filter to Multilibs and return the subset that remains
static multilib_list filterCopy(const FilterCallback &F,
const multilib_list &Ms);
/// Apply the filter to the multilib_list, removing those that don't match
static void filterInPlace(const FilterCallback &F, multilib_list &Ms);
};
raw_ostream &operator<<(raw_ostream &OS, const MultilibSet &MS);
}
}
#endif

View File

@ -571,6 +571,7 @@ def fmsc_version : Joined<["-"], "fmsc-version=">, Group<f_Group>, Flags<[CC1Opt
def fdelayed_template_parsing : Flag<["-"], "fdelayed-template-parsing">, Group<f_Group>,
HelpText<"Parse templated function definitions at the end of the "
"translation unit">, Flags<[CC1Option]>;
def fms_memptr_rep_EQ : Joined<["-"], "fms-memptr-rep=">, Group<f_Group>, Flags<[CC1Option]>;
def fmodules_cache_path : Joined<["-"], "fmodules-cache-path=">, Group<i_Group>,
Flags<[DriverOption, CC1Option]>, MetaVarName<"<directory>">,
HelpText<"Specify the module cache path">;
@ -580,6 +581,13 @@ def fmodules_prune_interval : Joined<["-"], "fmodules-prune-interval=">, Group<i
def fmodules_prune_after : Joined<["-"], "fmodules-prune-after=">, Group<i_Group>,
Flags<[CC1Option]>, MetaVarName<"<seconds>">,
HelpText<"Specify the interval (in seconds) after which a module file will be considered unused">;
def fbuild_session_timestamp : Joined<["-"], "fbuild-session-timestamp=">,
Group<i_Group>, Flags<[CC1Option]>, MetaVarName<"<time since Epoch in seconds>">,
HelpText<"Time when the current build session started">;
def fmodules_validate_once_per_build_session : Flag<["-"], "fmodules-validate-once-per-build-session">,
Group<i_Group>, Flags<[CC1Option]>,
HelpText<"Don't verify input files for the modules if the module has been "
"successfully validate or loaded during this build session">;
def fmodules : Flag <["-"], "fmodules">, Group<f_Group>,
Flags<[DriverOption, CC1Option]>,
HelpText<"Enable the 'modules' language feature">;
@ -763,6 +771,8 @@ def fshort_enums : Flag<["-"], "fshort-enums">, Group<f_Group>, Flags<[CC1Option
def : Flag<["-"], "freorder-blocks">, Group<clang_ignored_f_Group>;
def fshort_wchar : Flag<["-"], "fshort-wchar">, Group<f_Group>, Flags<[CC1Option]>,
HelpText<"Force wchar_t to be a short unsigned int">;
def fno_short_wchar : Flag<["-"], "fno-short-wchar">, Group<f_Group>, Flags<[CC1Option]>,
HelpText<"Force wchar_t to be an unsigned int">;
def fshow_overloads_EQ : Joined<["-"], "fshow-overloads=">, Group<f_Group>, Flags<[CC1Option]>,
HelpText<"Which overload candidates to show when overload resolution fails: "
"best|all; defaults to all">;
@ -916,6 +926,7 @@ def gno_strict_dwarf : Flag<["-"], "gno-strict-dwarf">, Group<g_flags_Group>;
def gcolumn_info : Flag<["-"], "gcolumn-info">, Group<g_flags_Group>;
def gsplit_dwarf : Flag<["-"], "gsplit-dwarf">, Group<g_flags_Group>;
def ggnu_pubnames : Flag<["-"], "ggnu-pubnames">, Group<g_flags_Group>;
def gdwarf_aranges : Flag<["-"], "gdwarf-aranges">, Group<g_flags_Group>;
def headerpad__max__install__names : Joined<["-"], "headerpad_max_install_names">;
def help : Flag<["-", "--"], "help">, Flags<[CC1Option]>,
HelpText<"Display available options">;
@ -938,7 +949,6 @@ def verify_pch : Flag<["-"], "verify-pch">, Group<Action_Group>, Flags<[CC1Optio
HelpText<"Load and verify that a pre-compiled header file is not stale">;
def init : Separate<["-"], "init">;
def install__name : Separate<["-"], "install_name">;
def integrated_as : Flag<["-"], "integrated-as">, Flags<[DriverOption]>;
def iprefix : JoinedOrSeparate<["-"], "iprefix">, Group<clang_i_Group>, Flags<[CC1Option]>,
HelpText<"Set the -iwithprefix/-iwithprefixbefore prefix">, MetaVarName<"<dir>">;
def iquote : JoinedOrSeparate<["-"], "iquote">, Group<clang_i_Group>, Flags<[CC1Option]>,
@ -956,6 +966,8 @@ def iwithsysroot : JoinedOrSeparate<["-"], "iwithsysroot">, Group<clang_i_Group>
HelpText<"Add directory to SYSTEM include search path, "
"absolute paths are relative to -isysroot">, MetaVarName<"<directory>">,
Flags<[CC1Option]>;
def ivfsoverlay : JoinedOrSeparate<["-"], "ivfsoverlay">, Group<clang_i_Group>, Flags<[CC1Option]>,
HelpText<"Overlay the virtual filesystem described by file over the real file system">;
def i : Joined<["-"], "i">, Group<i_Group>;
def keep__private__externs : Flag<["-"], "keep_private_externs">;
def l : JoinedOrSeparate<["-"], "l">, Flags<[LinkerInput, RenderJoined]>;
@ -1078,6 +1090,8 @@ def mpopcntd : Flag<["-"], "mpopcntd">, Group<m_ppc_Features_Group>;
def mno_popcntd : Flag<["-"], "mno-popcntd">, Group<m_ppc_Features_Group>;
def mqpx : Flag<["-"], "mqpx">, Group<m_ppc_Features_Group>;
def mno_qpx : Flag<["-"], "mno-qpx">, Group<m_ppc_Features_Group>;
def mcrbits : Flag<["-"], "mcrbits">, Group<m_ppc_Features_Group>;
def mno_crbits : Flag<["-"], "mno-crbits">, Group<m_ppc_Features_Group>;
def faltivec : Flag<["-"], "faltivec">, Group<f_Group>, Flags<[CC1Option]>,
HelpText<"Enable AltiVec vector initializer syntax">;
@ -1182,7 +1196,6 @@ def mwarn_nonportable_cfstrings : Flag<["-"], "mwarn-nonportable-cfstrings">, Gr
def no_canonical_prefixes : Flag<["-"], "no-canonical-prefixes">, Flags<[HelpHidden]>,
HelpText<"Use relative instead of canonical paths">;
def no_cpp_precomp : Flag<["-"], "no-cpp-precomp">, Group<clang_ignored_f_Group>;
def no_integrated_as : Flag<["-"], "no-integrated-as">, Flags<[DriverOption]>;
def no_integrated_cpp : Flag<["-", "--"], "no-integrated-cpp">, Flags<[DriverOption]>;
def no_pedantic : Flag<["-", "--"], "no-pedantic">, Group<pedantic_Group>;
def no__dead__strip__inits__and__terms : Flag<["-"], "no_dead_strip_inits_and_terms">;
@ -1302,7 +1315,7 @@ def undef : Flag<["-"], "undef">, Group<u_Group>, Flags<[CC1Option]>,
HelpText<"undef all system defines">;
def unexported__symbols__list : Separate<["-"], "unexported_symbols_list">;
def u : JoinedOrSeparate<["-"], "u">, Group<u_Group>;
def v : Flag<["-"], "v">, Flags<[CC1Option]>,
def v : Flag<["-"], "v">, Flags<[CC1Option, CoreOption]>,
HelpText<"Show commands to run and use verbose output">;
def verify_debug_info : Flag<["--"], "verify-debug-info">, Flags<[DriverOption]>,
HelpText<"Verify the binary representation of debug output">;
@ -1318,6 +1331,15 @@ def x : JoinedOrSeparate<["-"], "x">, Flags<[DriverOption,CC1Option]>,
MetaVarName<"<language>">;
def y : Joined<["-"], "y">;
def fintegrated_as : Flag<["-"], "fintegrated-as">, Flags<[DriverOption]>,
Group<f_Group>, HelpText<"Enable the integrated assembler">;
def fno_integrated_as : Flag<["-"], "fno-integrated-as">,
Flags<[CC1Option, DriverOption]>, Group<f_Group>,
HelpText<"Disable the integrated assembler">;
def : Flag<["-"], "integrated-as">, Alias<fintegrated_as>, Flags<[DriverOption]>;
def : Flag<["-"], "no-integrated-as">, Alias<fno_integrated_as>,
Flags<[CC1Option, DriverOption]>;
def working_directory : JoinedOrSeparate<["-"], "working-directory">, Flags<[CC1Option]>,
HelpText<"Resolve file paths relative to the specified directory">;
def working_directory_EQ : Joined<["-"], "working-directory=">, Flags<[CC1Option]>,

View File

@ -42,7 +42,8 @@ class SanitizerArgs {
NeedsLeakDetection = Leak,
NeedsUbsanRt = Undefined | Integer,
NotAllowedWithTrap = Vptr,
HasZeroBaseShadow = Thread | Memory | DataFlow
HasZeroBaseShadow = Thread | Memory | DataFlow,
NeedsUnwindTables = Address | Thread | Memory | DataFlow
};
unsigned Kind;
@ -73,6 +74,7 @@ class SanitizerArgs {
bool hasZeroBaseShadow() const {
return (Kind & HasZeroBaseShadow) || AsanZeroBaseShadow;
}
bool needsUnwindTables() const { return Kind & NeedsUnwindTables; }
void addArgs(const llvm::opt::ArgList &Args,
llvm::opt::ArgStringList &CmdArgs) const;

View File

@ -11,6 +11,7 @@
#define CLANG_DRIVER_TOOLCHAIN_H_
#include "clang/Driver/Action.h"
#include "clang/Driver/Multilib.h"
#include "clang/Driver/Types.h"
#include "clang/Driver/Util.h"
#include "llvm/ADT/OwningPtr.h"
@ -76,6 +77,8 @@ private:
mutable OwningPtr<SanitizerArgs> SanitizerArguments;
protected:
MultilibSet Multilibs;
ToolChain(const Driver &D, const llvm::Triple &T,
const llvm::opt::ArgList &Args);
@ -130,6 +133,8 @@ public:
path_list &getProgramPaths() { return ProgramPaths; }
const path_list &getProgramPaths() const { return ProgramPaths; }
const MultilibSet &getMultilibs() const { return Multilibs; }
const SanitizerArgs& getSanitizerArgs() const;
// Tool access.

View File

@ -76,7 +76,8 @@ struct FormatStyle {
/// \brief Set whether & and * bind to the type as opposed to the variable.
bool PointerBindsToType;
/// \brief If \c true, analyze the formatted file for the most common binding.
/// \brief If \c true, analyze the formatted file for the most common binding
/// and use \c PointerBindsToType only as fallback.
bool DerivePointerBinding;
/// \brief The extra indent or outdent of access modifiers, e.g. \c public:.

View File

@ -64,6 +64,24 @@ class ASTDeserializationListener;
/// \brief Utility class for loading a ASTContext from an AST file.
///
class ASTUnit : public ModuleLoader {
public:
struct StandaloneFixIt {
std::pair<unsigned, unsigned> RemoveRange;
std::pair<unsigned, unsigned> InsertFromRange;
std::string CodeToInsert;
bool BeforePreviousInsertions;
};
struct StandaloneDiagnostic {
unsigned ID;
DiagnosticsEngine::Level Level;
std::string Message;
std::string Filename;
unsigned LocOffset;
std::vector<std::pair<unsigned, unsigned> > Ranges;
std::vector<StandaloneFixIt> FixIts;
};
private:
IntrusiveRefCntPtr<LangOptions> LangOpts;
IntrusiveRefCntPtr<DiagnosticsEngine> Diagnostics;
@ -75,7 +93,7 @@ private:
IntrusiveRefCntPtr<ASTContext> Ctx;
IntrusiveRefCntPtr<TargetOptions> TargetOpts;
IntrusiveRefCntPtr<HeaderSearchOptions> HSOpts;
ASTReader *Reader;
IntrusiveRefCntPtr<ASTReader> Reader;
bool HadModuleLoaderFatalFailure;
struct ASTWriterData;
@ -136,7 +154,7 @@ private:
std::string OriginalSourceFile;
/// \brief The set of diagnostics produced when creating the preamble.
SmallVector<StoredDiagnostic, 4> PreambleDiagnostics;
SmallVector<StandaloneDiagnostic, 4> PreambleDiagnostics;
/// \brief The set of diagnostics produced when creating this
/// translation unit.
@ -295,9 +313,9 @@ private:
const char **ArgBegin, const char **ArgEnd,
ASTUnit &AST, bool CaptureDiagnostics);
void TranslateStoredDiagnostics(ASTReader *MMan, StringRef ModName,
void TranslateStoredDiagnostics(FileManager &FileMgr,
SourceManager &SrcMan,
const SmallVectorImpl<StoredDiagnostic> &Diags,
const SmallVectorImpl<StandaloneDiagnostic> &Diags,
SmallVectorImpl<StoredDiagnostic> &Out);
void clearFileLevelDecls();

View File

@ -24,13 +24,13 @@ class ChainedIncludesSource : public ExternalSemaSource {
public:
virtual ~ChainedIncludesSource();
static ChainedIncludesSource *create(CompilerInstance &CI);
static IntrusiveRefCntPtr<ChainedIncludesSource> create(CompilerInstance &CI);
ExternalSemaSource &getFinalReader() const { return *FinalReader; }
private:
std::vector<CompilerInstance *> CIs;
OwningPtr<ExternalSemaSource> FinalReader;
IntrusiveRefCntPtr<ExternalSemaSource> FinalReader;
protected:

View File

@ -28,6 +28,7 @@ CODEGENOPT(Name, Bits, Default)
CODEGENOPT(Name, Bits, Default)
#endif
CODEGENOPT(DisableIntegratedAS, 1, 0) ///< -no-integrated-as
CODEGENOPT(Autolink , 1, 1) ///< -fno-autolink
CODEGENOPT(AsmVerbose , 1, 0) ///< -dA, -fverbose-asm.
CODEGENOPT(ObjCAutoRefCountExceptions , 1, 0) ///< Whether ARC should be EH-safe.

View File

@ -75,6 +75,9 @@ class CompilerInstance : public ModuleLoader {
/// The target being compiled for.
IntrusiveRefCntPtr<TargetInfo> Target;
/// The virtual file system.
IntrusiveRefCntPtr<vfs::FileSystem> VirtualFileSystem;
/// The file manager.
IntrusiveRefCntPtr<FileManager> FileMgr;
@ -99,8 +102,8 @@ class CompilerInstance : public ModuleLoader {
/// \brief The frontend timer
OwningPtr<llvm::Timer> FrontendTimer;
/// \brief Non-owning reference to the ASTReader, if one exists.
ASTReader *ModuleManager;
/// \brief The ASTReader, if one exists.
IntrusiveRefCntPtr<ASTReader> ModuleManager;
/// \brief The set of top-level modules that has already been loaded,
/// along with the module map
@ -313,6 +316,26 @@ public:
/// Replace the current diagnostics engine.
void setTarget(TargetInfo *Value);
/// }
/// @name Virtual File System
/// {
bool hasVirtualFileSystem() const { return VirtualFileSystem != 0; }
vfs::FileSystem &getVirtualFileSystem() const {
assert(hasVirtualFileSystem() &&
"Compiler instance has no virtual file system");
return *VirtualFileSystem;
}
/// \brief Replace the current virtual file system.
///
/// \note Most clients should use setFileManager, which will implicitly reset
/// the virtual file system to the one contained in the file manager.
void setVirtualFileSystem(IntrusiveRefCntPtr<vfs::FileSystem> FS) {
VirtualFileSystem = FS;
}
/// }
/// @name File Manager
/// {
@ -330,7 +353,7 @@ public:
FileMgr.resetWithoutRelease();
}
/// setFileManager - Replace the current file manager.
/// \brief Replace the current file manager and virtual file system.
void setFileManager(FileManager *Value);
/// }
@ -431,8 +454,8 @@ public:
/// @name Module Management
/// {
ASTReader *getModuleManager() const { return ModuleManager; }
void setModuleManager(ASTReader *Reader) { ModuleManager = Reader; }
IntrusiveRefCntPtr<ASTReader> getModuleManager() const;
void setModuleManager(IntrusiveRefCntPtr<ASTReader> Reader);
/// }
/// @name Code Completion

View File

@ -123,6 +123,17 @@ inline int getLastArgIntValue(const llvm::opt::ArgList &Args,
return getLastArgIntValue(Args, Id, Default, &Diags);
}
uint64_t getLastArgUInt64Value(const llvm::opt::ArgList &Args,
llvm::opt::OptSpecifier Id, uint64_t Default,
DiagnosticsEngine *Diags = 0);
inline uint64_t getLastArgUInt64Value(const llvm::opt::ArgList &Args,
llvm::opt::OptSpecifier Id,
uint64_t Default,
DiagnosticsEngine &Diags) {
return getLastArgUInt64Value(Args, Id, Default, &Diags);
}
// When Clang->getFrontendOpts().DisableFree is set we don't delete some of the
// global objects, but we don't want LeakDetectors to complain, so we bury them
// in a globally visible array.

View File

@ -2,4 +2,4 @@ clang_tablegen(AttrSpellings.inc -gen-clang-attr-spelling-list
-I ${CMAKE_CURRENT_SOURCE_DIR}/../../
SOURCE ../Basic/Attr.td
TARGET ClangAttrSpellings
DEPENDS AttrSpellings.inc)
)

View File

@ -161,11 +161,16 @@ public:
/// \param [out] InUserSpecifiedSystemFramework If the file is found,
/// set to true if the file is located in a framework that has been
/// user-specified to be treated as a system framework.
const FileEntry *LookupFile(StringRef Filename, HeaderSearch &HS,
///
/// \param [out] MappedName if this is a headermap which maps the filename to
/// a framework include ("Foo.h" -> "Foo/Foo.h"), set the new name to this
/// vector and point Filename to it.
const FileEntry *LookupFile(StringRef &Filename, HeaderSearch &HS,
SmallVectorImpl<char> *SearchPath,
SmallVectorImpl<char> *RelativePath,
ModuleMap::KnownHeader *SuggestedModule,
bool &InUserSpecifiedSystemFramework) const;
bool &InUserSpecifiedSystemFramework,
SmallVectorImpl<char> &MappedName) const;
private:
const FileEntry *DoFrameworkLookup(

View File

@ -55,6 +55,11 @@ public:
/// "../../file.h".
const FileEntry *LookupFile(StringRef Filename, FileManager &FM) const;
/// If the specified relative filename is located in this HeaderMap return
/// the filename it is mapped to, otherwise return an empty StringRef.
StringRef lookupFilename(StringRef Filename,
SmallVectorImpl<char> &DestPath) const;
/// getFileName - Return the filename of the headermap.
const char *getFileName() const;

View File

@ -116,6 +116,12 @@ public:
/// regenerated often.
unsigned ModuleCachePruneAfter;
/// \brief The time in seconds when the build session started.
///
/// This time is used by other optimizations in header search and module
/// loading.
uint64_t BuildSessionTimestamp;
/// \brief The set of macro names that should be ignored for the purposes
/// of computing the module hash.
llvm::SetVector<std::string> ModulesIgnoreMacros;
@ -123,6 +129,9 @@ public:
/// \brief The set of user-provided module-map-files.
llvm::SetVector<std::string> ModuleMapFiles;
/// \brief The set of user-provided virtual filesystem overlay files.
std::vector<std::string> VFSOverlayFiles;
/// Include the compiler builtin includes.
unsigned UseBuiltinIncludes : 1;
@ -138,14 +147,21 @@ public:
/// Whether header search information should be output as for -v.
unsigned Verbose : 1;
/// \brief If true, skip verifying input files used by modules if the
/// module was already verified during this build session (see
/// \c BuildSessionTimestamp).
unsigned ModulesValidateOncePerBuildSession : 1;
public:
HeaderSearchOptions(StringRef _Sysroot = "/")
: Sysroot(_Sysroot), DisableModuleHash(0), ModuleMaps(0),
ModuleCachePruneInterval(7*24*60*60),
ModuleCachePruneAfter(31*24*60*60),
BuildSessionTimestamp(0),
UseBuiltinIncludes(true),
UseStandardSystemIncludes(true), UseStandardCXXIncludes(true),
UseLibcxx(false), Verbose(false) {}
UseLibcxx(false), Verbose(false),
ModulesValidateOncePerBuildSession(false) {}
/// AddPath - Add the \p Path path to the specified \p Group list.
void AddPath(StringRef Path, frontend::IncludeDirGroup Group,
@ -159,6 +175,10 @@ public:
void AddSystemHeaderPrefix(StringRef Prefix, bool IsSystemHeader) {
SystemHeaderPrefixes.push_back(SystemHeaderPrefix(Prefix, IsSystemHeader));
}
void AddVFSOverlayFile(StringRef Name) {
VFSOverlayFiles.push_back(Name);
}
};
} // end namespace clang

View File

@ -614,8 +614,28 @@ private:
/// \return The Unicode codepoint specified by the UCN, or 0 if the UCN is
/// invalid.
uint32_t tryReadUCN(const char *&CurPtr, const char *SlashLoc, Token *Tok);
};
/// \brief Try to consume a UCN as part of an identifier at the current
/// location.
/// \param CurPtr Initially points to the range of characters in the source
/// buffer containing the '\'. Updated to point past the end of
/// the UCN on success.
/// \param Size The number of characters occupied by the '\' (including
/// trigraphs and escaped newlines).
/// \param Result The token being produced. Marked as containing a UCN on
/// success.
/// \return \c true if a UCN was lexed and it produced an acceptable
/// identifier character, \c false otherwise.
bool tryConsumeIdentifierUCN(const char *&CurPtr, unsigned Size,
Token &Result);
/// \brief Try to consume an identifier character encoded in UTF-8.
/// \param CurPtr Points to the start of the (potential) UTF-8 code unit
/// sequence. On success, updated to point past the end of it.
/// \return \c true if a UTF-8 sequence mapping to an acceptable identifier
/// character was lexed, \c false otherwise.
bool tryConsumeIdentifierUTF8Char(const char *&CurPtr);
};
} // end namespace clang

View File

@ -33,6 +33,9 @@ class TargetInfo;
class SourceManager;
class LangOptions;
/// Copy characters from Input to Buf, expanding any UCNs.
void expandUCNs(SmallVectorImpl<char> &Buf, StringRef Input);
/// NumericLiteralParser - This performs strict semantic analysis of the content
/// of a ppnumber, classifying it as either integer, floating, or erroneous,
/// determines the radix of the value and can convert it to a useful value.
@ -48,6 +51,8 @@ class NumericLiteralParser {
bool saw_exponent, saw_period, saw_ud_suffix;
SmallString<32> UDSuffixBuf;
public:
NumericLiteralParser(StringRef TokSpelling,
SourceLocation TokLoc,
@ -72,7 +77,7 @@ public:
}
StringRef getUDSuffix() const {
assert(saw_ud_suffix);
return StringRef(SuffixBegin, ThisTokEnd - SuffixBegin);
return UDSuffixBuf;
}
unsigned getUDSuffixOffset() const {
assert(saw_ud_suffix);

View File

@ -803,6 +803,11 @@ public:
while (Result.getKind() == tok::comment);
}
/// \brief Parses a simple integer literal to get its numeric value. Floating
/// point literals and user defined literals are rejected. Used primarily to
/// handle pragmas that accept integer arguments.
bool parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value);
/// Disables macro expansion everywhere except for preprocessor directives.
void SetMacroExpansionOnlyInDirectives() {
DisableMacroExpansion = true;

View File

@ -40,7 +40,6 @@ namespace clang {
class ParsingDeclSpec;
class ParsingDeclarator;
class ParsingFieldDeclarator;
class PragmaUnusedHandler;
class ColonProtectionRAIIObject;
class InMessageExpressionRAIIObject;
class PoisonSEHIdentifiersRAIIObject;
@ -52,7 +51,6 @@ namespace clang {
/// been read.
///
class Parser : public CodeCompletionHandler {
friend class PragmaUnusedHandler;
friend class ColonProtectionRAIIObject;
friend class InMessageExpressionRAIIObject;
friend class PoisonSEHIdentifiersRAIIObject;
@ -151,11 +149,13 @@ class Parser : public CodeCompletionHandler {
OwningPtr<PragmaHandler> RedefineExtnameHandler;
OwningPtr<PragmaHandler> FPContractHandler;
OwningPtr<PragmaHandler> OpenCLExtensionHandler;
OwningPtr<CommentHandler> CommentSemaHandler;
OwningPtr<PragmaHandler> OpenMPHandler;
OwningPtr<PragmaHandler> MSCommentHandler;
OwningPtr<PragmaHandler> MSDetectMismatchHandler;
OwningPtr<PragmaHandler> MSPointersToMembers;
OwningPtr<PragmaHandler> MSVtorDisp;
OwningPtr<CommentHandler> CommentSemaHandler;
/// Whether the '>' token acts as an operator or not. This will be
/// true except when we are parsing an expression within a C++
@ -169,7 +169,7 @@ class Parser : public CodeCompletionHandler {
/// ColonProtectionRAIIObject RAII object.
bool ColonIsSacred;
/// \brief When true, we are directly inside an Objective-C messsage
/// \brief When true, we are directly inside an Objective-C message
/// send expression.
///
/// This is managed by the \c InMessageExpressionRAIIObject class, and
@ -439,6 +439,12 @@ private:
Kind == tok::annot_module_end || Kind == tok::annot_module_include;
}
/// \brief Initialize all pragma handlers.
void initializePragmaHandlers();
/// \brief Destroy and reset all pragma handlers.
void resetPragmaHandlers();
/// \brief Handle the annotation token produced for #pragma unused(...)
void HandlePragmaUnused();
@ -460,6 +466,8 @@ private:
void HandlePragmaMSPointersToMembers();
void HandlePragmaMSVtorDisp();
/// \brief Handle the annotation token produced for
/// #pragma align...
void HandlePragmaAlign();

View File

@ -693,40 +693,6 @@ public:
}
};
/// addAttributeLists - Add two AttributeLists together
/// The right-hand list is appended to the left-hand list, if any
/// A pointer to the joined list is returned.
/// Note: the lists are not left unmodified.
inline AttributeList *addAttributeLists(AttributeList *Left,
AttributeList *Right) {
if (!Left)
return Right;
AttributeList *next = Left, *prev;
do {
prev = next;
next = next->getNext();
} while (next);
prev->setNext(Right);
return Left;
}
/// CXX11AttributeList - A wrapper around a C++11 attribute list.
/// Stores, in addition to the list proper, whether or not an actual list was
/// (as opposed to an empty list, which may be ill-formed in some places) and
/// the source range of the list.
struct CXX11AttributeList {
AttributeList *AttrList;
SourceRange Range;
bool HasAttr;
CXX11AttributeList (AttributeList *attrList, SourceRange range, bool hasAttr)
: AttrList(attrList), Range(range), HasAttr (hasAttr) {
}
CXX11AttributeList ()
: AttrList(0), Range(), HasAttr(false) {
}
};
/// ParsedAttributes - A collection of parsed attributes. Currently
/// we don't differentiate between the various attribute syntaxes,
/// which is basically silly.

View File

@ -831,8 +831,8 @@ private:
// NOTE: VC++ treats enums as signed, avoid using ObjCPropertyAttributeKind
unsigned PropertyAttributes : 12;
IdentifierInfo *GetterName; // getter name of NULL if no getter
IdentifierInfo *SetterName; // setter name of NULL if no setter
IdentifierInfo *GetterName; // getter name or NULL if no getter
IdentifierInfo *SetterName; // setter name or NULL if no setter
};
/// \brief Represents a C++ unqualified-id that has been parsed.
@ -1115,7 +1115,8 @@ struct DeclaratorChunk {
};
/// ParamInfo - An array of paraminfo objects is allocated whenever a function
/// declarator is parsed. There are two interesting styles of arguments here:
/// declarator is parsed. There are two interesting styles of parameters
/// here:
/// K&R-style identifier lists and parameter type lists. K&R-style identifier
/// lists will have information about the identifier, but no type information.
/// Parameter type lists will have type info (if the actions module provides
@ -1147,7 +1148,7 @@ struct DeclaratorChunk {
struct FunctionTypeInfo : TypeInfoCommon {
/// hasPrototype - This is true if the function had at least one typed
/// argument. If the function is () or (a,b,c), then it has no prototype,
/// parameter. If the function is () or (a,b,c), then it has no prototype,
/// and is treated as a K&R-style function.
unsigned hasPrototype : 1;
@ -1170,8 +1171,8 @@ struct DeclaratorChunk {
/// ExceptionSpecType - An ExceptionSpecificationType value.
unsigned ExceptionSpecType : 3;
/// DeleteArgInfo - If this is true, we need to delete[] ArgInfo.
unsigned DeleteArgInfo : 1;
/// DeleteParams - If this is true, we need to delete[] Params.
unsigned DeleteParams : 1;
/// HasTrailingReturnType - If this is true, a trailing return type was
/// specified.
@ -1186,9 +1187,9 @@ struct DeclaratorChunk {
/// The location of the right parenthesis in the source.
unsigned RParenLoc;
/// NumArgs - This is the number of formal arguments provided for the
/// NumParams - This is the number of formal parameters specified by the
/// declarator.
unsigned NumArgs;
unsigned NumParams;
/// NumExceptions - This is the number of types in the dynamic-exception-
/// decl, if the function has one.
@ -1216,10 +1217,10 @@ struct DeclaratorChunk {
/// \brief The location of the keyword introducing the spec, if any.
unsigned ExceptionSpecLoc;
/// ArgInfo - This is a pointer to a new[]'d array of ParamInfo objects that
/// describe the arguments for this function declarator. This is null if
/// there are no arguments specified.
ParamInfo *ArgInfo;
/// Params - This is a pointer to a new[]'d array of ParamInfo objects that
/// describe the parameters specified by this function declarator. null if
/// there are no parameters specified.
ParamInfo *Params;
union {
/// \brief Pointer to a new[]'d array of TypeAndRange objects that
@ -1236,30 +1237,28 @@ struct DeclaratorChunk {
/// type specified.
UnionParsedType TrailingReturnType;
/// \brief Reset the argument list to having zero arguments.
/// \brief Reset the parameter list to having zero parameters.
///
/// This is used in various places for error recovery.
void freeArgs() {
if (DeleteArgInfo) {
delete[] ArgInfo;
DeleteArgInfo = false;
void freeParams() {
if (DeleteParams) {
delete[] Params;
DeleteParams = false;
}
NumArgs = 0;
NumParams = 0;
}
void destroy() {
if (DeleteArgInfo)
delete[] ArgInfo;
if (DeleteParams)
delete[] Params;
if (getExceptionSpecType() == EST_Dynamic)
delete[] Exceptions;
}
/// isKNRPrototype - Return true if this is a K&R style identifier list,
/// like "void foo(a,b,c)". In a function definition, this will be followed
/// by the argument type definitions.
bool isKNRPrototype() const {
return !hasPrototype && NumArgs != 0;
}
/// by the parameter type definitions.
bool isKNRPrototype() const { return !hasPrototype && NumParams != 0; }
SourceLocation getLParenLoc() const {
return SourceLocation::getFromRawEncoding(LParenLoc);
@ -1428,7 +1427,7 @@ struct DeclaratorChunk {
static DeclaratorChunk getFunction(bool hasProto,
bool isAmbiguous,
SourceLocation LParenLoc,
ParamInfo *ArgInfo, unsigned NumArgs,
ParamInfo *Params, unsigned NumParams,
SourceLocation EllipsisLoc,
SourceLocation RParenLoc,
unsigned TypeQuals,

View File

@ -262,15 +262,28 @@ public:
bool MSStructPragmaOn; // True when \#pragma ms_struct on
enum PragmaMSPointersToMembersKind {
PPTMK_BestCase,
PPTMK_FullGeneralitySingleInheritance,
PPTMK_FullGeneralityMultipleInheritance,
PPTMK_FullGeneralityVirtualInheritance
/// \brief Controls member pointer representation format under the MS ABI.
LangOptions::PragmaMSPointersToMembersKind
MSPointerToMemberRepresentationMethod;
enum PragmaVtorDispKind {
PVDK_Push, ///< #pragma vtordisp(push, mode)
PVDK_Set, ///< #pragma vtordisp(mode)
PVDK_Pop, ///< #pragma vtordisp(pop)
PVDK_Reset ///< #pragma vtordisp()
};
/// \brief Controls member pointer representation format under the MS ABI.
PragmaMSPointersToMembersKind MSPointerToMemberRepresentationMethod;
/// \brief Whether to insert vtordisps prior to virtual bases in the Microsoft
/// C++ ABI. Possible values are 0, 1, and 2, which mean:
///
/// 0: Suppress all vtordisps
/// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
/// structors
/// 2: Always insert vtordisps to support RTTI on partially constructed
/// objects
///
/// The stack always has at least one element in it.
SmallVector<MSVtorDispAttr::Mode, 2> VtorDispModeStack;
/// \brief Source location for newly created implicit MSInheritanceAttrs
SourceLocation ImplicitMSInheritanceAttrLoc;
@ -1315,11 +1328,6 @@ public:
/// function to pin them on. ActOnFunctionDeclarator reads this list and patches
/// them into the FunctionDecl.
std::vector<NamedDecl*> DeclsInPrototypeScope;
/// Nonzero if we are currently parsing a function declarator. This is a counter
/// as opposed to a boolean so we can deal with nested function declarators
/// such as:
/// void f(void (*g)(), ...)
unsigned InFunctionDeclarator;
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = 0);
@ -1341,7 +1349,8 @@ public:
SourceLocation IILoc,
Scope *S,
CXXScopeSpec *SS,
ParsedType &SuggestedType);
ParsedType &SuggestedType,
bool AllowClassTemplates = false);
/// \brief Describes the result of the name lookup and resolution performed
/// by \c ClassifyName().
@ -1498,8 +1507,6 @@ public:
void CheckVariableDeclarationType(VarDecl *NewVD);
void CheckCompleteVariableDeclaration(VarDecl *var);
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
void ActOnStartFunctionDeclarator();
void ActOnEndFunctionDeclarator();
NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
TypeSourceInfo *TInfo,
@ -1507,7 +1514,6 @@ public:
MultiTemplateParamsArg TemplateParamLists,
bool &AddToScope);
bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
void checkVoidParamDecl(ParmVarDecl *Param);
bool CheckConstexprFunctionDecl(const FunctionDecl *FD);
bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body);
@ -2645,7 +2651,8 @@ public:
/// DiagnoseUnimplementedProperties - This routine warns on those properties
/// which must be implemented by this implementation.
void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
ObjCContainerDecl *CDecl);
ObjCContainerDecl *CDecl,
bool SynthesizeProperties);
/// DefaultSynthesizeProperties - This routine default synthesizes all
/// properties which must be synthesized in the class's \@implementation.
@ -2653,12 +2660,6 @@ public:
ObjCInterfaceDecl *IDecl);
void DefaultSynthesizeProperties(Scope *S, Decl *D);
/// CollectImmediateProperties - This routine collects all properties in
/// the class and its conforming protocols; but not those it its super class.
void CollectImmediateProperties(ObjCContainerDecl *CDecl,
llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*>& PropMap,
llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*>& SuperPropMap);
/// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
/// an ivar synthesized for 'Method' and 'Method' is a property accessor
/// declared in class 'IFace'.
@ -4647,8 +4648,7 @@ public:
//
Decl *ActOnStartLinkageSpecification(Scope *S,
SourceLocation ExternLoc,
SourceLocation LangLoc,
StringRef Lang,
Expr *LangStr,
SourceLocation LBraceLoc);
Decl *ActOnFinishLinkageSpecification(Scope *S,
Decl *LinkageSpec,
@ -6986,8 +6986,13 @@ public:
/// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
/// pointers_to_members(representation method[, general purpose
/// representation]).
void ActOnPragmaMSPointersToMembers(PragmaMSPointersToMembersKind Kind,
SourceLocation PragmaLoc);
void ActOnPragmaMSPointersToMembers(
LangOptions::PragmaMSPointersToMembersKind Kind,
SourceLocation PragmaLoc);
/// \brief Called on well formed \#pragma vtordisp().
void ActOnPragmaMSVtorDisp(PragmaVtorDispKind Kind, SourceLocation PragmaLoc,
MSVtorDispAttr::Mode Value);
/// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
void ActOnPragmaDetectMismatch(StringRef Name, StringRef Value);
@ -7106,6 +7111,22 @@ public:
Stmt *AStmt,
SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp simd' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt,
SourceLocation StartLoc,
SourceLocation EndLoc);
OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
Expr *Expr,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'if' clause.
OMPClause *ActOnOpenMPIfClause(Expr *Condition, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
unsigned Argument,
@ -7175,6 +7196,10 @@ public:
// functions and arrays to their respective pointers (C99 6.3.2.1).
ExprResult UsualUnaryConversions(Expr *E);
/// CallExprUnaryConversions - a special case of an unary conversion
/// performed on a function designator of a call expression.
ExprResult CallExprUnaryConversions(Expr *E);
// DefaultFunctionArrayConversion - converts functions and arrays
// to their respective pointers (C99 6.3.2.1).
ExprResult DefaultFunctionArrayConversion(Expr *E);
@ -7224,6 +7249,9 @@ public:
/// function, issuing a diagnostic if not.
void checkVariadicArgument(const Expr *E, VariadicCallType CT);
/// Check to see if a given expression could have '.c_str()' called on it.
bool hasCStrMethod(const Expr *E);
/// GatherArgumentsForCall - Collector argument expressions for various
/// form of call prototypes.
bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
@ -7451,6 +7479,10 @@ public:
bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
SourceLocation QuestionLoc);
void DiagnoseAlwaysNonNullPointer(Expr *E,
Expr::NullPointerConstantKind NullType,
bool IsEqual, SourceRange Range);
/// type checking for vector binary operators.
QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
SourceLocation Loc, bool IsCompAssign);
@ -7860,10 +7892,12 @@ private:
ExprResult CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool SemaBuiltinVAStart(CallExpr *TheCall);
bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
@ -7878,6 +7912,7 @@ public:
private:
bool SemaBuiltinPrefetch(CallExpr *TheCall);
bool SemaBuiltinMMPrefetch(CallExpr *TheCall);
bool SemaBuiltinObjectSize(CallExpr *TheCall);
bool SemaBuiltinLongjmp(CallExpr *TheCall);
ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
@ -7919,6 +7954,10 @@ private:
SourceLocation Loc, SourceRange range,
llvm::SmallBitVector &CheckedVarArgs);
void CheckAbsoluteValueFunction(const CallExpr *Call,
const FunctionDecl *FDecl,
IdentifierInfo *FnInfo);
void CheckMemaccessArguments(const CallExpr *Call,
unsigned BId,
IdentifierInfo *FnName);

View File

@ -305,13 +305,16 @@ public:
class FunctionCallFilterCCC : public CorrectionCandidateCallback {
public:
FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
bool HasExplicitTemplateArgs);
bool HasExplicitTemplateArgs,
bool AllowNonStaticMethods = true);
virtual bool ValidateCandidate(const TypoCorrection &candidate);
private:
unsigned NumArgs;
bool HasExplicitTemplateArgs;
bool AllowNonStaticMethods;
DeclContext *CurContext;
};
// @brief Callback class that effectively disabled typo correction

View File

@ -1333,6 +1333,7 @@ namespace clang {
// OpenMP drectives
STMT_OMP_PARALLEL_DIRECTIVE,
STMT_OMP_SIMD_DIRECTIVE,
// ARC
EXPR_OBJC_BRIDGED_CAST, // ObjCBridgedCastExpr

View File

@ -64,6 +64,7 @@ class ASTUnit; // FIXME: Layering violation and egregious hack.
class Attr;
class Decl;
class DeclContext;
class DefMacroDirective;
class DiagnosticOptions;
class NestedNameSpecifier;
class CXXBaseSpecifier;
@ -471,18 +472,22 @@ private:
/// global submodule ID to produce a local ID.
GlobalSubmoduleMapType GlobalSubmoduleMap;
/// \brief Information on a macro definition or undefinition that is visible
/// at the end of a submodule.
struct ModuleMacroInfo;
/// \brief An entity that has been hidden.
class HiddenName {
public:
enum NameKind {
Declaration,
MacroVisibility
Macro
} Kind;
private:
union {
Decl *D;
MacroDirective *MD;
ModuleMacroInfo *MMI;
};
IdentifierInfo *Id;
@ -490,8 +495,8 @@ private:
public:
HiddenName(Decl *D) : Kind(Declaration), D(D), Id() { }
HiddenName(IdentifierInfo *II, MacroDirective *MD)
: Kind(MacroVisibility), MD(MD), Id(II) { }
HiddenName(IdentifierInfo *II, ModuleMacroInfo *MMI)
: Kind(Macro), MMI(MMI), Id(II) { }
NameKind getKind() const { return Kind; }
@ -500,15 +505,21 @@ private:
return D;
}
std::pair<IdentifierInfo *, MacroDirective *> getMacro() const {
assert(getKind() == MacroVisibility && "Hidden name is not a macro!");
return std::make_pair(Id, MD);
std::pair<IdentifierInfo *, ModuleMacroInfo *> getMacro() const {
assert(getKind() == Macro && "Hidden name is not a macro!");
return std::make_pair(Id, MMI);
}
};
typedef llvm::SmallDenseMap<IdentifierInfo*,
ModuleMacroInfo*> HiddenMacrosMap;
/// \brief A set of hidden declarations.
typedef SmallVector<HiddenName, 2> HiddenNames;
struct HiddenNames {
SmallVector<Decl*, 2> HiddenDecls;
HiddenMacrosMap HiddenMacros;
};
typedef llvm::DenseMap<Module *, HiddenNames> HiddenNamesMapType;
/// \brief A mapping from each of the hidden submodules to the deserialized
@ -564,8 +575,8 @@ private:
ModuleFile *M;
struct ModuleMacroDataTy {
serialization::GlobalMacroID GMacID;
unsigned ImportLoc;
uint32_t MacID;
serialization::SubmoduleID *Overrides;
};
struct PCHMacroDataTy {
uint64_t MacroDirectivesOffset;
@ -577,10 +588,10 @@ private:
};
PendingMacroInfo(ModuleFile *M,
serialization::GlobalMacroID GMacID,
SourceLocation ImportLoc) : M(M) {
ModuleMacroData.GMacID = GMacID;
ModuleMacroData.ImportLoc = ImportLoc.getRawEncoding();
uint32_t MacID,
serialization::SubmoduleID *Overrides) : M(M) {
ModuleMacroData.MacID = MacID;
ModuleMacroData.Overrides = Overrides;
}
PendingMacroInfo(ModuleFile *M, uint64_t MacroDirectivesOffset) : M(M) {
@ -1253,14 +1264,14 @@ public:
/// \param ImportLoc The location at which the import occurs.
///
/// \param Complain Whether to complain about conflicting module imports.
void makeModuleVisible(Module *Mod,
void makeModuleVisible(Module *Mod,
Module::NameVisibilityKind NameVisibility,
SourceLocation ImportLoc,
bool Complain);
/// \brief Make the names within this set of hidden names visible.
void makeNamesVisible(const HiddenNames &Names, Module *Owner);
/// \brief Set the AST callbacks listener.
void setListener(ASTReaderListener *listener) {
Listener.reset(listener);
@ -1687,14 +1698,27 @@ public:
serialization::IdentifierID getGlobalIdentifierID(ModuleFile &M,
unsigned LocalID);
ModuleMacroInfo *getModuleMacro(const PendingMacroInfo &PMInfo);
void resolvePendingMacro(IdentifierInfo *II, const PendingMacroInfo &PMInfo);
void installPCHMacroDirectives(IdentifierInfo *II,
ModuleFile &M, uint64_t Offset);
void installImportedMacro(IdentifierInfo *II, MacroDirective *MD,
void installImportedMacro(IdentifierInfo *II, ModuleMacroInfo *MMI,
Module *Owner);
typedef llvm::SmallVector<DefMacroDirective*, 1> AmbiguousMacros;
llvm::DenseMap<IdentifierInfo*, AmbiguousMacros> AmbiguousMacroDefs;
void
removeOverriddenMacros(IdentifierInfo *II, AmbiguousMacros &Ambig,
llvm::ArrayRef<serialization::SubmoduleID> Overrides);
AmbiguousMacros *
removeOverriddenMacros(IdentifierInfo *II,
llvm::ArrayRef<serialization::SubmoduleID> Overrides);
/// \brief Retrieve the macro with the given ID.
MacroInfo *getMacro(serialization::MacroID ID);
@ -1875,7 +1899,7 @@ public:
void addPendingMacroFromModule(IdentifierInfo *II,
ModuleFile *M,
serialization::GlobalMacroID GMacID,
SourceLocation ImportLoc);
llvm::ArrayRef<serialization::SubmoduleID>);
/// \brief Add a macro to deserialize its macro directive history from a PCH.
///

View File

@ -115,6 +115,10 @@ public:
/// \brief The file name of the module file.
std::string FileName;
std::string getTimestampFilename() const {
return FileName + ".timestamp";
}
/// \brief The original source file name that was used to build the
/// primary AST file, which may have been modified for
/// relocatable-pch support.
@ -167,6 +171,9 @@ public:
/// If module A depends on and imports module B, both modules will have the
/// same DirectImportLoc, but different ImportLoc (B's ImportLoc will be a
/// source location inside module A).
///
/// WARNING: This is largely useless. It doesn't tell you when a module was
/// made visible, just when the first submodule of that module was imported.
SourceLocation DirectImportLoc;
/// \brief The source location where this module was first imported.
@ -185,6 +192,12 @@ public:
/// \brief The input files that have been loaded from this AST file.
std::vector<InputFile> InputFilesLoaded;
/// \brief If non-zero, specifies the time when we last validated input
/// files. Zero means we never validated them.
///
/// The time is specified in seconds since the start of the Epoch.
uint64_t InputFilesValidationTimestamp;
// === Source Locations ===
/// \brief Cursor used to read source location entries.

View File

@ -19,6 +19,7 @@
#include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
#include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitor.h"
#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
#include "clang/StaticAnalyzer/Core/CheckerManager.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/FoldingSet.h"
@ -463,7 +464,12 @@ public:
/// reports.
void emitReport(BugReport *R);
void EmitBasicReport(const Decl *DeclWithIssue,
void EmitBasicReport(const Decl *DeclWithIssue, const CheckerBase *Checker,
StringRef BugName, StringRef BugCategory,
StringRef BugStr, PathDiagnosticLocation Loc,
ArrayRef<SourceRange> Ranges = None);
void EmitBasicReport(const Decl *DeclWithIssue, CheckName CheckName,
StringRef BugName, StringRef BugCategory,
StringRef BugStr, PathDiagnosticLocation Loc,
ArrayRef<SourceRange> Ranges = None);
@ -473,7 +479,8 @@ private:
/// \brief Returns a BugType that is associated with the given name and
/// category.
BugType *getBugTypeForName(StringRef name, StringRef category);
BugType *getBugTypeForName(CheckName CheckName, StringRef name,
StringRef category);
};
// FIXME: Get rid of GRBugReporter. It's the wrong abstraction.

View File

@ -16,6 +16,7 @@
#include "clang/Basic/LLVM.h"
#include "clang/StaticAnalyzer/Core/BugReporter/CommonBugCategories.h"
#include "clang/StaticAnalyzer/Core/Checker.h"
#include "llvm/ADT/FoldingSet.h"
#include <string>
@ -29,20 +30,25 @@ class ExprEngine;
class BugType {
private:
const CheckName Check;
const std::string Name;
const std::string Category;
bool SuppressonSink;
virtual void anchor();
public:
BugType(StringRef name, StringRef cat)
: Name(name), Category(cat), SuppressonSink(false) {}
BugType(class CheckName check, StringRef name, StringRef cat)
: Check(check), Name(name), Category(cat), SuppressonSink(false) {}
BugType(const CheckerBase *checker, StringRef name, StringRef cat)
: Check(checker->getCheckName()), Name(name), Category(cat),
SuppressonSink(false) {}
virtual ~BugType() {}
// FIXME: Should these be made strings as well?
StringRef getName() const { return Name; }
StringRef getCategory() const { return Category; }
StringRef getCheckName() const { return Check.getName(); }
/// isSuppressOnSink - Returns true if bug reports associated with this bug
/// type should be suppressed if the end node of the report is post-dominated
/// by a sink node.
@ -56,12 +62,16 @@ class BuiltinBug : public BugType {
const std::string desc;
virtual void anchor();
public:
BuiltinBug(const char *name, const char *description)
: BugType(name, categories::LogicError), desc(description) {}
BuiltinBug(const char *name)
: BugType(name, categories::LogicError), desc(name) {}
BuiltinBug(class CheckName check, const char *name, const char *description)
: BugType(check, name, categories::LogicError), desc(description) {}
BuiltinBug(const CheckerBase *checker, const char *name,
const char *description)
: BugType(checker, name, categories::LogicError), desc(description) {}
BuiltinBug(const CheckerBase *checker, const char *name)
: BugType(checker, name, categories::LogicError), desc(name) {}
StringRef getDescription() const { return desc; }
};

View File

@ -710,6 +710,7 @@ public:
/// diagnostic. It represents an ordered-collection of PathDiagnosticPieces,
/// each which represent the pieces of the path.
class PathDiagnostic : public llvm::FoldingSetNode {
std::string CheckName;
const Decl *DeclWithIssue;
std::string BugType;
std::string VerboseDesc;
@ -730,8 +731,8 @@ class PathDiagnostic : public llvm::FoldingSetNode {
PathDiagnostic() LLVM_DELETED_FUNCTION;
public:
PathDiagnostic(const Decl *DeclWithIssue, StringRef bugtype,
StringRef verboseDesc, StringRef shortDesc,
PathDiagnostic(StringRef CheckName, const Decl *DeclWithIssue,
StringRef bugtype, StringRef verboseDesc, StringRef shortDesc,
StringRef category, PathDiagnosticLocation LocationToUnique,
const Decl *DeclToUnique);
@ -788,6 +789,7 @@ public:
StringRef getShortDescription() const {
return ShortDesc.empty() ? VerboseDesc : ShortDesc;
}
StringRef getCheckName() const { return CheckName; }
StringRef getBugType() const { return BugType; }
StringRef getCategory() const { return Category; }

View File

@ -453,14 +453,29 @@ public:
} // end eval namespace
class CheckerBase : public ProgramPointTag {
CheckName Name;
friend class ::clang::ento::CheckerManager;
public:
StringRef getTagDescription() const;
CheckName getCheckName() const;
/// See CheckerManager::runCheckersForPrintState.
virtual void printState(raw_ostream &Out, ProgramStateRef State,
const char *NL, const char *Sep) const { }
};
/// Dump checker name to stream.
raw_ostream& operator<<(raw_ostream &Out, const CheckerBase &Checker);
/// Tag that can use a checker name as a message provider
/// (see SimpleProgramPointTag).
class CheckerProgramPointTag : public SimpleProgramPointTag {
public:
CheckerProgramPointTag(StringRef CheckerName, StringRef Msg);
CheckerProgramPointTag(const CheckerBase *Checker, StringRef Msg);
};
template <typename CHECK1, typename CHECK2=check::_VoidCheck,
typename CHECK3=check::_VoidCheck, typename CHECK4=check::_VoidCheck,
typename CHECK5=check::_VoidCheck, typename CHECK6=check::_VoidCheck,

View File

@ -29,6 +29,7 @@ namespace clang {
namespace ento {
class CheckerBase;
class CheckerRegistry;
class ExprEngine;
class AnalysisManager;
class BugReporter;
@ -131,9 +132,26 @@ enum PointerEscapeKind {
PSK_EscapeOther
};
// This wrapper is used to ensure that only StringRefs originating from the
// CheckerRegistry are used as check names. We want to make sure all check
// name strings have a lifetime that keeps them alive at least until the path
// diagnostics have been processed.
class CheckName {
StringRef Name;
friend class ::clang::ento::CheckerRegistry;
explicit CheckName(StringRef Name) : Name(Name) {}
public:
CheckName() {}
CheckName(const CheckName &Other) : Name(Other.Name) {}
StringRef getName() const { return Name; }
};
class CheckerManager {
const LangOptions LangOpts;
AnalyzerOptionsRef AOptions;
CheckName CurrentCheckName;
public:
CheckerManager(const LangOptions &langOpts,
AnalyzerOptionsRef AOptions)
@ -142,6 +160,9 @@ public:
~CheckerManager();
void setCurrentCheckName(CheckName name) { CurrentCheckName = name; }
CheckName getCurrentCheckName() const { return CurrentCheckName; }
bool hasPathSensitiveCheckers() const;
void finishedCheckerRegistration();
@ -168,6 +189,7 @@ public:
return static_cast<CHECKER *>(ref); // already registered.
CHECKER *checker = new CHECKER();
checker->Name = CurrentCheckName;
CheckerDtors.push_back(CheckerDtor(checker, destruct<CHECKER>));
CHECKER::_register(checker, *this);
ref = checker;
@ -182,6 +204,7 @@ public:
return static_cast<CHECKER *>(ref); // already registered.
CHECKER *checker = new CHECKER(AOpts);
checker->Name = CurrentCheckName;
CheckerDtors.push_back(CheckerDtor(checker, destruct<CHECKER>));
CHECKER::_register(checker, *this);
ref = checker;

View File

@ -23,21 +23,8 @@ add_clang_library(clangARCMigrate
TransZeroOutPropsInDealloc.cpp
TransformActions.cpp
Transforms.cpp
)
add_dependencies(clangARCMigrate
ClangAttrClasses
ClangAttrList
ClangAttrParsedAttrList
ClangCommentNodes
ClangDeclNodes
ClangDiagnosticCommon
ClangDiagnosticGroups
ClangDiagnosticSema
ClangStmtNodes
)
target_link_libraries(clangARCMigrate
LINK_LIBS
clangAST
clangAnalysis
clangBasic

View File

@ -111,8 +111,7 @@ bool FileRemapper::initFromFile(StringRef filePath, DiagnosticsEngine &Diag,
bool FileRemapper::flushToDisk(StringRef outputDir, DiagnosticsEngine &Diag) {
using namespace llvm::sys;
bool existed;
if (fs::create_directory(outputDir, existed) != llvm::errc::success)
if (fs::create_directory(outputDir) != llvm::errc::success)
return report("Could not create directory: " + outputDir, Diag);
std::string infoFile = getRemapInfoFile(outputDir);
@ -124,8 +123,7 @@ bool FileRemapper::flushToFile(StringRef outputPath, DiagnosticsEngine &Diag) {
std::string errMsg;
std::string infoFile = outputPath;
llvm::raw_fd_ostream infoOut(infoFile.c_str(), errMsg,
llvm::sys::fs::F_Binary);
llvm::raw_fd_ostream infoOut(infoFile.c_str(), errMsg, llvm::sys::fs::F_None);
if (!errMsg.empty())
return report(errMsg, Diag);
@ -181,8 +179,7 @@ bool FileRemapper::overwriteOriginal(DiagnosticsEngine &Diag,
Diag);
std::string errMsg;
llvm::raw_fd_ostream Out(origFE->getName(), errMsg,
llvm::sys::fs::F_Binary);
llvm::raw_fd_ostream Out(origFE->getName(), errMsg, llvm::sys::fs::F_None);
if (!errMsg.empty())
return report(errMsg, Diag);

View File

@ -1843,7 +1843,7 @@ void ObjCMigrateASTConsumer::HandleTranslationUnit(ASTContext &Ctx) {
if (IsOutputFile) {
std::string Error;
llvm::raw_fd_ostream OS(MigrateDir.c_str(), Error, llvm::sys::fs::F_Binary);
llvm::raw_fd_ostream OS(MigrateDir.c_str(), Error, llvm::sys::fs::F_None);
if (!Error.empty()) {
DiagnosticsEngine &Diags = Ctx.getDiagnostics();
Diags.Report(Diags.getCustomDiagID(DiagnosticsEngine::Error, "%0"))

View File

@ -41,7 +41,7 @@ void arcmt::writeARCDiagsToPlist(const std::string &outPath,
}
std::string errMsg;
llvm::raw_fd_ostream o(outPath.c_str(), errMsg);
llvm::raw_fd_ostream o(outPath.c_str(), errMsg, llvm::sys::fs::F_Text);
if (!errMsg.empty()) {
llvm::errs() << "error: could not create file: " << outPath << '\n';
return;

Some files were not shown because too many files have changed in this diff Show More