Compare commits

..

319 Commits

Author SHA1 Message Date
Tom Stellard
6a075b6de4 Bump version to 5.0.2
llvm-svn: 328729
2018-03-28 20:25:17 +00:00
Simon Dardis
4e1dadff9a Backporting r325647 and r325713:
------------------------------------------------------------------------
r325713 | sdardis | 2018-02-21 20:01:43 +0000 (Wed, 21 Feb 2018) | 5 lines

[mips][lld] Address post commit review nit.

Address @ruiu's post commit review comment about a value which is intended
to be a unsigned 32 bit integer as using uint32_t rather than unsigned.

------------------------------------------------------------------------
------------------------------------------------------------------------
r325647 | sdardis | 2018-02-20 23:49:17 +0000 (Tue, 20 Feb 2018) | 27 lines

[mips][lld] Spectre variant two mitigation for MIPSR2

This patch provides migitation for CVE-2017-5715, Spectre variant two,
which affects the P5600 and P6600. It implements the LLD part of
-z hazardplt. Like the Clang part of this patch, I have opted for that
specific option name in case alternative migitation methods are required
in the future.

The mitigation strategy suggested by MIPS for these processors is to use
hazard barrier instructions. 'jalr.hb' and 'jr.hb' are hazard
barrier variants of the 'jalr' and 'jr' instructions respectively.

These instructions impede the execution of instruction stream until
architecturally defined hazards (changes to the instruction stream,
privileged registers which may affect execution) are cleared. These
instructions in MIPS' designs are not speculated past.

These instructions are defined by the MIPS32R2 ISA, so this mitigation
method is not compatible with processors which implement an earlier
revision of the MIPS ISA.

For LLD, this changes PLT stubs to use 'jalr.hb' and 'jr.hb'.

Reviewers: atanasyan, ruiu

Differential Revision: https://reviews.llvm.org/D43488

------------------------------------------------------------------------

llvm-svn: 327757
2018-03-16 22:28:08 +00:00
Simon Dardis
c3a89385a4 Backporting 325651::
------------------------------------------------------------------------
r325651 | sdardis | 2018-02-21 00:05:05 +0000 (Wed, 21 Feb 2018) | 34 lines

[mips] Spectre variant two mitigation for MIPSR2

This patch provides mitigation for CVE-2017-5715, Spectre variant two,
which affects the P5600 and P6600. It provides the option
-mindirect-jump=hazard, which instructs the LLVM backend to replace
indirect branches with their hazard barrier variants.

This option is accepted when targeting MIPS revision two or later.

The migitation strategy suggested by MIPS for these processors is to
use two hazard barrier instructions. 'jalr.hb' and 'jr.hb' are hazard
barrier variants of the 'jalr' and 'jr' instructions respectively.

These instructions impede the execution of instruction stream until
architecturally defined hazards (changes to the instruction stream,
privileged registers which may affect execution) are cleared. These
instructions in MIPS' designs are not speculated past.

These instructions are used with the option -mindirect-jump=hazard
when branching indirectly and for indirect function calls.

These instructions are defined by the MIPS32R2 ISA, so this mitigation
method is not compatible with processors which implement an earlier
revision of the MIPS ISA.

Implementation note: I've opted to provide this as an
-mindirect-jump={hazard,...} style option in case alternative
mitigation methods are required for other implementations of the MIPS
ISA in future, e.g. retpoline style solutions.

Reviewers: atanasyan

Differential Revision: https://reviews.llvm.org/D43487

------------------------------------------------------------------------

llvm-svn: 327755
2018-03-16 22:21:00 +00:00
Simon Dardis
64778dce96 Backporting r325653:
------------------------------------------------------------------------
r325653 | sdardis | 2018-02-21 00:06:53 +0000 (Wed, 21 Feb 2018) | 31 lines

[mips] Spectre variant two mitigation for MIPSR2

This patch provides mitigation for CVE-2017-5715, Spectre variant two,
which affects the P5600 and P6600. It implements the LLVM part of
-mindirect-jump=hazard. It is _not_ enabled by default for the P5600.

The migitation strategy suggested by MIPS for these processors is to use
hazard barrier instructions. 'jalr.hb' and 'jr.hb' are hazard
barrier variants of the 'jalr' and 'jr' instructions respectively.

These instructions impede the execution of instruction stream until
architecturally defined hazards (changes to the instruction stream,
privileged registers which may affect execution) are cleared. These
instructions in MIPS' designs are not speculated past.

These instructions are used with the attribute +use-indirect-jump-hazard
when branching indirectly and for indirect function calls.

These instructions are defined by the MIPS32R2 ISA, so this mitigation
method is not compatible with processors which implement an earlier
revision of the MIPS ISA.

Performance benchmarking of this option with -fpic and lld using
-z hazardplt shows a difference of overall 10%~ time increase
for the LLVM testsuite. Certain benchmarks such as methcall show a
substantially larger increase in time due to their nature.

Reviewers: atanasyan, zoran.jovanovic

Differential Revision: https://reviews.llvm.org/D43486

------------------------------------------------------------------------

llvm-svn: 327751
2018-03-16 22:14:38 +00:00
Reid Kleckner
0d404721f4 Merging r325085:
------------------------------------------------------------------------
r325085 | rnk | 2018-02-13 16:24:29 -0800 (Tue, 13 Feb 2018) | 3 lines

[X86] Remove dead code from retpoline thunk generation

Follow-up to r325049
------------------------------------------------------------------------

llvm-svn: 325091
2018-02-14 00:34:35 +00:00
Reid Kleckner
2caa871699 Merging r325049:
------------------------------------------------------------------------
r325049 | rnk | 2018-02-13 12:47:49 -0800 (Tue, 13 Feb 2018) | 17 lines

[X86] Use EDI for retpoline when no scratch regs are left

Summary:
Instead of solving the hard problem of how to pass the callee to the indirect
jump thunk without a register, just use a CSR. At a call boundary, there's
nothing stopping us from using a CSR to hold the callee as long as we save and
restore it in the prologue.

Also, add tests for this mregparm=3 case. I wrote execution tests for
__llvm_retpoline_push, but they never got committed as lit tests, either
because I never rewrote them or because they got lost in merge conflicts.

Reviewers: chandlerc, dwmw2

Subscribers: javed.absar, kristof.beyls, hiraditya, llvm-commits

Differential Revision: https://reviews.llvm.org/D43214
------------------------------------------------------------------------

llvm-svn: 325090
2018-02-14 00:34:13 +00:00
Reid Kleckner
940d56c109 Merging r324645:
------------------------------------------------------------------------
r324645 | dwmw2 | 2018-02-08 12:06:05 -0800 (Thu, 08 Feb 2018) | 5 lines

[X86] Support 'V' register operand modifier

This allows the register name to be printed without the leading '%'.
This can be used for emitting calls to the retpoline thunks from inline
asm.
------------------------------------------------------------------------

llvm-svn: 325089
2018-02-14 00:33:00 +00:00
Reid Kleckner
754e957b80 Merging r324449:
------------------------------------------------------------------------
r324449 | chandlerc | 2018-02-06 22:16:24 -0800 (Tue, 06 Feb 2018) | 15 lines

[x86/retpoline] Make the external thunk names exactly match the names
that happened to end up in GCC.

This is really unfortunate, as the names don't have much rhyme or reason
to them. Originally in the discussions it seemed fine to rely on aliases
to map different names to whatever external thunk code developers wished
to use but there are practical problems with that in the kernel it turns
out. And since we're discovering this practical problems late and since
GCC has already shipped a release with one set of names, we are forced,
yet again, to blindly match what is there.

Somewhat rushing this patch out for the Linux kernel folks to test and
so we can get it patched into our releases.

Differential Revision: https://reviews.llvm.org/D42998
------------------------------------------------------------------------

llvm-svn: 325088
2018-02-14 00:32:26 +00:00
Reid Kleckner
0e39460d5e Merging r323288:
------------------------------------------------------------------------
r323288 | ruiu | 2018-01-23 16:26:57 -0800 (Tue, 23 Jan 2018) | 3 lines

Fix retpoline PLT header size for i386.

Differential Revision: https://reviews.llvm.org/D42397
------------------------------------------------------------------------

llvm-svn: 324026
2018-02-01 22:39:52 +00:00
Reid Kleckner
ff3a8f17df Merging r323155 in LLD, with modifications to handle int3 fill
Original commit message:
------------------------------------------------------------------------
r323155 | chandlerc | 2018-01-22 14:05:25 -0800 (Mon, 22 Jan 2018) | 133 lines

Introduce the "retpoline" x86 mitigation technique for variant #2 of the speculative execution vulnerabilities disclosed today, specifically identified by CVE-2017-5715, "Branch Target Injection", and is one of the two halves to Spectre..

Summary:
First, we need to explain the core of the vulnerability. Note that this
is a very incomplete description, please see the Project Zero blog post
for details:
https://googleprojectzero.blogspot.com/2018/01/reading-privileged-memory-with-side.html

The basis for branch target injection is to direct speculative execution
of the processor to some "gadget" of executable code by poisoning the
prediction of indirect branches with the address of that gadget. The
gadget in turn contains an operation that provides a side channel for
reading data. Most commonly, this will look like a load of secret data
followed by a branch on the loaded value and then a load of some
predictable cache line. The attacker then uses timing of the processors
cache to determine which direction the branch took *in the speculative
execution*, and in turn what one bit of the loaded value was. Due to the
nature of these timing side channels and the branch predictor on Intel
processors, this allows an attacker to leak data only accessible to
a privileged domain (like the kernel) back into an unprivileged domain.

The goal is simple: avoid generating code which contains an indirect
branch that could have its prediction poisoned by an attacker. In many
cases, the compiler can simply use directed conditional branches and
a small search tree. LLVM already has support for lowering switches in
this way and the first step of this patch is to disable jump-table
lowering of switches and introduce a pass to rewrite explicit indirectbr
sequences into a switch over integers.

However, there is no fully general alternative to indirect calls. We
introduce a new construct we call a "retpoline" to implement indirect
calls in a non-speculatable way. It can be thought of loosely as
a trampoline for indirect calls which uses the RET instruction on x86.
Further, we arrange for a specific call->ret sequence which ensures the
processor predicts the return to go to a controlled, known location. The
retpoline then "smashes" the return address pushed onto the stack by the
call with the desired target of the original indirect call. The result
is a predicted return to the next instruction after a call (which can be
used to trap speculative execution within an infinite loop) and an
actual indirect branch to an arbitrary address.

On 64-bit x86 ABIs, this is especially easily done in the compiler by
using a guaranteed scratch register to pass the target into this device.
For 32-bit ABIs there isn't a guaranteed scratch register and so several
different retpoline variants are introduced to use a scratch register if
one is available in the calling convention and to otherwise use direct
stack push/pop sequences to pass the target address.

This "retpoline" mitigation is fully described in the following blog
post: https://support.google.com/faqs/answer/7625886

We also support a target feature that disables emission of the retpoline
thunk by the compiler to allow for custom thunks if users want them.
These are particularly useful in environments like kernels that
routinely do hot-patching on boot and want to hot-patch their thunk to
different code sequences. They can write this custom thunk and use
`-mretpoline-external-thunk` *in addition* to `-mretpoline`. In this
case, on x86-64 thu thunk names must be:
```
  __llvm_external_retpoline_r11
```
or on 32-bit:
```
  __llvm_external_retpoline_eax
  __llvm_external_retpoline_ecx
  __llvm_external_retpoline_edx
  __llvm_external_retpoline_push
```
And the target of the retpoline is passed in the named register, or in
the case of the `push` suffix on the top of the stack via a `pushl`
instruction.

There is one other important source of indirect branches in x86 ELF
binaries: the PLT. These patches also include support for LLD to
generate PLT entries that perform a retpoline-style indirection.

The only other indirect branches remaining that we are aware of are from
precompiled runtimes (such as crt0.o and similar). The ones we have
found are not really attackable, and so we have not focused on them
here, but eventually these runtimes should also be replicated for
retpoline-ed configurations for completeness.

For kernels or other freestanding or fully static executables, the
compiler switch `-mretpoline` is sufficient to fully mitigate this
particular attack. For dynamic executables, you must compile *all*
libraries with `-mretpoline` and additionally link the dynamic
executable and all shared libraries with LLD and pass `-z retpolineplt`
(or use similar functionality from some other linker). We strongly
recommend also using `-z now` as non-lazy binding allows the
retpoline-mitigated PLT to be substantially smaller.

When manually apply similar transformations to `-mretpoline` to the
Linux kernel we observed very small performance hits to applications
running typical workloads, and relatively minor hits (approximately 2%)
even for extremely syscall-heavy applications. This is largely due to
the small number of indirect branches that occur in performance
sensitive paths of the kernel.

When using these patches on statically linked applications, especially
C++ applications, you should expect to see a much more dramatic
performance hit. For microbenchmarks that are switch, indirect-, or
virtual-call heavy we have seen overheads ranging from 10% to 50%.

However, real-world workloads exhibit substantially lower performance
impact. Notably, techniques such as PGO and ThinLTO dramatically reduce
the impact of hot indirect calls (by speculatively promoting them to
direct calls) and allow optimized search trees to be used to lower
switches. If you need to deploy these techniques in C++ applications, we
*strongly* recommend that you ensure all hot call targets are statically
linked (avoiding PLT indirection) and use both PGO and ThinLTO. Well
tuned servers using all of these techniques saw 5% - 10% overhead from
the use of retpoline.

We will add detailed documentation covering these components in
subsequent patches, but wanted to make the core functionality available
as soon as possible. Happy for more code review, but we'd really like to
get these patches landed and backported ASAP for obvious reasons. We're
planning to backport this to both 6.0 and 5.0 release streams and get
a 5.0 release with just this cherry picked ASAP for distros and vendors.

This patch is the work of a number of people over the past month: Eric, Reid,
Rui, and myself. I'm mailing it out as a single commit due to the time
sensitive nature of landing this and the need to backport it. Huge thanks to
everyone who helped out here, and everyone at Intel who helped out in
discussions about how to craft this. Also, credit goes to Paul Turner (at
Google, but not an LLVM contributor) for much of the underlying retpoline
design.

Reviewers: echristo, rnk, ruiu, craig.topper, DavidKreitzer

Subscribers: sanjoy, emaste, mcrosier, mgorny, mehdi_amini, hiraditya, llvm-commits

Differential Revision: https://reviews.llvm.org/D41723
------------------------------------------------------------------------

llvm-svn: 324025
2018-02-01 22:37:22 +00:00
Reid Kleckner
f94a984645 Merging r323155:
------------------------------------------------------------------------
r323155 | chandlerc | 2018-01-22 14:05:25 -0800 (Mon, 22 Jan 2018) | 133 lines

Introduce the "retpoline" x86 mitigation technique for variant #2 of the speculative execution vulnerabilities disclosed today, specifically identified by CVE-2017-5715, "Branch Target Injection", and is one of the two halves to Spectre..

Summary:
First, we need to explain the core of the vulnerability. Note that this
is a very incomplete description, please see the Project Zero blog post
for details:
https://googleprojectzero.blogspot.com/2018/01/reading-privileged-memory-with-side.html

The basis for branch target injection is to direct speculative execution
of the processor to some "gadget" of executable code by poisoning the
prediction of indirect branches with the address of that gadget. The
gadget in turn contains an operation that provides a side channel for
reading data. Most commonly, this will look like a load of secret data
followed by a branch on the loaded value and then a load of some
predictable cache line. The attacker then uses timing of the processors
cache to determine which direction the branch took *in the speculative
execution*, and in turn what one bit of the loaded value was. Due to the
nature of these timing side channels and the branch predictor on Intel
processors, this allows an attacker to leak data only accessible to
a privileged domain (like the kernel) back into an unprivileged domain.

The goal is simple: avoid generating code which contains an indirect
branch that could have its prediction poisoned by an attacker. In many
cases, the compiler can simply use directed conditional branches and
a small search tree. LLVM already has support for lowering switches in
this way and the first step of this patch is to disable jump-table
lowering of switches and introduce a pass to rewrite explicit indirectbr
sequences into a switch over integers.

However, there is no fully general alternative to indirect calls. We
introduce a new construct we call a "retpoline" to implement indirect
calls in a non-speculatable way. It can be thought of loosely as
a trampoline for indirect calls which uses the RET instruction on x86.
Further, we arrange for a specific call->ret sequence which ensures the
processor predicts the return to go to a controlled, known location. The
retpoline then "smashes" the return address pushed onto the stack by the
call with the desired target of the original indirect call. The result
is a predicted return to the next instruction after a call (which can be
used to trap speculative execution within an infinite loop) and an
actual indirect branch to an arbitrary address.

On 64-bit x86 ABIs, this is especially easily done in the compiler by
using a guaranteed scratch register to pass the target into this device.
For 32-bit ABIs there isn't a guaranteed scratch register and so several
different retpoline variants are introduced to use a scratch register if
one is available in the calling convention and to otherwise use direct
stack push/pop sequences to pass the target address.

This "retpoline" mitigation is fully described in the following blog
post: https://support.google.com/faqs/answer/7625886

We also support a target feature that disables emission of the retpoline
thunk by the compiler to allow for custom thunks if users want them.
These are particularly useful in environments like kernels that
routinely do hot-patching on boot and want to hot-patch their thunk to
different code sequences. They can write this custom thunk and use
`-mretpoline-external-thunk` *in addition* to `-mretpoline`. In this
case, on x86-64 thu thunk names must be:
```
  __llvm_external_retpoline_r11
```
or on 32-bit:
```
  __llvm_external_retpoline_eax
  __llvm_external_retpoline_ecx
  __llvm_external_retpoline_edx
  __llvm_external_retpoline_push
```
And the target of the retpoline is passed in the named register, or in
the case of the `push` suffix on the top of the stack via a `pushl`
instruction.

There is one other important source of indirect branches in x86 ELF
binaries: the PLT. These patches also include support for LLD to
generate PLT entries that perform a retpoline-style indirection.

The only other indirect branches remaining that we are aware of are from
precompiled runtimes (such as crt0.o and similar). The ones we have
found are not really attackable, and so we have not focused on them
here, but eventually these runtimes should also be replicated for
retpoline-ed configurations for completeness.

For kernels or other freestanding or fully static executables, the
compiler switch `-mretpoline` is sufficient to fully mitigate this
particular attack. For dynamic executables, you must compile *all*
libraries with `-mretpoline` and additionally link the dynamic
executable and all shared libraries with LLD and pass `-z retpolineplt`
(or use similar functionality from some other linker). We strongly
recommend also using `-z now` as non-lazy binding allows the
retpoline-mitigated PLT to be substantially smaller.

When manually apply similar transformations to `-mretpoline` to the
Linux kernel we observed very small performance hits to applications
running typical workloads, and relatively minor hits (approximately 2%)
even for extremely syscall-heavy applications. This is largely due to
the small number of indirect branches that occur in performance
sensitive paths of the kernel.

When using these patches on statically linked applications, especially
C++ applications, you should expect to see a much more dramatic
performance hit. For microbenchmarks that are switch, indirect-, or
virtual-call heavy we have seen overheads ranging from 10% to 50%.

However, real-world workloads exhibit substantially lower performance
impact. Notably, techniques such as PGO and ThinLTO dramatically reduce
the impact of hot indirect calls (by speculatively promoting them to
direct calls) and allow optimized search trees to be used to lower
switches. If you need to deploy these techniques in C++ applications, we
*strongly* recommend that you ensure all hot call targets are statically
linked (avoiding PLT indirection) and use both PGO and ThinLTO. Well
tuned servers using all of these techniques saw 5% - 10% overhead from
the use of retpoline.

We will add detailed documentation covering these components in
subsequent patches, but wanted to make the core functionality available
as soon as possible. Happy for more code review, but we'd really like to
get these patches landed and backported ASAP for obvious reasons. We're
planning to backport this to both 6.0 and 5.0 release streams and get
a 5.0 release with just this cherry picked ASAP for distros and vendors.

This patch is the work of a number of people over the past month: Eric, Reid,
Rui, and myself. I'm mailing it out as a single commit due to the time
sensitive nature of landing this and the need to backport it. Huge thanks to
everyone who helped out here, and everyone at Intel who helped out in
discussions about how to craft this. Also, credit goes to Paul Turner (at
Google, but not an LLVM contributor) for much of the underlying retpoline
design.

Reviewers: echristo, rnk, ruiu, craig.topper, DavidKreitzer

Subscribers: sanjoy, emaste, mcrosier, mgorny, mehdi_amini, hiraditya, llvm-commits

Differential Revision: https://reviews.llvm.org/D41723
------------------------------------------------------------------------

llvm-svn: 324012
2018-02-01 21:46:03 +00:00
Reid Kleckner
e68de2381b Merging r323915:
------------------------------------------------------------------------
r323915 | chandlerc | 2018-01-31 12:56:37 -0800 (Wed, 31 Jan 2018) | 17 lines

[x86] Make the retpoline thunk insertion a machine function pass.

Summary:
This removes the need for a machine module pass using some deeply
questionable hacks. This should address PR36123 which is a case where in
full LTO the memory usage of a machine module pass actually ended up
being significant.

We should revert this on trunk as soon as we understand and fix the
memory usage issue, but we should include this in any backports of
retpolines themselves.

Reviewers: echristo, MatzeB

Subscribers: sanjoy, mcrosier, mehdi_amini, hiraditya, llvm-commits

Differential Revision: https://reviews.llvm.org/D42726
------------------------------------------------------------------------

llvm-svn: 324009
2018-02-01 21:31:35 +00:00
Reid Kleckner
507d5d8ef9 Merging r323155:
------------------------------------------------------------------------
r323155 | chandlerc | 2018-01-22 14:05:25 -0800 (Mon, 22 Jan 2018) | 133 lines

Introduce the "retpoline" x86 mitigation technique for variant #2 of the speculative execution vulnerabilities disclosed today, specifically identified by CVE-2017-5715, "Branch Target Injection", and is one of the two halves to Spectre..

Summary:
First, we need to explain the core of the vulnerability. Note that this
is a very incomplete description, please see the Project Zero blog post
for details:
https://googleprojectzero.blogspot.com/2018/01/reading-privileged-memory-with-side.html

The basis for branch target injection is to direct speculative execution
of the processor to some "gadget" of executable code by poisoning the
prediction of indirect branches with the address of that gadget. The
gadget in turn contains an operation that provides a side channel for
reading data. Most commonly, this will look like a load of secret data
followed by a branch on the loaded value and then a load of some
predictable cache line. The attacker then uses timing of the processors
cache to determine which direction the branch took *in the speculative
execution*, and in turn what one bit of the loaded value was. Due to the
nature of these timing side channels and the branch predictor on Intel
processors, this allows an attacker to leak data only accessible to
a privileged domain (like the kernel) back into an unprivileged domain.

The goal is simple: avoid generating code which contains an indirect
branch that could have its prediction poisoned by an attacker. In many
cases, the compiler can simply use directed conditional branches and
a small search tree. LLVM already has support for lowering switches in
this way and the first step of this patch is to disable jump-table
lowering of switches and introduce a pass to rewrite explicit indirectbr
sequences into a switch over integers.

However, there is no fully general alternative to indirect calls. We
introduce a new construct we call a "retpoline" to implement indirect
calls in a non-speculatable way. It can be thought of loosely as
a trampoline for indirect calls which uses the RET instruction on x86.
Further, we arrange for a specific call->ret sequence which ensures the
processor predicts the return to go to a controlled, known location. The
retpoline then "smashes" the return address pushed onto the stack by the
call with the desired target of the original indirect call. The result
is a predicted return to the next instruction after a call (which can be
used to trap speculative execution within an infinite loop) and an
actual indirect branch to an arbitrary address.

On 64-bit x86 ABIs, this is especially easily done in the compiler by
using a guaranteed scratch register to pass the target into this device.
For 32-bit ABIs there isn't a guaranteed scratch register and so several
different retpoline variants are introduced to use a scratch register if
one is available in the calling convention and to otherwise use direct
stack push/pop sequences to pass the target address.

This "retpoline" mitigation is fully described in the following blog
post: https://support.google.com/faqs/answer/7625886

We also support a target feature that disables emission of the retpoline
thunk by the compiler to allow for custom thunks if users want them.
These are particularly useful in environments like kernels that
routinely do hot-patching on boot and want to hot-patch their thunk to
different code sequences. They can write this custom thunk and use
`-mretpoline-external-thunk` *in addition* to `-mretpoline`. In this
case, on x86-64 thu thunk names must be:
```
  __llvm_external_retpoline_r11
```
or on 32-bit:
```
  __llvm_external_retpoline_eax
  __llvm_external_retpoline_ecx
  __llvm_external_retpoline_edx
  __llvm_external_retpoline_push
```
And the target of the retpoline is passed in the named register, or in
the case of the `push` suffix on the top of the stack via a `pushl`
instruction.

There is one other important source of indirect branches in x86 ELF
binaries: the PLT. These patches also include support for LLD to
generate PLT entries that perform a retpoline-style indirection.

The only other indirect branches remaining that we are aware of are from
precompiled runtimes (such as crt0.o and similar). The ones we have
found are not really attackable, and so we have not focused on them
here, but eventually these runtimes should also be replicated for
retpoline-ed configurations for completeness.

For kernels or other freestanding or fully static executables, the
compiler switch `-mretpoline` is sufficient to fully mitigate this
particular attack. For dynamic executables, you must compile *all*
libraries with `-mretpoline` and additionally link the dynamic
executable and all shared libraries with LLD and pass `-z retpolineplt`
(or use similar functionality from some other linker). We strongly
recommend also using `-z now` as non-lazy binding allows the
retpoline-mitigated PLT to be substantially smaller.

When manually apply similar transformations to `-mretpoline` to the
Linux kernel we observed very small performance hits to applications
running typical workloads, and relatively minor hits (approximately 2%)
even for extremely syscall-heavy applications. This is largely due to
the small number of indirect branches that occur in performance
sensitive paths of the kernel.

When using these patches on statically linked applications, especially
C++ applications, you should expect to see a much more dramatic
performance hit. For microbenchmarks that are switch, indirect-, or
virtual-call heavy we have seen overheads ranging from 10% to 50%.

However, real-world workloads exhibit substantially lower performance
impact. Notably, techniques such as PGO and ThinLTO dramatically reduce
the impact of hot indirect calls (by speculatively promoting them to
direct calls) and allow optimized search trees to be used to lower
switches. If you need to deploy these techniques in C++ applications, we
*strongly* recommend that you ensure all hot call targets are statically
linked (avoiding PLT indirection) and use both PGO and ThinLTO. Well
tuned servers using all of these techniques saw 5% - 10% overhead from
the use of retpoline.

We will add detailed documentation covering these components in
subsequent patches, but wanted to make the core functionality available
as soon as possible. Happy for more code review, but we'd really like to
get these patches landed and backported ASAP for obvious reasons. We're
planning to backport this to both 6.0 and 5.0 release streams and get
a 5.0 release with just this cherry picked ASAP for distros and vendors.

This patch is the work of a number of people over the past month: Eric, Reid,
Rui, and myself. I'm mailing it out as a single commit due to the time
sensitive nature of landing this and the need to backport it. Huge thanks to
everyone who helped out here, and everyone at Intel who helped out in
discussions about how to craft this. Also, credit goes to Paul Turner (at
Google, but not an LLVM contributor) for much of the underlying retpoline
design.

Reviewers: echristo, rnk, ruiu, craig.topper, DavidKreitzer

Subscribers: sanjoy, emaste, mcrosier, mgorny, mehdi_amini, hiraditya, llvm-commits

Differential Revision: https://reviews.llvm.org/D41723
------------------------------------------------------------------------

llvm-svn: 324007
2018-02-01 21:28:26 +00:00
Tom Stellard
c8574de3a9 Merging r312509:
------------------------------------------------------------------------
r312509 | dannyb | 2017-09-04 19:17:42 -0700 (Mon, 04 Sep 2017) | 1 line

NewGVN: Fix PR 34452 by passing instruction all the way down when we do aggregate value simplification
------------------------------------------------------------------------

llvm-svn: 319952
2017-12-06 20:45:18 +00:00
Tom Stellard
7b93862750 Merging r314733:
------------------------------------------------------------------------
r314733 | rsmith | 2017-10-02 15:43:36 -0700 (Mon, 02 Oct 2017) | 5 lines

PR33839: Fix -Wunused handling for structured binding declarations.

We warn about a structured binding declaration being unused only if none of its
bindings are used.

------------------------------------------------------------------------

llvm-svn: 319847
2017-12-05 22:38:44 +00:00
Tom Stellard
adb004d9f4 Merging r314107:
------------------------------------------------------------------------
r314107 | sylvestre | 2017-09-25 07:08:35 -0700 (Mon, 25 Sep 2017) | 9 lines

Fix clangd when built with LLVM_LINK_LLVM_DYLIB=ON

Reviewers: malaperle, malaperle-ericsson, bkramer

Reviewed By: bkramer

Subscribers: bkramer, mgorny, ilya-biryukov, cfe-commits

Differential Revision: https://reviews.llvm.org/D38228
------------------------------------------------------------------------

llvm-svn: 319846
2017-12-05 22:28:17 +00:00
Tom Stellard
d5cd8bc98b Merging r311734:
------------------------------------------------------------------------
r311734 | ruiu | 2017-08-24 16:51:40 -0700 (Thu, 24 Aug 2017) | 44 lines

[MACH-O] Fix the ASM code generated for __stub_helpers section

Patch by Patricio Villalobos.

I discovered that lld for darwin is generating the wrong code for lazy
bindings in the __stub_helper section (at least for osx 10.12). This is
the way i can reproduce this problem, using this program:

  #include <stdio.h>

  int main(int argc, char **argv) {
      printf("C: printf!\n");
      puts("C: puts!\n");
      return 0;
  }

Then I link it using i have tested it in 3.9, 4.0 and 4.1 versions:

  $ clang -c hello.c
  $ lld -flavor darwin hello.o -o h1  -lc

When i execute the binary h1 the system gives me the following error:

  C: printf!
  dyld: lazy symbol binding failed:
  BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB
  has segment 4 which is too large (0..3)
  dyld: BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB has segment 4 which is too
  large (0..3)
  Trace/BPT trap: 5

Investigating the code, it seems that the problem is that the asm code
generated in the file StubPass.cpp, specifically in the line 323,when it
adds, what it seems an arbitrary number (12) to the offset into the lazy
bind opcodes section, but it should be calculated depending on the
MachONormalizedFileBinaryWrite::lazyBindingInfo result.

I confirmed this bug by patching the code manually in the binary and
writing the right offset in the asm code (__stub_helper).

This patch fixes the content of the atom that contains the assembly code
when the offset is known.

Differential Revision: https://reviews.llvm.org/D35387
------------------------------------------------------------------------

llvm-svn: 319825
2017-12-05 20:25:50 +00:00
Yonghong Song
170dfab48d bpf: fix bug on silently truncating 64-bit immediate
We came across an llvm bug when compiling some testcases that 64-bit
immediates are silently truncated into 32-bit and then packed into
BPF_JMP | BPF_K encoding.  This caused comparison with wrong value.

This bug looks to be introduced by r308080 (llvm 5.0). The Select_Ri pattern is
supposed to be lowered into J*_Ri while the latter only support 32-bit
immediate encoding, therefore Select_Ri should have similar immediate
predicate check as what J*_Ri are doing.

The bug is fixed by
git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@315889 91177308-0d34-0410-b5e6-96231b3b80d8
in llvm 6.0.

This patch is largely the same as the fix in llvm 6.0 except
one minor adjustment for the test case.

Reported-by: John Fastabend <john.fastabend@gmail.com>
Reported-by: Jakub Kicinski <jakub.kicinski@netronome.com>
Signed-off-by: Jiong Wang <jiong.wang@netronome.com>
Reviewed-by: Yonghong Song <yhs@fb.com>
llvm-svn: 319633
2017-12-03 19:02:03 +00:00
Tom Stellard
1254c70db9 Merging r316035:
------------------------------------------------------------------------
r316035 | tnorthover | 2017-10-17 14:43:52 -0700 (Tue, 17 Oct 2017) | 6 lines

AArch64: account for possible frame index operand in compares.

If the address of a local is used in a comparison, AArch64 can fold the
address-calculation into the comparison via "adds". Unfortunately, a couple of
places (both hit in this one test) are not ready to deal with that yet and just
assume the first source operand is a register.
------------------------------------------------------------------------

llvm-svn: 319231
2017-11-28 22:02:15 +00:00
Tom Stellard
041898d210 Merging r319130:
------------------------------------------------------------------------
r319130 | matze | 2017-11-27 17:17:52 -0800 (Mon, 27 Nov 2017) | 7 lines

ARM: Fix PR32578

https://llvm.org/PR32578

I simplified and converted the reproducer into a lit test.

Patch by Vedant Kumar!
------------------------------------------------------------------------

llvm-svn: 319181
2017-11-28 16:35:04 +00:00
Tom Stellard
6a66741f58 Merging r311456:
------------------------------------------------------------------------
r311456 | krasimir | 2017-08-22 07:28:01 -0700 (Tue, 22 Aug 2017) | 13 lines

[clang-format] Fix lines regression in clang-format.py

Summary:
This patch fixes a regression after https://reviews.llvm.org/rL305665,
which updates the structure of the `lines` variable.

Reviewers: djasper

Reviewed By: djasper

Subscribers: cfe-commits

Differential Revision: https://reviews.llvm.org/D37011
------------------------------------------------------------------------

llvm-svn: 319179
2017-11-28 16:19:54 +00:00
Tom Stellard
0c60ce13b2 Merging r318848:
------------------------------------------------------------------------
r318848 | hahnfeld | 2017-11-22 09:15:20 -0800 (Wed, 22 Nov 2017) | 7 lines

Fix for OMP doacross implementation on Power

Power has a weak consistency model so we need memory barriers to
make writes (both from runtime and from user code) available for
all threads.

Differential Revision: https://reviews.llvm.org/D40175
------------------------------------------------------------------------

llvm-svn: 319057
2017-11-27 17:34:55 +00:00
Tom Stellard
c510d36788 Merging r318658:
------------------------------------------------------------------------
r318658 | achurbanov | 2017-11-20 08:00:42 -0800 (Mon, 20 Nov 2017) | 4 lines

Fixed OMP doacross implementation on 32-bit platforms.

Differential Revision: https://reviews.llvm.org/D40171

------------------------------------------------------------------------

llvm-svn: 319053
2017-11-27 17:29:37 +00:00
Tom Stellard
786065d588 Merging r316106:
------------------------------------------------------------------------
r316106 | labath | 2017-10-18 11:52:16 -0700 (Wed, 18 Oct 2017) | 4 lines

lldb-server tests: Fix undefined behavior

We were creating a StringRef pointing to a temporary string. Problem manifested
itself when running the test on osx.
------------------------------------------------------------------------

llvm-svn: 319035
2017-11-27 15:22:38 +00:00
Tom Stellard
3f76a35b1f Merging r316181:
------------------------------------------------------------------------
r316181 | jvesely | 2017-10-19 13:40:13 -0700 (Thu, 19 Oct 2017) | 4 lines

AMDGPU: Parse r600 CPU name early and expose FMAF capability

Improve amdgcn macro test
Differential Revision: https://reviews.llvm.org/D38667
------------------------------------------------------------------------

llvm-svn: 319032
2017-11-27 14:54:45 +00:00
Tom Stellard
2030ade152 Merging r313182:
------------------------------------------------------------------------
r313182 | sylvestre | 2017-09-13 13:03:29 -0700 (Wed, 13 Sep 2017) | 13 lines

SplitEmptyFunction should be true in the Mozilla coding style

Summary:
As defined here: https://developer.mozilla.org/en-US/docs/Mozilla/Developer_guide/Coding_Style#Classes
See for the downstream bug report: https://bugzilla.mozilla.org/show_bug.cgi?id=1399359

Reviewers: Typz, djasper

Reviewed By: Typz

Subscribers: klimek, cfe-commits

Differential Revision: https://reviews.llvm.org/D37795
------------------------------------------------------------------------

llvm-svn: 318858
2017-11-22 18:30:28 +00:00
Tom Stellard
3d27c09b3e Merging r318788:
------------------------------------------------------------------------
r318788 | mcrosier | 2017-11-21 10:08:34 -0800 (Tue, 21 Nov 2017) | 16 lines

[AArch64] Mark mrs of TPIDR_EL0 (thread pointer) as *having* side effects.

This partially reverts r298851.  The the underlying issue is that we don't
currently model the dependency between mrs (read system register) and
msr (write system register) instructions.

Something like the below should never be reordered:

 msr TPIDR_EL0, x0  ;; set thread pointer
 mrs x8, TPIDR_EL0  ;; read thread pointer

but was being reordered after r298851.  The functional part of the patch
that wasn't reverted needed to remain in place in order to not break
r299462.

PR35317
------------------------------------------------------------------------

llvm-svn: 318854
2017-11-22 18:04:47 +00:00
Tom Stellard
6f6353afc1 Merging r315086:
------------------------------------------------------------------------
r315086 | compnerd | 2017-10-06 11:06:59 -0700 (Fri, 06 Oct 2017) | 8 lines

Bitcode: add an auto-upgrade for LTO section name

The bitcode reader looks specifically for `__DATA, __objc_catlist` as a
section name.  However, SVN r304661 removed the spaces (the two names
are functionally equivalent but do not compare equally
lexicographically).  This causes compatibility issues.  Add an
auto-upgrade path for removing the spaces as well as use the new name in
the LTO plugin.
------------------------------------------------------------------------

llvm-svn: 318851
2017-11-22 17:49:17 +00:00
Tom Stellard
b45efad49d Merging r313398:
------------------------------------------------------------------------
r313398 | steven_wu | 2017-09-15 14:12:14 -0700 (Fri, 15 Sep 2017) | 19 lines

[AutoUpgrade] Fix a compatibility issue with module flag

Summary:
After r304661, module flag to record objective-c image info section is
encoded without whitespaces after comma. The new name is equivalent to
the old one, except that when LTO a module built by old compiler and a
module built by a new compiler, it will fail with conflicting values.

Fix the issue by removing whitespaces in bitcode upgrade path.

rdar://problem/34416934

Reviewers: compnerd

Reviewed By: compnerd

Subscribers: mehdi_amini, hans, llvm-commits

Differential Revision: https://reviews.llvm.org/D37909
------------------------------------------------------------------------

llvm-svn: 318850
2017-11-22 17:43:15 +00:00
Tom Stellard
f0cacaaac7 Merging r318039:
------------------------------------------------------------------------
r318039 | labath | 2017-11-13 06:03:17 -0800 (Mon, 13 Nov 2017) | 37 lines

Revert "[lldb] Use OrcMCJITReplacement rather than MCJIT as the underlying JIT for LLDB"

This commit really did not introduce any functional changes (for most
people) but it turns out it's not for the reason we thought it was.

The reason wasn't that Orc is a perfect drop-in replacement for MCJIT,
but it was because we were never using Orc in the first place, as it was
not initialized.

Orc's initialization relies on a global constructor in the LLVMOrcJIT.a.
Since this archive does not expose any symbols referenced from other
object files, it does not get linked into liblldb when linking against
llvm components statically. However, in an LLVM_LINK_LLVM_DYLIB=On
build, LLVMOrcJit.a is linked into libLLVM.so using --whole-archive, so
the global constructor does end up firing.

The result of using Orc jit is pr34194, where lldb fails to evaluate
even very simple expressions. This bug can be reproduced in
non-LLVM_LINK_LLVM_DYLIB builds by making sure Orc jit is linked into
liblldb, for example by #including
llvm/ExecutionEngine/OrcMCJITReplacement.h in IRExecutionUnit.cpp (and
adding OrcJIT as a dependency to the relevant CMakeLists.txt file). The
bug reproduces (at least) on linux and osx.

The root cause of the bug seems to be related to relocation processing.
It seems Orc processes relocations earlier than the system it is
replacing. This means the relocation processing happens before we have
had a chance to remap section load addresses to reflect their address in
the target process memory, so they end up pointing to locations in the
lldb's address space instead.

I am not sure whether this is a bug in Orc jit, or in how we are using
it from lldb, but in any case it is preventing us from using Orc right
now. Reverting this fixes LLVM_LINK_LLVM_DYLIB build, and makes it clear
that we are in fact *not* using Orc, and we never really were.

This reverts commit r279327.
------------------------------------------------------------------------

llvm-svn: 318845
2017-11-22 16:57:36 +00:00
Tom Stellard
1d45231962 Merging r315994:
------------------------------------------------------------------------
r315994 | ericwf | 2017-10-17 06:03:17 -0700 (Tue, 17 Oct 2017) | 18 lines

[libc++] Fix PR34898 - vector iterator constructors and assign method perform push_back instead of emplace_back.

Summary:
The constructors `vector(Iter, Iter, Alloc = Alloc{})` and `assign(Iter, Iter)` don't correctly perform EmplaceConstruction from the result of dereferencing the iterator. This results in them performing an additional and unneeded copy.

This patch addresses the issue by correctly using `emplace_back` in C++11 and newer.

There are also some bugs in our `insert` implementation, but those will be handled separately.

@mclow.lists We should probably merge this into 5.1, agreed?

Reviewers: mclow.lists, dlj, EricWF

Reviewed By: mclow.lists, EricWF

Subscribers: cfe-commits, mclow.lists

Differential Revision: https://reviews.llvm.org/D38757
------------------------------------------------------------------------

llvm-svn: 318837
2017-11-22 15:06:35 +00:00
Tom Stellard
8c2d95c8bb Merging r312892:
------------------------------------------------------------------------
r312892 | ericwf | 2017-09-10 16:41:20 -0700 (Sun, 10 Sep 2017) | 10 lines

Fix PR34298 - Allow std::function with an incomplete return type.

This patch fixes llvm.org/PR34298. Previously libc++ incorrectly evaluated
the __invokable trait via the converting constructor `function(Tp)` [with Tp = std::function]
whenever the copy constructor or copy assignment operator
was required. This patch further constrains that constructor to short
circut before evaluating the troublesome SFINAE when `Tp` matches
std::function.

The original patch is from Alex Lorenz.
------------------------------------------------------------------------

llvm-svn: 318835
2017-11-22 14:45:26 +00:00
Tom Stellard
406ca54633 Merging r318289:
------------------------------------------------------------------------
r318289 | jdevlieghere | 2017-11-15 02:57:05 -0800 (Wed, 15 Nov 2017) | 14 lines

[DebugInfo] Fix potential CU mismatch for SubprogramScopeDIEs.

In constructAbstractSubprogramScopeDIE there can be a potential mismatch
between `this` and the CU of ContextDIE when a scope is shared between
two DISubprograms belonging to a different CU. In that case, `this` is
the CU that was specified in the IR, but the CU of ContextDIE is that of
the first subprogram that was emitted. This patch fixes the mismatch by
looking up the CU of ContextDIE, and switching to use that.

This fixes PR35212 (https://bugs.llvm.org/show_bug.cgi?id=35212)

Patch by Philip Craig!

Differential revision: https://reviews.llvm.org/D39981
------------------------------------------------------------------------

llvm-svn: 318542
2017-11-17 18:48:34 +00:00
Simon Dardis
b4d5c65186 Merging r318207:
------------------------------------------------------------------------
r318207 | sdardis | 2017-11-14 22:26:42 +0000 (Tue, 14 Nov 2017) | 18 lines

Reland "[mips][mt][6/7] Add support for mftr, mttr instructions."

This adjusts the tests to hopfully pacify the
llvm-clang-x86_64-expensive-checks-win buildbot.

Unlike many other instructions, these instructions have aliases which
take coprocessor registers, gpr register, accumulator (and dsp accumulator)
registers, floating point registers, floating point control registers and
coprocessor 2 data and control operands.

For the moment, these aliases are treated as pseudo instructions which are
expanded into the underlying instruction. As a result, disassembling these
instructions shows the underlying instruction and not the alias.

Reviewers: slthakur, atanasyan

Differential Revision: https://reviews.llvm.org/D35253

------------------------------------------------------------------------

llvm-svn: 318386
2017-11-16 10:13:49 +00:00
Tom Stellard
5c325eae11 Merging r312748:
------------------------------------------------------------------------
r312748 | jroelofs | 2017-09-07 15:01:25 -0700 (Thu, 07 Sep 2017) | 10 lines

Fix validation of the -mthread-model flag in the Clang driver

The ToolChain class validates the -mthread-model flag in the constructor which
doesn't work correctly since the thread model methods are virtual methods. The
check is moved into Clang::ConstructJob() when constructing the internal
command line.

https://reviews.llvm.org/D37496

Patch by: Ian Tessier!
------------------------------------------------------------------------

llvm-svn: 318346
2017-11-15 22:41:48 +00:00
Tom Stellard
1e07f078f8 Merging r312043:
------------------------------------------------------------------------
r312043 | rnk | 2017-08-29 14:44:21 -0700 (Tue, 29 Aug 2017) | 25 lines

[cmake] Stop putting the revision info in LLVM_VERSION_STRING

Summary:
This reduces the number of build actions after a no-op commit from
thousands to about six, which should be acceptable. If six actions is
still too many, developers can disable the LLVM_APPEND_VC_REV cmake
option.

llvm-config.h is a widely included header that should rarely change.
Before this patch, it would change after every re-configure. Very few
users of llvm-config.h need to know the precise version, and those that
do can migrate to incorporating LLVM_REVISION as provided by
llvm/Support/VCSRevision.h.

This should bring LLVM back to the behavior that it had before r306858
from June 30 2017. Most LLVM tools will now print a version string like
"6.0.0svn" instead of "6.0.0-git-c40c2a23de4".

Fixes PR34308

Reviewers: pcc, rafael, hans

Subscribers: mgorny, llvm-commits

Differential Revision: https://reviews.llvm.org/D37272
------------------------------------------------------------------------

llvm-svn: 318344
2017-11-15 22:26:48 +00:00
Tom Stellard
3f249e8317 Merging r310475:
------------------------------------------------------------------------
r310475 | belleyb | 2017-08-09 06:47:01 -0700 (Wed, 09 Aug 2017) | 28 lines

[Support] PR33388 - Fix formatv_object move constructor

formatv_object currently uses the implicitly defined move constructor,
but it is buggy. In typical use-cases, the problem doesn't show-up
because all calls to the move constructor are elided. Thus, the buggy
constructors are never invoked.

The issue especially shows-up when code is compiled using the
-fno-elide-constructors compiler flag. For instance, this is useful when
attempting to collect accurate code coverage statistics.

The exact issue is the following:

The Parameters data member is correctly moved, thus making the
parameters occupy a new memory location in the target
object. Unfortunately, the default copying of the Adapters blindly
copies the vector of pointers, leaving each of these pointers
referencing the parameters in the original object instead of the copied
one. These pointers quickly become dangling when the original object is
deleted. This quickly leads to crashes.

The solution is to update the Adapters pointers when performing a move.
The copy constructor isn't useful for format objects and can thus be
deleted.

This resolves PR33388.

Differential Revision: https://reviews.llvm.org/D34463
------------------------------------------------------------------------

llvm-svn: 318333
2017-11-15 20:48:55 +00:00
Tom Stellard
7b672917b4 Merging r315578:
------------------------------------------------------------------------
r315578 | abataev | 2017-10-12 06:51:32 -0700 (Thu, 12 Oct 2017) | 7 lines

[OPENMP] Fix PR34925: Fix getting thread_id lvalue for inlined regions
in C.

If we try to get the lvalue for thread_id variables in inlined regions,
we did not use the correct version of function. Fixed this bug by adding
overrided version of the function getThreadIDVariableLValue for inlined
regions.
------------------------------------------------------------------------

llvm-svn: 318315
2017-11-15 17:51:08 +00:00
Tom Stellard
6fd1575384 Merging r313776:
------------------------------------------------------------------------
r313776 | marshall | 2017-09-20 10:34:11 -0700 (Wed, 20 Sep 2017) | 1 line

Fix a bit of UB in __independent_bits_engine. Fixes PR#34663
------------------------------------------------------------------------

llvm-svn: 318236
2017-11-15 00:21:20 +00:00
Tom Stellard
e3d4cdb1dd Merging r315464:
------------------------------------------------------------------------
r315464 | abataev | 2017-10-11 08:29:40 -0700 (Wed, 11 Oct 2017) | 5 lines

[OPENMP] Fix PR34916: Crash on mixing taskloop|tasks directives.

If both taskloop and task directives are used at the same time in one
program, we may ran into the situation when the particular type for task
directive is reused for taskloop directives. Patch fixes this problem.
------------------------------------------------------------------------

llvm-svn: 318233
2017-11-15 00:07:19 +00:00
Tom Stellard
98532e41e0 Merging r310905 and r310994:
------------------------------------------------------------------------
r310905 | rnk | 2017-08-14 18:17:47 -0700 (Mon, 14 Aug 2017) | 11 lines

Avoid PointerIntPair of constexpr EvalInfo structs

They are stack allocated, so their alignment is not to be trusted.
32-bit MSVC only guarantees 4 byte stack alignment, even though alignof
would tell you otherwise. I tried fixing this with __declspec align, but
that apparently upsets GCC. Hopefully this version will satisfy all
compilers.

See PR32018 for some info about the mingw issues.

Should supercede https://reviews.llvm.org/D34873
------------------------------------------------------------------------

------------------------------------------------------------------------
r310994 | chandlerc | 2017-08-16 00:22:49 -0700 (Wed, 16 Aug 2017) | 6 lines

Fix a UBSan failure where this boolean was copied when uninitialized.

When r310905 moved the pointer and bool out of a PointerIntPair, it made
them end up uninitialized and caused UBSan failures when copying the
uninitialized boolean. However, making the pointer be null should avoid
the reference to the boolean entirely.
------------------------------------------------------------------------

llvm-svn: 318225
2017-11-14 23:53:22 +00:00
Tom Stellard
9ad76aac5a Merging r315310:
------------------------------------------------------------------------
r315310 | sdardis | 2017-10-10 06:34:45 -0700 (Tue, 10 Oct 2017) | 22 lines

[mips] Partially fix PR34391

Previously, the parsing of the 'subu $reg, ($reg,) imm' relied on a parser
which also rendered the operand to the instruction. In some cases the
general parser could construct an MCExpr which was not a MCConstantExpr
which MipsAsmParser was expecting.

Address this by altering the special handling to cope with unexpected inputs
and fine-tune the handling of cases where an register name that is not
available in the current ABI is regarded as not a match for the custom parser
but also not as an outright error.

Also enforces the binutils restriction that only constants are accepted.

This partially resolves PR34391.

Thanks to Ed Maste for reporting the issue!

Reviewers: nitesh.jain, arichardson

Differential Revision: https://reviews.llvm.org/D37476

------------------------------------------------------------------------

llvm-svn: 318192
2017-11-14 20:49:34 +00:00
Tom Stellard
ee6a0ad5af Merging r317204 and r318172:
------------------------------------------------------------------------
r317204 | sdardis | 2017-11-02 05:47:22 -0700 (Thu, 02 Nov 2017) | 15 lines

[mips] Use register scavenging with MSA.

MSA stores and loads to the stack are more likely to require an
emergency GPR spill slot due to the smaller offsets available
with those instructions.

Handle this by overestimating the size of the stack by determining
the largest offset presuming that all callee save registers are
spilled and accounting of incoming arguments when determining
whether an emergency spill slot is required.

Reviewers: atanasyan

Differential Revision: https://reviews.llvm.org/D39056

------------------------------------------------------------------------

------------------------------------------------------------------------
r318172 | sdardis | 2017-11-14 11:11:45 -0800 (Tue, 14 Nov 2017) | 5 lines

[mips] Simplify test for 5.0.1 (NFC)

Simplify testing that an emergency spill slot is used when MSA
is used so that it can be included in the 5.0.1 release.

------------------------------------------------------------------------

llvm-svn: 318191
2017-11-14 20:40:11 +00:00
Tom Stellard
3547c904e2 Merging r317470:
------------------------------------------------------------------------
r317470 | sdardis | 2017-11-06 02:50:04 -0800 (Mon, 06 Nov 2017) | 12 lines

[mips] Fix PR35140

Mark all symbols involved with TLS relocations as being TLS symbols.

This resolves PR35140.

Thanks to Alex Crichton for reporting the issue!

Reviewers: atanasyan

Differential Revision: https://reviews.llvm.org/D39591

------------------------------------------------------------------------

llvm-svn: 318188
2017-11-14 20:09:34 +00:00
Tom Stellard
40a82ea1e5 Merging r314798:
------------------------------------------------------------------------
r314798 | sdardis | 2017-10-03 06:45:49 -0700 (Tue, 03 Oct 2017) | 9 lines

[mips] Enable spilling and reloading of the dsp register set.

The dsp register class is an alias of the gpr register class, so
we have to define instructions for spilling and reloading.

Reviewers: atanasyan

Differential Revision: https://reviews.llvm.org/D38038

------------------------------------------------------------------------

llvm-svn: 318183
2017-11-14 19:54:26 +00:00
Tom Stellard
0830004ba8 Merging r310543:
------------------------------------------------------------------------
r310543 | pcc | 2017-08-09 18:07:44 -0700 (Wed, 09 Aug 2017) | 9 lines

Linker: Create a function declaration when moving a non-prevailing alias of function type.

We were previously creating a global variable of function type,
which is invalid IR. This issue was exposed by r304690, in which we
started asserting that global variables were of a valid type.

Fixes PR33462.

Differential Revision: https://reviews.llvm.org/D36438
------------------------------------------------------------------------

llvm-svn: 318181
2017-11-14 19:47:47 +00:00
Tom Stellard
a08fd1409b Merging r310522:
------------------------------------------------------------------------
r310522 | belleyb | 2017-08-09 13:58:39 -0700 (Wed, 09 Aug 2017) | 8 lines

[Linker] PR33527 - Linker::LinkOnlyNeeded should import AppendingLinkage globals

Linker::LinkOnlyNeeded should always import globals with
AppendingLinkage.

This resolves PR33527.

Differential Revision: https://reviews.llvm.org/D34448
------------------------------------------------------------------------

llvm-svn: 318180
2017-11-14 19:40:53 +00:00
Tom Stellard
b32afe4684 Merging r317115:
------------------------------------------------------------------------
r317115 | jlpeyton | 2017-11-01 12:44:42 -0700 (Wed, 01 Nov 2017) | 19 lines

[OpenMP] Fix race condition in omp_init_lock

This is a partial fix for bug 34050.

This prevents callers of omp_set_lock (which does not hold __kmp_global_lock)
from ever seeing an uninitialized version of __kmp_i_lock_table.table.

It does not solve a use-after-free race condition if omp_set_lock obtains a
pointer to __kmp_i_lock_table.table before it is updated and then attempts to
dereference afterwards. That race is far less likely and can be handled in a
separate patch.

The unit test usually segfaults on the current trunk revision. It passes with
the patch.

Patch by Adam Azarchs

Differential Revision: https://reviews.llvm.org/D39439

------------------------------------------------------------------------

llvm-svn: 318178
2017-11-14 19:21:30 +00:00
Tom Stellard
def3a920c3 Merging r316452:
------------------------------------------------------------------------
r316452 | jlpeyton | 2017-10-24 09:10:09 -0700 (Tue, 24 Oct 2017) | 9 lines

Disable threadprivate data cleanup if runtime is terminating

The problem is due to the runtime's threadprivate cleanup code which tries to
access data that was already destroyed by one of the root threads.
__kmp_init_gtid is used as a checker here since it is set to false before actual
resource cleanup is done in __kmp_cleanup().

Patch by Hansang Bae

------------------------------------------------------------------------

llvm-svn: 318176
2017-11-14 19:19:10 +00:00
Tom Stellard
c925bd49fe Merging r311269:
------------------------------------------------------------------------
r311269 | jlpeyton | 2017-08-19 16:53:36 -0700 (Sat, 19 Aug 2017) | 8 lines

Use va_copy instead of __va_copy to fix building libomp against musl libc

Fixes https://bugs.llvm.org/show_bug.cgi?id=34040

Patch by Peter Levine

Differential Revision: https://reviews.llvm.org/D36343

------------------------------------------------------------------------

llvm-svn: 318175
2017-11-14 19:16:52 +00:00
Tom Stellard
562975c62d Merging r309875:
------------------------------------------------------------------------
r309875 | jlpeyton | 2017-08-02 13:06:32 -0700 (Wed, 02 Aug 2017) | 11 lines

Move lock acquire/release functions in task deque cleanup code

The original locations can be reached without initializing the lock variable
(td_deque_lock), so it is potentially unsafe.  It is guaranteed that the lock
is initialized if the deque (td_deque) is not NULL, and lock functions can be
safely called.

Patch by Hansang Bae

Differential Revision: https://reviews.llvm.org/D36017

------------------------------------------------------------------------

llvm-svn: 318171
2017-11-14 19:11:04 +00:00
Tom Stellard
c05dace09d Merging r313278:
------------------------------------------------------------------------
r313278 | prazek | 2017-09-14 10:33:08 -0700 (Thu, 14 Sep 2017) | 11 lines

Enable __declspec(selectany) on any platform

Summary:
This feature was disabled probably by mistake in rL300562
This fixes bug https://bugs.llvm.org/show_bug.cgi?id=33285

Reviewers: davide, rnk

Subscribers: cfe-commits

Differential Revision: https://reviews.llvm.org/D33852
------------------------------------------------------------------------

llvm-svn: 318133
2017-11-14 02:38:20 +00:00
Tom Stellard
dc4d480f3e Merging r315611:
------------------------------------------------------------------------
r315611 | abataev | 2017-10-12 13:03:39 -0700 (Thu, 12 Oct 2017) | 5 lines

[OPENMP] Fix PR34927: Emit initializer for reduction array with declare
reduction.

If the reduction is an array or an array section and reduction operation
is declare reduction without initializer, it may lead to crash.
------------------------------------------------------------------------

llvm-svn: 318120
2017-11-14 00:18:14 +00:00
Tom Stellard
9347003bd9 Merging r315586:
------------------------------------------------------------------------
r315586 | abataev | 2017-10-12 08:18:41 -0700 (Thu, 12 Oct 2017) | 5 lines

[OPENMP] Fix PR34926: Fix handling of the array sections passed as
function params.

Codegen could crash if the array section base expression is the
function parameter.
------------------------------------------------------------------------

llvm-svn: 318118
2017-11-14 00:00:35 +00:00
Tom Stellard
8a6a32d37a Merging r313675:
------------------------------------------------------------------------
r313675 | rcraik | 2017-09-19 14:04:23 -0700 (Tue, 19 Sep 2017) | 9 lines

[OpenMP] fix seg-faults printing diagnostics with invalid ordered(n) values

When the value specified for n in ordered(n) is larger than the number of loops a segmentation fault can occur in one of two ways when attempting to print out a diagnostic for an associated depend(sink : vec):
1) The iteration vector vec contains less than n items
2) The iteration vector vec contains a variable that is not a loop control variable
This patch addresses both of these issues.

Differential Revision: https://reviews.llvm.org/D38049

------------------------------------------------------------------------

llvm-svn: 318116
2017-11-13 23:52:05 +00:00
Tom Stellard
9ddaa3d4b4 Merging r312296:
------------------------------------------------------------------------
r312296 | abataev | 2017-08-31 16:34:33 -0700 (Thu, 31 Aug 2017) | 1 line

[OPENMP] Fix the test, NFC.
------------------------------------------------------------------------

llvm-svn: 318114
2017-11-13 23:42:12 +00:00
Tom Stellard
d6a5bd12cc Merging r312292:
------------------------------------------------------------------------
r312292 | abataev | 2017-08-31 16:06:52 -0700 (Thu, 31 Aug 2017) | 8 lines

[OPENMP] Fix for PR34398: assert with random access iterator if the
step>1.

If the loop is a loot with random access iterators and the iteration
construct is represented it += n, then the compiler crashed because of
reusing of the same MaterializedTemporaryExpr around N. Patch fixes it
by using the expression as written, without any special kind of
wrappings.
------------------------------------------------------------------------

llvm-svn: 318113
2017-11-13 23:34:53 +00:00
Tom Stellard
9bc8cddc28 Merging r311777:
------------------------------------------------------------------------
r311777 | abataev | 2017-08-25 08:43:55 -0700 (Fri, 25 Aug 2017) | 5 lines

[OPENMP] Fix for PR34321: ustom OpenMP reduction in C++ template causes
SEGFAULT at compile time

Compiler crashed when tried to rebuild non-template expression in
dependent context.
------------------------------------------------------------------------

llvm-svn: 318107
2017-11-13 23:26:36 +00:00
Tom Stellard
bff911cfa5 Merging r311013:
------------------------------------------------------------------------
r311013 | abataev | 2017-08-16 08:58:46 -0700 (Wed, 16 Aug 2017) | 7 lines

[OPENMP] Fix for PR28581: OpenMP linear clause - wrong results.

If worksharing construct has at least one linear item, an implicit
synchronization point must be emitted to avoid possible conflict with
the loading/storing values to the original variables. Added implicit
barrier if the linear item is found before actual start of the
worksharing construct.
------------------------------------------------------------------------

llvm-svn: 318105
2017-11-13 23:12:35 +00:00
Tom Stellard
eadbc97bc9 Merging r309288:
------------------------------------------------------------------------
r309288 | erichkeane | 2017-07-27 09:28:20 -0700 (Thu, 27 Jul 2017) | 32 lines

Fix double destruction of objects when OpenMP construct is canceled

When an omp for loop is canceled the constructed objects are being destructed
twice.

It looks like the desired code is:

{

  Obj o;
  If (cancelled) branch-through-cleanups to cancel.exit.

}
[cleanups]
cancel.exit:

__kmpc_for_static_fini
br cancel.cont (*)

cancel.cont:

__kmpc_barrier
return

The problem seems to be the branch to cancel.cont is currently also going
through the cleanups calling them again. This change just does a direct branch
instead.

Patch By: michael.p.rice@intel.com

Differential Revision: https://reviews.llvm.org/D35854

------------------------------------------------------------------------

llvm-svn: 318099
2017-11-13 22:52:27 +00:00
Tom Stellard
8810e0e6dc Merging r316824:
------------------------------------------------------------------------
r316824 | haicheng | 2017-10-27 19:27:14 -0700 (Fri, 27 Oct 2017) | 7 lines

[ConstantFold] Fix a crash when folding a GEP that has vector index

LLVM crashes when factoring out an out-of-bound index into preceding dimension
and the preceding dimension uses vector index.  Simply bail out now when this
case happens.

Differential Revision: https://reviews.llvm.org/D38677
------------------------------------------------------------------------

llvm-svn: 318096
2017-11-13 22:26:54 +00:00
Tom Stellard
645a5f1355 Merging r312693:
------------------------------------------------------------------------
r312693 | marshall | 2017-09-06 21:19:32 -0700 (Wed, 06 Sep 2017) | 1 line

Add even more string_view tests. These found some bugs in the default parameter value for rfind/find_last_of/find_last_not_of
------------------------------------------------------------------------

llvm-svn: 318088
2017-11-13 21:27:53 +00:00
Renato Golin
c7fc688bf6 Merge r311574: ARM: explicitly specify the 8-byte alignment
Fixing the last libunwind failure on ARM.

llvm-svn: 316991
2017-10-31 12:21:32 +00:00
Renato Golin
42478613cd Merging r316657: fixing libunwind tests
llvm-svn: 316664
2017-10-26 13:53:36 +00:00
Tom Stellard
831f831817 Merging r315485:
------------------------------------------------------------------------
r315485 | spatel | 2017-10-11 11:24:21 -0700 (Wed, 11 Oct 2017) | 7 lines

[x86] avoid infinite loop from SoftenFloatOperand (PR34866)

Legalization of fp128 assumes things that we should have asserts for,
so that's another potential improvement.

Differential Revision: https://reviews.llvm.org/D38771

------------------------------------------------------------------------

llvm-svn: 316607
2017-10-25 20:56:42 +00:00
Dylan McKay
5945e5f25b Merging r314898:
------------------------------------------------------------------------
r314898 | dylanmckay | 2017-10-04 23:37:22 +1300 (Wed, 04 Oct 2017) | 6 lines

[AVR] Implement LPMWRdZ pseudo-instruction's expansion.

FIXME: implementation is mostly copy-pasted from LDWRdPtr, so we should
refactor a bit and unify the two

Patch by Gerdo Erdi.
------------------------------------------------------------------------

llvm-svn: 315836
2017-10-14 22:31:06 +00:00
Dylan McKay
c201f2417a Merging r314897:
------------------------------------------------------------------------
r314897 | dylanmckay | 2017-10-04 23:36:07 +1300 (Wed, 04 Oct 2017) | 3 lines

[AVR] Factor out mayLoad in tablegen patterns

Patch by Gergo Erdi.
------------------------------------------------------------------------

llvm-svn: 315835
2017-10-14 22:30:44 +00:00
Dylan McKay
fb12e5f481 Merging r314896:
------------------------------------------------------------------------
r314896 | dylanmckay | 2017-10-04 23:33:36 +1300 (Wed, 04 Oct 2017) | 3 lines

[AVR] Elaborate LDWRdPtr into `ld r, X++; ld r+1, X`

Patch by Gergo Erdi.
------------------------------------------------------------------------

llvm-svn: 315834
2017-10-14 22:30:19 +00:00
Dylan McKay
037e4e6596 Merging r314891:
------------------------------------------------------------------------
r314891 | dylanmckay | 2017-10-04 22:51:28 +1300 (Wed, 04 Oct 2017) | 8 lines

[AVR] Insert JMP for long branches

Previously, on long branches (relative jumps of >4 kB), an assertion
failure was hit, as AVRInstrInfo::insertIndirectBranch was not
implemented. Despite its name, it is called by the branch relaxator
for *all* unconditional jumps.

Patch by Thomas Backman.
------------------------------------------------------------------------

llvm-svn: 315833
2017-10-14 22:29:48 +00:00
Dylan McKay
a8575044a7 Merging r314890:
------------------------------------------------------------------------
r314890 | dylanmckay | 2017-10-04 22:51:21 +1300 (Wed, 04 Oct 2017) | 16 lines

[AVR] Fix displacement overflow for LDDW/STDW

In some cases, the code generator attempts to generate instructions such as:

lddw r24, Y+63

which expands to:

ldd r24, Y+63
ldd r25, Y+64 # Oops! This is actually ld r25, Y in the binary

This commit limits the first offset to 62, and thus the second to 63.
It also updates some asserts in AVRExpandPseudoInsts.cpp, including for
INW and OUTW, which appear to be unused.

Patch by Thomas Backman.
------------------------------------------------------------------------

llvm-svn: 315832
2017-10-14 22:29:18 +00:00
Tom Stellard
feff932b08 Merging r312357:
------------------------------------------------------------------------
r312357 | davide | 2017-09-01 12:54:08 -0700 (Fri, 01 Sep 2017) | 9 lines

[TTI] Fix getGEPCost() for geps with a single operand.

Previously this would sporadically crash as TargetType
was never initialized. We special-case the single-operand
case returning earlier and trying to mimic the behaviour of
isLegalAddressingMode as closely as possible.

Differential Revision:  https://reviews.llvm.org/D37277
------------------------------------------------------------------------

llvm-svn: 315663
2017-10-13 02:33:17 +00:00
Tom Stellard
7aaddf659d Merging r314513:
------------------------------------------------------------------------
r314513 | hahnfeld | 2017-09-29 06:53:03 -0700 (Fri, 29 Sep 2017) | 3 lines

[test] Fix uninitialized memory in omp_taskloop_grainsize.c

result was never initialized to zero which sometimes failed the test.
------------------------------------------------------------------------

llvm-svn: 315353
2017-10-10 19:57:45 +00:00
Tom Stellard
e97b489fd5 Merging r309979:
------------------------------------------------------------------------
r309979 | mgorny | 2017-08-03 12:41:33 -0700 (Thu, 03 Aug 2017) | 16 lines

[test] Fix clang library dir in LD_LIBRARY_PATH For stand-alone build

Prepend the clang library directory (determined using SHLIBDIR, alike
in clang) to the LD_LIBRARY_PATH to ensure that just-built clang
libraries will be used instead of a previous installed version.

When a stand-alone build is performed, LLVM_LIBS_DIR contains the path
to installed LLVM library directory. The same directory frequently
contains a previously installed version of clang. SHLIBDIR, on the other
hand, is always the build-tree directory, and therefore contains
the freshly built clang libraries.

In a non-stand-alone build, both paths will be the same and therefore
including them both will not cause any issues.

Differential Revision: https://reviews.llvm.org/D30155
------------------------------------------------------------------------

llvm-svn: 315224
2017-10-09 18:00:04 +00:00
Craig Topper
9fd74c167d Merging r313366:
------------------------------------------------------------------------
r313366 | ctopper | 2017-09-15 10:09:03 -0700 (Fri, 15 Sep 2017) | 9 lines

[X86] Don't create i64 constants on 32-bit targets when lowering v64i1 constant build vectors

When handling a v64i1 build vector of constants on 32-bit targets we were creating an illegal i64 constant that we then bitcasted back to v64i1. We need to instead create two 32-bit constants, bitcast them to v32i1 and concat the result. We should also take care to handle the halves being all zeros/ones after the split.

This patch splits the build vector and then recursively lowers the two pieces. This allows us to handle the all ones and all zeros cases with minimal effort. Ideally we'd just do the split and concat, and let lowering get called again on the new nodes, but getNode has special handling for CONCAT_VECTORS that reassembles the pieces back into a single BUILD_VECTOR. Hopefully the two temporary BUILD_VECTORS we had to create to do this that don't get returned don't cause any issues.

Fixes PR34605.

Differential Revision: https://reviews.llvm.org/D37858
------------------------------------------------------------------------

llvm-svn: 315198
2017-10-08 23:49:29 +00:00
Dylan McKay
542b004d8f Revert r314892
It was accidentally merged.

llvm-svn: 314893
2017-10-04 10:06:12 +00:00
Dylan McKay
6b0b442e21 Merging r314891:
------------------------------------------------------------------------
r314891 | dylanmckay | 2017-10-04 22:51:28 +1300 (Wed, 04 Oct 2017) | 8 lines

[AVR] Insert JMP for long branches

Previously, on long branches (relative jumps of >4 kB), an assertion
failure was hit, as AVRInstrInfo::insertIndirectBranch was not
implemented. Despite its name, it is called by the branch relaxator
for *all* unconditional jumps.

Patch by Thomas Backman.
------------------------------------------------------------------------

llvm-svn: 314892
2017-10-04 10:01:09 +00:00
Rui Ueyama
08de6a4a9d Merging r312706:
------------------------------------------------------------------------
r312706 | anng | 2017-09-07 01:43:56 -0700 (Thu, 07 Sep 2017) | 14 lines

[LLD] Fix padding of .eh_frame when in executable segment

The default padding for an executable segment is the target trap
instruction which for x86_64 is 0xCC. However, the .eh_frame section
requires the padding to be zero. The code that writes the .eh_frame
section assumes that its segment is zero initialized and does not
explicitly write the zero padding. This does not work when the .eh_frame
section is in the executable segment (for example when using
-no-rosegment).

This patch changes the .eh_frame writing code to explicitly write the
zero padding.

Differential Revision: https://reviews.llvm.org/D37462
------------------------------------------------------------------------

llvm-svn: 314861
2017-10-03 23:44:23 +00:00
Rui Ueyama
a4fcc49a8b Merging r313741:
------------------------------------------------------------------------
r313741 | grimar | 2017-09-20 02:27:41 -0700 (Wed, 20 Sep 2017) | 9 lines

[ELF] - Fix segfault when processing .eh_frame.

Its a PR34648 which was a segfault that happened because
we stored pointers to elements in DenseMap. 
When DenseMap grows such pointers are invalidated.
Solution implemented is to keep elements by pointer
and not by value.

Differential revision: https://reviews.llvm.org/D38034
------------------------------------------------------------------------

llvm-svn: 314860
2017-10-03 23:42:47 +00:00
Renato Golin
08d41dde76 [release_50] Merging r313916
[AArch64] Fix bug in store of vector 0 DAGCombine.

Summary:
Avoid using XZR/WZR directly as operands to split stores of zero
vectors.  Doing so can lead to the XZR/WZR being used by an instruction
that doesn't allow it (e.g. add).

Fixes bug 34674.

Reviewers: t.p.northover, efriedma, MatzeB

Subscribers: aemerson, rengolin, javed.absar, mcrosier, eraman, llvm-commits, kristof.beyls

Differential Revision: https://reviews.llvm.org/D38146

PR34695.

llvm-svn: 314796
2017-10-03 13:13:34 +00:00
Tom Stellard
84c46fba40 Merging r313392:
------------------------------------------------------------------------
r313392 | ctopper | 2017-09-15 13:27:59 -0700 (Fri, 15 Sep 2017) | 7 lines

[X86] Disable _mm512_maskz_set1_epi64 intrinsic on 32-bit targets to prevent a backend isel failure.

The __builtin_ia32_pbroadcastq512_mem_mask we were previously trying to use in 32-bit mode is not implemented in the x86 backend and causes isel to fail in release builds. In debug builds it fails even earlier during legalization with an llvm_unreachable.

While there add the missing test case for this intrinsic for this for 64-bit mode.

This fixes PR34631. D37668 should be able to recover this for 32-bit mode soon. But I wanted to fix the crash ahead of that.
------------------------------------------------------------------------

llvm-svn: 314569
2017-09-29 23:52:26 +00:00
Tom Stellard
dead2486d3 Merging r311951 and r312038:
------------------------------------------------------------------------
r311951 | adrian | 2017-08-28 16:07:43 -0700 (Mon, 28 Aug 2017) | 6 lines

Fix a logic error in DwarfExpression::addMachineReg()

This fixes PR34323 and thus splitting undescribable registers into
smaller, describable sub-registers.

https://bugs.llvm.org/show_bug.cgi?id=34323
------------------------------------------------------------------------

------------------------------------------------------------------------
r312038 | joerg | 2017-08-29 14:18:07 -0700 (Tue, 29 Aug 2017) | 2 lines

Simplify test case, so that it works for both trunk and release-5.0.

------------------------------------------------------------------------

llvm-svn: 314567
2017-09-29 23:39:09 +00:00
Tom Stellard
1c536006b3 Merging r312348:
------------------------------------------------------------------------
r312348 | matze | 2017-09-01 11:36:26 -0700 (Fri, 01 Sep 2017) | 39 lines

LiveIntervalAnalysis: Fix alias regunit reserved definition

A register in CodeGen can be marked as reserved: In that case we
consider the register always live and do not use (or rather ignore)
kill/dead/undef operand flags.

LiveIntervalAnalysis however tracks liveness per register unit (not per
register). We already needed adjustments for this in r292871 to deal
with super/sub registers. However I did not look at aliased register
there. Looking at ARM:

FPSCR (regunits FPSCR, FPSCR~FPSCR_NZCV) aliases with FPSCR_NZCV
(regunits FPSCR_NZCV, FPSCR~FPSCR_NZCV) hence they share a register unit
(FPSCR~FPSCR_NZCV) that represents the aliased parts of the registers.
This shared register unit was previously considered non-reserved,
however given that we uses of the reserved FPSCR potentially violate
some rules (like uses without defs) we should make FPSCR~FPSCR_NZCV
reserved too and stop tracking liveness for it.

This patch:
- Defines a register unit as reserved when: At least for one root
  register, the root register and all its super registers are reserved.
- Adjust LiveIntervals::computeRegUnitRange() for new reserved
  definition.
- Add MachineRegisterInfo::isReservedRegUnit() to have a canonical way
  of testing.
- Stop computing LiveRanges for reserved register units in HMEditor even
  with UpdateFlags enabled.
- Skip verification of uses of reserved reg units in the machine
  verifier (this usually didn't happen because there would be no cached
  liverange but there is no guarantee for that and I would run into this
  case before the HMEditor tweak, so may as well fix the verifier too).

Note that this should only affect ARMs FPSCR/FPSCR_NZCV registers today;
aliased registers are rarely used, the only other cases are hexagons
P0-P3/P3_0 and C8/USR pairs which are not mixing reserved/non-reserved
registers in an alias.

Differential Revision: https://reviews.llvm.org/D37356
------------------------------------------------------------------------

llvm-svn: 314565
2017-09-29 23:22:57 +00:00
Tom Stellard
ed5c0ab4df Merging r314252:
------------------------------------------------------------------------
r314252 | gberry | 2017-09-26 14:40:46 -0700 (Tue, 26 Sep 2017) | 12 lines

[AArch64][Falkor] Fix bug in falkor prefetcher fix pass.

Summary:
In rare cases, loads that don't get prefetched that were marked as
strided loads could cause a crash if they occurred in a loop with other
colliding loads.

Reviewers: mcrosier

Subscribers: aemerson, rengolin, javed.absar, kristof.beyls

Differential Revision: https://reviews.llvm.org/D38261
------------------------------------------------------------------------

llvm-svn: 314555
2017-09-29 20:35:06 +00:00
Tom Stellard
7507fd1c71 Merging r314251:
------------------------------------------------------------------------
r314251 | gberry | 2017-09-26 14:40:41 -0700 (Tue, 26 Sep 2017) | 16 lines

[AArch64][Falkor] Fix correctness bug in falkor prefetcher fix pass and correct some opcode tag computations.

Summary:
This addresses a correctness bug for LD[1234]*_POST opcodes that have
the prefetcher fix applied to them: the base register was not being
written back from the temp after being incremented, so it would appear
to never be incremented.

Also, fix some opcode tag computations based on some updated HW details
to get better tag avoidance and thus better prefetcher performance.

Reviewers: mcrosier

Subscribers: aemerson, rengolin, javed.absar, kristof.beyls

Differential Revision: https://reviews.llvm.org/D38256
------------------------------------------------------------------------

llvm-svn: 314554
2017-09-29 20:30:55 +00:00
Tom Stellard
4041da7a87 Merging r311599:
------------------------------------------------------------------------
r311599 | gberry | 2017-08-23 14:11:28 -0700 (Wed, 23 Aug 2017) | 4 lines

[AArch64][Falkor] Fix bug in Falkor HWPF tag collision avoidance

LDPDi was incorrectly marked as ignoring the destination register in the
prefetcher tag.
------------------------------------------------------------------------

llvm-svn: 314553
2017-09-29 20:26:51 +00:00
Tom Stellard
afaf296186 Merging r312447:
------------------------------------------------------------------------
r312447 | hfinkel | 2017-09-03 10:18:25 -0700 (Sun, 03 Sep 2017) | 12 lines

[CodeGen] Treat all vector fields as mayalias

Because it is common to treat vector types as an array of their elements, or
even some other type that's not the element type, and thus index into them, we
can't use struct-path TBAA for these accesses. Even though we already treat all
vector types as equivalent to 'char', we were using field-offset information
for them with TBAA, and this renders undefined the intra-value indexing we
intend to allow. Note that, although 'char' is universally aliasing, with path
TBAA, we can still differentiate between access to s.a and s.b in
  struct { char a, b; } s;. We can't use this capability as-is for vector types.

Fixes PR33967.
------------------------------------------------------------------------

llvm-svn: 314476
2017-09-28 23:41:39 +00:00
Tom Stellard
3c3efb4e6c Merging r312651:
------------------------------------------------------------------------
r312651 | jroelofs | 2017-09-06 10:09:25 -0700 (Wed, 06 Sep 2017) | 23 lines

Fix ARM bare metal driver to support atomics

The new bare metal support only supports the single thread model. This causes
the builtin atomic functions (e.g.: __atomic_fetch_add) to not generate
thread-safe assembly for these operations, which breaks our firmware. We target
bare metal, and need to atomically modify variables in our interrupt routines,
and task threads.

Internally, the -mthread-model flag determines whether to lower or expand
atomic operations (see D4984).

This change removes the overridden thread model methods, and instead relies on
the base ToolChain class to validate the thread model (which already includes
logic to validate single thread model support). If the single thread model is
required, the -mthread-model flag will have to be provided.

As a workaround "-mthread-model posix" could be provided, but it only works due
to a bug in the validation of the -mthread-model flag (separate patch coming to
fix this).

https://reviews.llvm.org/D37493

Patch by: Ian Tessier!
------------------------------------------------------------------------

llvm-svn: 314464
2017-09-28 21:57:43 +00:00
Tom Stellard
a9ebe38526 Merging r313998:
------------------------------------------------------------------------
r313998 | bmakam | 2017-09-22 10:46:36 -0700 (Fri, 22 Sep 2017) | 3 lines

    [Falkor] Add falkor CPU to host detection

    This returns "falkor" for Falkor CPU.
------------------------------------------------------------------------

llvm-svn: 314437
2017-09-28 17:52:12 +00:00
Tom Stellard
7c188fa829 Merging r312622:
------------------------------------------------------------------------
r312622 | jbcoe | 2017-09-06 00:33:32 -0700 (Wed, 06 Sep 2017) | 13 lines

Fix __repr__ for Diagnostic in clang.cindex

Summary: Also move misplaced tests for exception specification to fix failing Python tests.

Reviewers: hans, compnerd

Reviewed By: compnerd

Subscribers: cfe-commits

Tags: #clang-c

Differential Revision: https://reviews.llvm.org/D37490
------------------------------------------------------------------------

llvm-svn: 314434
2017-09-28 17:22:56 +00:00
Joerg Sonnenberger
722d0d2760 Merging r311921:
------------------------------------------------------------------------
r311921 | joerg | 2017-08-28 22:20:47 +0200 (Mon, 28 Aug 2017) | 16 lines

Fix ARMv4 support

ARMv4 doesn't support the "BX" instruction, which has been introduced
with ARMv4t. Adjust the call lowering and tail call implementation
accordingly.

Further changes are necessary to ensure that presence of the v4t feature
is correctly set. Most importantly, the "generic" CPU for thumb-*
triples should include ARMv4t, since thumb mode without thumb support
would naturally be pointless.

Add a couple of asserts to ensure thumb instructions are not emitted
without CPU support.

Differential Revision: https://reviews.llvm.org/D37030

------------------------------------------------------------------------

llvm-svn: 314417
2017-09-28 14:13:54 +00:00
Dylan McKay
c2f252c42c Merging r314180:
------------------------------------------------------------------------
r314180 | dylanmckay | 2017-09-26 13:51:03 +1300 (Tue, 26 Sep 2017) | 7 lines

[AVR] When lowering shifts into loops, put newly generated MBBs in the same
spot as the original MBB

Discovered in avr-rust/rust#62
https://github.com/avr-rust/rust/issues/62

Patch by Gergo Erdi.
------------------------------------------------------------------------

llvm-svn: 314383
2017-09-28 07:18:32 +00:00
Dylan McKay
6058b5f922 Merging r314183:
------------------------------------------------------------------------
r314183 | dylanmckay | 2017-09-26 15:07:54 +1300 (Tue, 26 Sep 2017) | 3 lines

[AVR] Fix the build after setting alignment to 1 in r314179

Changing all types to be byte-aligned broke a small number of tests.
------------------------------------------------------------------------

llvm-svn: 314382
2017-09-28 07:13:51 +00:00
Dylan McKay
bb93923aac Merging r314354:
------------------------------------------------------------------------
r314354 | dylanmckay | 2017-09-28 11:09:01 +1300 (Thu, 28 Sep 2017) | 3 lines

[AVR] Update data layout to match current LLVM trunk

The data layout was changed in r314179 to fix atomic loads and stores.
------------------------------------------------------------------------

llvm-svn: 314381
2017-09-28 07:06:54 +00:00
Dylan McKay
749ebdf766 Merging r314179:
------------------------------------------------------------------------
r314179 | dylanmckay | 2017-09-26 13:45:27 +1300 (Tue, 26 Sep 2017) | 11 lines

[AVR] Use 1-byte alignment for all data types

This was an oversight in the original backend data layout.

The AVR architecture does not have the concept of unaligned loads - all
loads/stores from all addresses are aligned to one byte.

Discovered in avr-rust issue #64
https://github.com/avr-rust/rust/issues/64

Patch By Gergo Erdi.
------------------------------------------------------------------------

llvm-svn: 314379
2017-09-28 06:16:45 +00:00
Dylan McKay
0200f2bf64 Merging r311620:
------------------------------------------------------------------------
r311620 | dylanmckay | 2017-08-24 12:14:38 +1200 (Thu, 24 Aug 2017) | 1 line

[AVR] Use the correct register classes for 16-bit atomic operations
------------------------------------------------------------------------

llvm-svn: 314358
2017-09-27 22:18:57 +00:00
Dylan McKay
51d9915350 Merging r314070:
------------------------------------------------------------------------
r314070 | dylanmckay | 2017-09-24 14:07:26 +1300 (Sun, 24 Sep 2017) | 6 lines

[AVR] Implement getCmpLibcallReturnType().

This fixes the avr-rust issue (#75) with floating-point comparisons generating broken code.
By default, LLVM assumes these comparisons return 32-bit values, but ours are 8-bit.

Patch By Thomas Backman.
------------------------------------------------------------------------

llvm-svn: 314357
2017-09-27 22:17:11 +00:00
Dylan McKay
34c887f155 Merging r312905:
------------------------------------------------------------------------
r312905 | dylanmckay | 2017-09-11 22:32:51 +1200 (Mon, 11 Sep 2017) | 10 lines

[AVR] Enable the '__do_copy_data' function

Also enables '__do_clear_bss'.

These functions are automaticalled called by the CRT if they are
declared.

We need these to be called otherwise RAM will start completely
uninitialised, even though we need to copy RAM variables from progmem to
RAM.
------------------------------------------------------------------------

llvm-svn: 314356
2017-09-27 22:15:50 +00:00
Tom Stellard
7f6d22cdd8 Merging r312337:
------------------------------------------------------------------------
r312337 | nha | 2017-09-01 09:56:32 -0700 (Fri, 01 Sep 2017) | 12 lines

AMDGPU: IMPLICIT_DEFs and DBG_VALUEs do not contribute to wait states

Summary:
This fixes a bug that was exposed on gfx9 in various
GL45-CTS.shaders.loops.*_iterations.select_iteration_count_fragment tests,
e.g. GL45-CTS.shaders.loops.do_while_uniform_iterations.select_iteration_count_fragment

Reviewers: arsenm

Subscribers: kzhuravl, wdng, yaxunl, dstuttard, tpr, t-tye, llvm-commits

Differential Revision: https://reviews.llvm.org/D36193
------------------------------------------------------------------------

llvm-svn: 314327
2017-09-27 18:08:25 +00:00
Tom Stellard
14adbd0d8b Revert "Merging r312337:"
This reverts commit r314324.

I unintentionally deleted most of the svn:mergeinfo for the release_50
branch with this commit.

llvm-svn: 314326
2017-09-27 18:06:46 +00:00
Tom Stellard
95eb0d9490 Merging r312337:
------------------------------------------------------------------------
r312337 | nha | 2017-09-01 09:56:32 -0700 (Fri, 01 Sep 2017) | 12 lines

AMDGPU: IMPLICIT_DEFs and DBG_VALUEs do not contribute to wait states

Summary:
This fixes a bug that was exposed on gfx9 in various
GL45-CTS.shaders.loops.*_iterations.select_iteration_count_fragment tests,
e.g. GL45-CTS.shaders.loops.do_while_uniform_iterations.select_iteration_count_fragment

Reviewers: arsenm

Subscribers: kzhuravl, wdng, yaxunl, dstuttard, tpr, t-tye, llvm-commits

Differential Revision: https://reviews.llvm.org/D36193
------------------------------------------------------------------------

llvm-svn: 314324
2017-09-27 17:56:19 +00:00
Tom Stellard
ddd861d8f0 Bump version to 5.0.1
llvm-svn: 313339
2017-09-15 04:05:37 +00:00
Tom Stellard
6442f8f876 Merging r313334:
------------------------------------------------------------------------
r313334 | tstellar | 2017-09-14 19:25:22 -0700 (Thu, 14 Sep 2017) | 15 lines

merge-request.sh: Update to use new "Fixed by Commit(s)" field

Summary:
This will be used instead of the url field to track which commits need
to be merged.

This patch also drops support for version 1.x of the bugzilla CLI tool.

Reviewers: hansw, hans

Reviewed By: hans

Subscribers: hans, llvm-commits

Differential Revision: https://reviews.llvm.org/D37786
------------------------------------------------------------------------

llvm-svn: 313337
2017-09-15 03:05:55 +00:00
Hans Wennborg
a7a5059842 Merging r312285:
------------------------------------------------------------------------
r312285 | ctopper | 2017-08-31 14:39:23 -0700 (Thu, 31 Aug 2017) | 11 lines

[X86] Don't pull carry through X86ISD::ADD carryin, -1 if we can't guranteed we're really using the carry flag from the add.

Prior to this patch we had a DAG combine that tried to bypass an X86ISD::ADD with -1 being added to the carry flag of some previous operation. We would then pass the carry flag directly to user.

But this is only safe if the user is looking for the carry flag and not the zero flag.

So we need to only do this combine in a context where we know what flag the consumer is using.

Fixes PR34381.

Differential Revision: https://reviews.llvm.org/D37317
------------------------------------------------------------------------

llvm-svn: 312333
2017-09-01 16:28:52 +00:00
Richard Smith
a679b0d880 Mention the expected change to default -std= in future clang releases.
llvm-svn: 312293
2017-08-31 23:19:49 +00:00
Richard Smith
e6d17f269a Consistently use code font for command-line flags in the release notes.
llvm-svn: 312189
2017-08-30 23:03:58 +00:00
Richard Smith
14bea5767e Add a couple of release note updates for C++ changes since Clang 4.
llvm-svn: 312187
2017-08-30 22:58:37 +00:00
Hans Wennborg
1f646c235c ReleaseNotes: one back-tick too many
llvm-svn: 312155
2017-08-30 18:43:04 +00:00
Hans Wennborg
df7de19749 ReleaseNotes: remove another in-progress warning
llvm-svn: 312153
2017-08-30 18:38:40 +00:00
Hans Wennborg
8ecb8673fa ReleaseNotes: remove another in-progress warning
llvm-svn: 312152
2017-08-30 18:38:07 +00:00
Hans Wennborg
f3872bfdd9 Merging r312149:
------------------------------------------------------------------------
r312149 | hans | 2017-08-30 11:35:44 -0700 (Wed, 30 Aug 2017) | 1 line

docs: typo fix
------------------------------------------------------------------------

llvm-svn: 312150
2017-08-30 18:36:09 +00:00
Hans Wennborg
656a28815c Merging r312022:
------------------------------------------------------------------------
r312022 | hans | 2017-08-29 11:41:00 -0700 (Tue, 29 Aug 2017) | 10 lines

[DAG] Bound loop dependence check in merge optimization.

The loop dependence check looks for dependencies between store merge
candidates not captured by the chain sub-DAG doing a check of
predecessors which may be very large. Conservatively bound number of
nodes checked for compilation time. (Resolves PR34326).

Landing on behalf of Nirav Dave to unblock the 5.0.0 release.

Differential Revision: https://reviews.llvm.org/D37220
------------------------------------------------------------------------

llvm-svn: 312041
2017-08-29 21:38:44 +00:00
Hans Wennborg
f0701b2b85 Merging r312008:
------------------------------------------------------------------------
r312008 | cbieneman | 2017-08-29 09:13:41 -0700 (Tue, 29 Aug 2017) | 7 lines

[IPv6] Fix a bug in the IPv6 listen behavior

The socket bind address should either be localhost or anyaddress. This bug in the listen behavior was preventing lldb-server from opening sockets for non-localhost connections.

The added test verifies that opening an anyaddress socket works and has a non-zero port assignment.

This should resolve PR34183.
------------------------------------------------------------------------

llvm-svn: 312016
2017-08-29 17:33:27 +00:00
Hans Wennborg
828b681314 Merging r311835:
------------------------------------------------------------------------
r311835 | dhinton | 2017-08-26 14:08:51 -0700 (Sat, 26 Aug 2017) | 12 lines

[Dominators] Remove redundant explicit template instantiation.

Summary:
Remove redundant explicit template instantiation.

This was reported by Andrew Kelley building release_50 with gcc7.2.0 on MacOS: duplicate symbol llvm::DominatorTreeBase.

Reviewers: kuhar, andrewrk, davide, hans

Subscribers: llvm-commits

Differential Revision: https://reviews.llvm.org/D37185
------------------------------------------------------------------------

llvm-svn: 312014
2017-08-29 17:17:42 +00:00
Hans Wennborg
a18e824abb Merging r311823: (+update ClangCommandLineReference.rst)
------------------------------------------------------------------------
r311823 | rsmith | 2017-08-25 18:04:35 -0700 (Fri, 25 Aug 2017) | 16 lines

Add flag to request Clang is ABI-compatible with older versions of itself

This patch adds a flag -fclang-abi-compat that can be used to request that
Clang attempts to be ABI-compatible with some older version of itself.

This is provided on a best-effort basis; right now, this can be used to undo
the ABI change in r310401, reverting Clang to its prior C++ ABI for pass/return
by value of class types affected by that change, and to undo the ABI change in
r262688, reverting Clang to using integer registers rather than SSE registers
for passing <1 x long long> vectors. The intent is that we will maintain this
backwards compatibility path as we make ABI-breaking fixes in future.

The reversion to the old behavior for r310401 is also applied to the PS4 target
since that change is not part of its platform ABI (which is essentially to do
whatever Clang 3.2 did).

------------------------------------------------------------------------

llvm-svn: 312013
2017-08-29 17:13:55 +00:00
Hans Wennborg
fccffd72af ReleaseNotes: NetBSD LLDB improvements
By Kamil Rytarowski!

llvm-svn: 311932
2017-08-28 20:53:38 +00:00
Hans Wennborg
dae3c15512 ReleaseNotes: llvm-dlltool
By Martell Malone!

llvm-svn: 311927
2017-08-28 20:31:49 +00:00
Hans Wennborg
16b72b1d7e ReleaseNotes: LLVM_REVERSE_ITERATION
By Mandeep Singh Grang!

llvm-svn: 311919
2017-08-28 20:16:59 +00:00
Hans Wennborg
f38cbf36c3 index.rst: Remove doxygen link which doesn't work
llvm-svn: 311910
2017-08-28 19:38:12 +00:00
Hans Wennborg
74b83365ac index.rst: remove in-progress notice
llvm-svn: 311909
2017-08-28 19:36:56 +00:00
Hans Wennborg
16b04ba257 Merging r311792:
------------------------------------------------------------------------
r311792 | djasper | 2017-08-25 12:14:53 -0700 (Fri, 25 Aug 2017) | 9 lines

[Format] Invert nestingAndIndentLevel pair in WhitespaceManager used for
alignments

Indent should be compared before nesting level to determine if a token
is on the same scope as the one we align with. Because it was inverted,
clang-format sometimes tried to align tokens with tokens from outer
scopes, causing the assert(Shift >= 0) to fire.

This fixes bug #33507. Patch by Beren Minor, thank you!
------------------------------------------------------------------------

llvm-svn: 311800
2017-08-25 20:30:43 +00:00
Hans Wennborg
6493242f86 Merging r311695:
------------------------------------------------------------------------
r311695 | rsmith | 2017-08-24 13:10:33 -0700 (Thu, 24 Aug 2017) | 9 lines

[ubsan] PR34266: When sanitizing the 'this' value for a member function that happens to be a lambda call operator, use the lambda's 'this' pointer, not the captured enclosing 'this' pointer (if any).

Do not sanitize the 'this' pointer of a member call operator for a lambda with
no capture-default, since that call operator can legitimately be called with a
null this pointer from the static invoker function. Any actual call with a null
this pointer should still be caught in the caller (if it is being sanitized).

This reinstates r311589 (reverted in r311680) with the above fix.

------------------------------------------------------------------------

llvm-svn: 311799
2017-08-25 20:27:58 +00:00
Simon Dardis
f84d026a4a [mips][Release Notes] Release notes for 5.0
Reviewers: atanasyan, nitesh.jain

Differential Revision: https://reviews.llvm.org/D37077

llvm-svn: 311771
2017-08-25 09:57:29 +00:00
Hans Wennborg
419b8efe58 ReleaseNotes: Note about opt-viewer.py, by Adam Nemet
llvm-svn: 311738
2017-08-25 00:42:51 +00:00
Hans Wennborg
1c2f283db5 Merging r311674:
------------------------------------------------------------------------
r311674 | hans | 2017-08-24 10:00:36 -0700 (Thu, 24 Aug 2017) | 3 lines

Mark allocator_oom_test.cc unsupported on arm & aarch64 (PR33972)

The buildbots don't seem to like it.
------------------------------------------------------------------------

llvm-svn: 311736
2017-08-25 00:31:02 +00:00
Eric Fiselier
3d589e8dad Update ABI lists for 5.0
llvm-svn: 311735
2017-08-25 00:19:47 +00:00
Hans Wennborg
46c4cf6886 ReleaseNotes: typo
llvm-svn: 311729
2017-08-24 22:56:18 +00:00
Hans Wennborg
51f757871d ReleaseNotes: remove one more in-progress warning
llvm-svn: 311728
2017-08-24 22:54:37 +00:00
Hans Wennborg
b9ce1590b7 ReleaseNotes: minor touch-ups
llvm-svn: 311725
2017-08-24 22:50:05 +00:00
Hans Wennborg
6ca1e06c95 ReleaseNotes: drop in-progress warning
llvm-svn: 311724
2017-08-24 22:48:26 +00:00
Hans Wennborg
0ce6a33e7a ReleaseNotes: minor touch-ups
llvm-svn: 311723
2017-08-24 22:47:33 +00:00
Hans Wennborg
a17696cb85 ReleaseNotes: drop in-progress warning
llvm-svn: 311722
2017-08-24 22:44:30 +00:00
Hans Wennborg
e6bf68455a ReleaseNotes: remove boilerplate
llvm-svn: 311721
2017-08-24 22:43:29 +00:00
Hans Wennborg
89116b027c ReleaseNotes: drop in-progress warning
llvm-svn: 311718
2017-08-24 22:39:11 +00:00
Hans Wennborg
66b13fef46 ReleaseNotes: remove boiler-plate, and minor fixes
llvm-svn: 311717
2017-08-24 22:38:21 +00:00
Hans Wennborg
f4ca6971c5 ReleaseNotes: drop in-progress warning
llvm-svn: 311716
2017-08-24 22:34:18 +00:00
Hans Wennborg
2da4f8c736 ReleaseNotes: remove boiler-plate, and minor fixes
llvm-svn: 311715
2017-08-24 22:32:10 +00:00
Hans Wennborg
f37549fe0e ReleaseNotes: remove in-progress warning
llvm-svn: 311714
2017-08-24 22:25:24 +00:00
Hans Wennborg
72315f1506 Merging r311601:
------------------------------------------------------------------------
r311601 | adrian | 2017-08-23 14:24:12 -0700 (Wed, 23 Aug 2017) | 5 lines

Fix a bug in CGDebugInfo::EmitInlineFunctionStart causing DILocations to be
parented in function declarations.

Fixes PR33997.
https://bugs.llvm.org/show_bug.cgi?id=33997
------------------------------------------------------------------------

llvm-svn: 311671
2017-08-24 16:21:49 +00:00
Hans Wennborg
5a4a37705d Merging r311623:
------------------------------------------------------------------------
r311623 | hans | 2017-08-23 18:08:27 -0700 (Wed, 23 Aug 2017) | 11 lines

[DAG] Fix Node Replacement in PromoteIntBinOp

When one operand is a user of another in a promoted binary operation
we may replace and delete the returned value before returning
triggering an assertion. Reorder node replacements to prevent this.

Fixes PR34137.

Landing on behalf of Nirav.

Differential Revision: https://reviews.llvm.org/D36581
------------------------------------------------------------------------

llvm-svn: 311670
2017-08-24 16:16:07 +00:00
Hans Wennborg
387479f758 Release Notes fix
Patch by Marek Kurdej!

llvm-svn: 311668
2017-08-24 15:49:39 +00:00
Hans Wennborg
ab640dfb84 Merging r311555:
------------------------------------------------------------------------
r311555 | oleg | 2017-08-23 07:26:31 -0700 (Wed, 23 Aug 2017) | 14 lines

[ARM][Compiler-rt] Fix AEABI builtins to correctly pass arguments to non-AEABI functions on HF targets

Summary:
This is a patch for PR34167.

On HF targets functions like `__{eq,lt,le,ge,gt}df2` and `__{eq,lt,le,ge,gt}sf2` expect their arguments to be passed in d/s registers, while some of the AEABI builtins pass them in r registers.

Reviewers: compnerd, peter.smith, asl

Reviewed By: peter.smith, asl

Subscribers: peter.smith, aemerson, dberris, javed.absar, llvm-commits, asl, kristof.beyls

Differential Revision: https://reviews.llvm.org/D36675
------------------------------------------------------------------------

llvm-svn: 311606
2017-08-23 21:38:59 +00:00
Hans Wennborg
5f78a79e30 Merging r311554:
------------------------------------------------------------------------
r311554 | mcrosier | 2017-08-23 07:10:06 -0700 (Wed, 23 Aug 2017) | 10 lines

[Reassociate] Don't canonicalize x + (-Constant * y) -> x - (Constant * y)..

..if the resulting subtract will be broken up later.  This can cause us to get
into an infinite loop.

x + (-5.0 * y)      -> x - (5.0 * y)       ; Canonicalize neg const
x - (5.0 * y)       -> x + (0 - (5.0 * y)) ; Break up subtract
x + (0 - (5.0 * y)) -> x + (-5.0 * y)      ; Replace 0-X with X*-1.

PR34078
------------------------------------------------------------------------

llvm-svn: 311603
2017-08-23 21:33:38 +00:00
Hans Wennborg
a58f36d2e5 Merging r311565:
------------------------------------------------------------------------
r311565 | hans | 2017-08-23 08:43:28 -0700 (Wed, 23 Aug 2017) | 8 lines

LowerAtomic: Don't skip optnone functions; atomic still need lowering (PR34020)

The lowering isn't really an optimization, so optnone shouldn't make a
difference. ARM relies on the pass running when using "-mthread-model
single", because in that mode, it doesn't run AtomicExpand. See bug for
more details.

Differential Revision: https://reviews.llvm.org/D37040
------------------------------------------------------------------------

llvm-svn: 311602
2017-08-23 21:30:37 +00:00
Hans Wennborg
8f166cc642 Revert r307529 "This patch completely replaces the scheduling information for the SandyBridge architecture"
This caused PR34080, which seems to have been fixed by r310792, but that change
introduced severe performance regressions.

Reverting to unblock the 5.0.0 release while these issues are worked out on trunk.

Also reverting a few tests that were added later and depended on the new scheduling:

    LLVM :: CodeGen/X86/f16c-schedule.ll
    LLVM :: CodeGen/X86/lea32-schedule.ll
    LLVM :: CodeGen/X86/lea64-schedule.ll
    LLVM :: CodeGen/X86/popcnt-schedule.ll

llvm-svn: 311600
2017-08-23 21:17:15 +00:00
Hans Wennborg
1bbc6d0018 Revert r309328 and r309290 (which merged r309327 and r309226).
The header change caused problems; see PR34182, and PR33858 from #9 onwards, as
well as the discussion on the r309226 cfe-commits thread.

These changes don't seem to be addressing any regression from 4.0.0, so rather
than scrambling to fix this on the branch, let's revert to safety.

llvm-svn: 311597
2017-08-23 20:50:42 +00:00
Hans Wennborg
d0c62f909f Merging r311572:
------------------------------------------------------------------------
r311572 | ctopper | 2017-08-23 09:41:02 -0700 (Wed, 23 Aug 2017) | 9 lines

[AVX512] Don't create SHRUNKBLEND SDNodes for 512-bit vectors

There are no 512-bit blend instructions so we shouldn't create SHRUNKBLEND for them.

On a side note, it looks like there may be a missed opportunity for constant folding TESTM when LHS and RHS are equal.

This fixes PR34139.

Differential Revision: https://reviews.llvm.org/D36992
------------------------------------------------------------------------

llvm-svn: 311593
2017-08-23 20:03:43 +00:00
Hans Wennborg
301eb2b8c6 Merging r311330:
------------------------------------------------------------------------
r311330 | ibiryukov | 2017-08-21 05:03:08 -0700 (Mon, 21 Aug 2017) | 16 lines

Fixed a crash on replaying Preamble's PP conditional stack.

Summary:
The crash occurs when the first token after a preamble is a macro
expansion.
Fixed by moving replayPreambleConditionalStack from Parser into
Preprocessor. It is now called right after the predefines file is
processed.

Reviewers: erikjv, bkramer, klimek, yvvan

Reviewed By: bkramer

Subscribers: cfe-commits

Differential Revision: https://reviews.llvm.org/D36872
------------------------------------------------------------------------

llvm-svn: 311591
2017-08-23 19:56:39 +00:00
Hans Wennborg
5b257ba214 Merging r311579:
------------------------------------------------------------------------
r311579 | compnerd | 2017-08-23 10:23:12 -0700 (Wed, 23 Aug 2017) | 6 lines

Process: fix FXSAVE on x86

The FXSAVE member `ftw` (FPU Tag Word) was given the wrong size (8-bit)
instead of the correct width (16-bit) as per the x87 Programmer's
Manual.  Adjust this to ensure that we print out the complete value for
the register.
------------------------------------------------------------------------

llvm-svn: 311585
2017-08-23 18:41:31 +00:00
Hans Wennborg
76c1c287a8 Merging r311496:
------------------------------------------------------------------------
r311496 | hans | 2017-08-22 14:54:37 -0700 (Tue, 22 Aug 2017) | 1 line

[profile] Fix warning about C++ style comment in C file
------------------------------------------------------------------------

llvm-svn: 311584
2017-08-23 18:09:02 +00:00
Hans Wennborg
9c1a363fc7 Merging r311495:
------------------------------------------------------------------------
r311495 | hans | 2017-08-22 14:54:37 -0700 (Tue, 22 Aug 2017) | 6 lines

[esan] Use stack_t instead of struct sigaltstack (PR34011)

The struct tag is going away in soon-to-be-released glibc 2.26 and the
stack_t typedef seems to have been there forever.

Patch by Bernhard Rosenkraenzer!
------------------------------------------------------------------------

llvm-svn: 311583
2017-08-23 18:07:44 +00:00
Renato Golin
c3f2f85c33 [ARM] more release notes updates for 5.0
llvm-svn: 311578
2017-08-23 17:04:59 +00:00
Hans Wennborg
d3baa293ae Merging r311532:
------------------------------------------------------------------------
r311532 | krasimir | 2017-08-23 00:18:36 -0700 (Wed, 23 Aug 2017) | 24 lines

[clang-format] Align trailing comments if ColumnLimit is 0

Summary:
ColumnLimit = 0 means no limit, so comment should always be aligned if requested. This was broken with

  https://llvm.org/svn/llvm-project/cfe/trunk@304687

introduced via

  https://reviews.llvm.org/D33830

and is included in 5.0.0-rc2. This commit fixes it and adds a unittest for this property.

Should go into clang-5.0 IMHO.

Contributed by @pboettch!

Reviewers: djasper, krasimir

Reviewed By: djasper, krasimir

Subscribers: hans, klimek

Differential Revision: https://reviews.llvm.org/D36967
------------------------------------------------------------------------

llvm-svn: 311573
2017-08-23 16:49:21 +00:00
Florian Hahn
a2c40bdbaf [RelNotes,AArch64] Mention improved instruction fusion and fun alignment.
Reviewers: t.p.northover, hans, kristof.beyls

Reviewed By: hans

Subscribers: aemerson, rengolin, llvm-commits

Differential Revision: https://reviews.llvm.org/D36965

llvm-svn: 311539
2017-08-23 09:12:41 +00:00
Hans Wennborg
5e5333b736 Merging r311397:
------------------------------------------------------------------------
r311397 | ahatanak | 2017-08-21 15:46:46 -0700 (Mon, 21 Aug 2017) | 8 lines

[Driver][Darwin] Do not pass -munwind-table if -fno-excpetions is
supplied.

With this change, -fno-exceptions disables unwind tables unless
-funwind-tables is supplied too or the target is x86-64 (x86-64 requires
emitting unwind tables).

rdar://problem/33934446
------------------------------------------------------------------------

llvm-svn: 311505
2017-08-22 22:27:59 +00:00
Hans Wennborg
fc37a76cd7 Merging r311391:
------------------------------------------------------------------------
r311391 | stl_msft | 2017-08-21 15:19:33 -0700 (Mon, 21 Aug 2017) | 28 lines

[Driver] Recognize DevDiv internal builds of MSVC, with a different directory structure.

This is a reasonably non-intrusive change, which I've verified
works for both x86 and x64 DevDiv-internal builds.

The idea is to change `bool IsVS2017OrNewer` into a 3-state
`ToolsetLayout VSLayout`. Either a build is DevDiv-internal,
released VS 2017 or newer, or released VS 2015 or older. When looking at
the directory structure, if instead of `"VC"` we see `"x86ret"`, `"x86chk"`,
`"amd64ret"`, or `"amd64chk"`, we recognize this as a DevDiv-internal build.

After we get past the directory structure validation, we use this knowledge
to regenerate paths appropriately. `llvmArchToDevDivInternalArch()` knows how
we use `"i386"` subdirectories, and `MSVCToolChain::getSubDirectoryPath()`
uses that. It also knows that DevDiv-internal builds have an `"inc"`
subdirectory instead of `"include"`.

This may still not be the "right" fix in any sense, but I believe that it's
non-intrusive in the sense that if the special directory names aren't found,
no codepaths are affected. (`ToolsetLayout::OlderVS` and
`ToolsetLayout::VS2017OrNewer` correspond to `IsVS2017OrNewer` being `false`
or `true`, respectively.) I searched for all references to `IsVS2017OrNewer`,
which are places where Clang cares about VS's directory structure, and the
only one that isn't being patched is some logic to deal with
cross-compilation. I'm fine with that not working for DevDiv-internal builds
for the moment (we typically test the native compilers), so I added a comment.

Fixes D36860.
------------------------------------------------------------------------

llvm-svn: 311500
2017-08-22 22:01:04 +00:00
Kit Barton
6db7036401 [Docs] Update release notes for PPC
llvm-svn: 311486
2017-08-22 19:56:41 +00:00
Anastasia Stulova
d43534a1e6 [Docs] Added release notes for OpenCL.
Differential Revision: https://reviews.llvm.org/D36951

llvm-svn: 311485
2017-08-22 19:29:27 +00:00
Hans Wennborg
002ca6e8fc Merging r311387:
------------------------------------------------------------------------
r311387 | steven_wu | 2017-08-21 14:49:13 -0700 (Mon, 21 Aug 2017) | 16 lines

[IR] AutoUpgrade ModuleFlagBehavior for PIC and PIE level

Summary:
From r303590, ModuleFlagBehavior for PIC and PIE level is changed from
Error to Max. This will cause bitcode compatibility issue when linking
against a bitcode static archive built with old compiler.
Add an auto-ugprade path to upgrade the the ModuleFlagBehavior in the
old bitcode to match the new one so IRLinker can link them.

Reviewers: tejohnson, mehdi_amini, dexonsmith

Reviewed By: dexonsmith

Subscribers: hans, llvm-commits

Differential Revision: https://reviews.llvm.org/D36556
------------------------------------------------------------------------

llvm-svn: 311481
2017-08-22 18:19:41 +00:00
Hans Wennborg
0955a0821d Merging r311263:
------------------------------------------------------------------------
r311263 | ctopper | 2017-08-19 15:02:02 -0700 (Sat, 19 Aug 2017) | 1 line

[AVX512] Use alignedstore256 in a pattern that's emitting a 256-bit movaps from an extract subvector operation.
------------------------------------------------------------------------

llvm-svn: 311478
2017-08-22 17:44:59 +00:00
Hans Wennborg
8aef319e0a ReleaseNotes: coroutines update from Gor
llvm-svn: 311475
2017-08-22 17:41:05 +00:00
Hans Wennborg
e34082cd2e Merging r311443:
------------------------------------------------------------------------
r311443 | arphaman | 2017-08-22 03:38:07 -0700 (Tue, 22 Aug 2017) | 15 lines

[ObjC] Check written attributes only when synthesizing ambiguous property

This commit fixes a bug introduced in r307903. The attribute ambiguity checker
that was introduced in r307903 checked all property attributes, which caused
errors for source-compatible properties, like:

@property (nonatomic, readonly) NSObject *prop;
@property (nonatomic, readwrite) NSObject *prop;

because the readwrite property would get implicit 'strong' attribute. The
ambiguity checker should be concerned about explicitly specified attributes
only.

rdar://33748089

------------------------------------------------------------------------

llvm-svn: 311464
2017-08-22 16:23:19 +00:00
Hans Wennborg
532ae22185 Merging r311429:
------------------------------------------------------------------------
r311429 | ctopper | 2017-08-21 22:40:17 -0700 (Mon, 21 Aug 2017) | 9 lines

[X86] Prevent several calls to ISD::isConstantSplatVector from returning a narrower APInt than the original scalar type

ISD::isConstantSplatVector can shrink to the smallest splat width. But we don't check the size of the resulting APInt at all. This can cause us to misinterpret the results.

This patch just adds a flag to prevent the APInt from changing width.

Fixes PR34271.

Differential Revision: https://reviews.llvm.org/D36996
------------------------------------------------------------------------

llvm-svn: 311462
2017-08-22 16:17:32 +00:00
Hans Wennborg
25b4363457 Merging r311061:
------------------------------------------------------------------------
r311061 | compnerd | 2017-08-16 19:42:24 -0700 (Wed, 16 Aug 2017) | 10 lines

ARM: mark CPSR as clobbered for Windows VLAs

When lowering a VLA, we emit a __chstk call.  However, this call can
internally clobber CPSR.  We did not mark this register as an ImpDef,
which could potentially allow a comparison to be hoisted above the call
to `__chkstk`.  In such a case, the CPSR could be clobbered, and the
check invalidated.  When the support was initially added, it seemed that
the call would take care of preventing CPSR from being clobbered, but
this is not the case.  Mark the register as clobbered to fix a possible
state corruption.
------------------------------------------------------------------------

llvm-svn: 311461
2017-08-22 16:09:55 +00:00
Florian Hahn
314ce05cba [RelNotes,ARM] Mention improved ARM/Thumb codegen and LTO.
Reviewers: echristo, rengolin, kristof.beyls, hans, t.p.northover

Reviewed By: hans

Subscribers: aemerson, inglorion, llvm-commits

Differential Revision: https://reviews.llvm.org/D36968

llvm-svn: 311460
2017-08-22 16:01:04 +00:00
Alex Lorenz
130f6085c2 Mention libclang code-completion changes in release notes
llvm-svn: 311455
2017-08-22 13:36:03 +00:00
Alex Lorenz
cf7623706d Mention #pragma pack PCH serialization change in release notes
llvm-svn: 311453
2017-08-22 13:23:54 +00:00
Alex Lorenz
f54ac07c7e Mention #pragma clang attribute in the release notes
llvm-svn: 311452
2017-08-22 13:15:19 +00:00
Alex Lorenz
e204970b96 Mention the ObjC property synthesis changes in release notes
llvm-svn: 311451
2017-08-22 13:11:19 +00:00
Simon Dardis
98b234054b [Sema] Update release notes with details of implicit scalar to vector conversions
Add notes on this to the C language section, along with the C++ section.

Reviewers: bruno, hans

Differential Revision: https://reviews.llvm.org/D36954

llvm-svn: 311441
2017-08-22 10:01:35 +00:00
Hans Wennborg
3288db6b38 Merging r310983:
------------------------------------------------------------------------
r310983 | rsmith | 2017-08-15 18:49:53 -0700 (Tue, 15 Aug 2017) | 31 lines

PR19668, PR23034: Fix handling of move constructors and deleted copy
constructors when deciding whether classes should be passed indirectly.

This fixes ABI differences between Clang and GCC:

 * Previously, Clang ignored the move constructor when making this
   determination. It now takes the move constructor into account, per
   https://github.com/itanium-cxx-abi/cxx-abi/pull/17 (this change may
   seem recent, but the ABI change was agreed on the Itanium C++ ABI
   list a long time ago).

 * Previously, Clang's behavior when the copy constructor was deleted
   was unstable -- depending on whether the lazy declaration of the
   copy constructor had been triggered, you might get different behavior.
   We now eagerly declare the copy constructor whenever its deletedness
   is unclear, and ignore deleted copy/move constructors when looking for
   a trivial such constructor.

This also fixes an ABI difference between Clang and MSVC:

 * If the copy constructor would be implicitly deleted (but has not been
   lazily declared yet), for instance because the class has an rvalue
   reference member, we would pass it directly. We now pass such a class
   indirectly, matching MSVC.

Based on a patch by Vassil Vassilev, which was based on a patch by Bernd
Schmidt, which was based on a patch by Reid Kleckner!

This is a re-commit of r310401, which was reverted in r310464 due to ARM
failures (which should now be fixed).

------------------------------------------------------------------------

llvm-svn: 311410
2017-08-21 23:40:02 +00:00
Hans Wennborg
6d9d605865 Merging r311071:
------------------------------------------------------------------------
r311071 | eladcohen | 2017-08-17 01:06:36 -0700 (Thu, 17 Aug 2017) | 13 lines

[SelectionDAG] Teach the vector-types operand scalarizer about SETCC

When v1i1 is legal (e.g. AVX512) the legalizer can reach
a case where a v1i1 SETCC with an illgeal vector type operand
wasn't scalarized (since v1i1 is legal) but its operands does
have to be scalarized. This used to assert because SETCC was
missing from the vector operand scalarizer.

This patch attemps to teach the legalizer to handle these cases
by scalazring the operands, converting the node into a scalar
SETCC node.

Differential revision: https://reviews.llvm.org/D36651
------------------------------------------------------------------------

llvm-svn: 311409
2017-08-21 23:28:04 +00:00
Hans Wennborg
0a641ff458 Merging r310990:
------------------------------------------------------------------------
r310990 | mstorsjo | 2017-08-15 22:18:36 -0700 (Tue, 15 Aug 2017) | 18 lines

[llvm-dlltool] Fix creating stdcall/fastcall import libraries for i386

Hook up the -k option (that in the original GNU dlltool removes the
@n suffix from the symbol that the final executable ends up linked to).

In llvm-dlltool, make sure that functions end up with the undecorate
name type if this option is set and they are decorated. In mingw, when
creating import libraries from def files instead of creating an import
library as a side effect of linking a DLL, the symbol names in the def
contain the stdcall/fastcall decoration (but no leading underscore).

By setting the undecorate name type, a linker linking to the import
library will omit the decoration from the DLL import entry.

With this in place, mingw-w64 for i386 built with llvm-dlltool/clang
produces import libraries that actually work.

Differential Revision: https://reviews.llvm.org/D36548
------------------------------------------------------------------------

llvm-svn: 311408
2017-08-21 23:26:07 +00:00
Hans Wennborg
f3b83c6a51 Merging r311182:
------------------------------------------------------------------------
r311182 | alexshap | 2017-08-18 11:20:43 -0700 (Fri, 18 Aug 2017) | 22 lines

[analyzer] Fix modeling of constructors

This diff fixes analyzer's crash (triggered assert) on the newly added test case.
The assert being discussed is assert(!B.lookup(R, BindingKey::Direct))
in lib/StaticAnalyzer/Core/RegionStore.cpp, however the root cause is different.
For classes with empty bases the offsets might be tricky.
For example, let's assume we have
 struct S: NonEmptyBase, EmptyBase {
     ...
 };
In this case Clang applies empty base class optimization and 
the offset of EmptyBase will be 0, it can be verified via
clang -cc1 -x c++ -v -fdump-record-layouts main.cpp -emit-llvm -o /dev/null.
When the analyzer tries to perform zero initialization of EmptyBase
it will hit the assert because that region
has already been "written" by the constructor of NonEmptyBase.

Test plan:
make check-all

Differential revision: https://reviews.llvm.org/D36851

------------------------------------------------------------------------

llvm-svn: 311378
2017-08-21 20:27:26 +00:00
Hans Wennborg
69da95993f Merging r311122, r311354 and r311355:
------------------------------------------------------------------------
r311122 | mgorny | 2017-08-17 13:33:21 -0700 (Thu, 17 Aug 2017) | 20 lines

[cmake] Add explicit linkage from Core to curses

The Core library calls functions provided by the curses library. Add
an appropriate explicit LINK_LIBS to ${CURSES_LIBRARIES} to propagate
the dependency correctly within the build system.

It seems that so far the linkage was handled by some kind of implicit
magic LLDB_SYSTEM_LIBS variable. However, it stopped working for
unittests as the curses libraries are passed before the LLDBCore
library, resulting in `-Wl,--as-needed` stripping the yet-unused library
before it is required by LLDBCore, and effectively breaking the build.
I think it's better to focus on listing all the dependencies explicitly
and let CMake propagate them rather than trying to figure out why this
hack stopped working.

This is also more consistent with LLVM where the curses linkage
in LLVMSupport is expressed directly in the library rather than deferred
to the final programs.

Differential Revision: https://reviews.llvm.org/D36358
------------------------------------------------------------------------

------------------------------------------------------------------------
r311354 | mgorny | 2017-08-21 10:41:33 -0700 (Mon, 21 Aug 2017) | 19 lines

[cmake] Explicitly link dependency libraries in the Host library

Add explicit linkage to the necessary system libraries in the Host
library. Otherwise, the library fails to build with -Wl,--as-needed.
The system libraries ended up being listed on the linker command-line
before the static libraries needing them, resulting in --as-needed
stripping them.

Listing the dependent libraries explicitly is the canonical way of
declaring libraries in CMake. It guarantees that the system library
dependencies will be correctly propagated to reverse dependencies.

The code used to link libraries reuses existing EXTRA_LIBS variable,
copying code from other parts of LLDB. We might eventually remove
the direct use of system libraries in the programs; however, I would
prefer if we focused on fixing the build regressions in 5.0 branch
first, and went further after the release.

Differential Revision: https://reviews.llvm.org/D36885
------------------------------------------------------------------------

------------------------------------------------------------------------
r311355 | mgorny | 2017-08-21 10:41:39 -0700 (Mon, 21 Aug 2017) | 10 lines

[unittests] Build LLVMTestingSupport for out-of-source builds

The Process/gdb-remote test now requires the LLVMTestingSupport library
that is not installed by LLVM. As a result, when doing an out-of-source
build it fails being unable to find the library. To solve that, build
a local copy of the library when building LLDB with unittests and LLVM
sources available. This is based on how we deal with bundled gtest
sources.

Differential Revision: https://reviews.llvm.org/D36886
------------------------------------------------------------------------

llvm-svn: 311377
2017-08-21 20:21:43 +00:00
Hans Wennborg
60bda997c7 Merging r310712:
------------------------------------------------------------------------
r310712 | mgorny | 2017-08-11 06:25:20 -0700 (Fri, 11 Aug 2017) | 26 lines

[cmake] Expose the dependencies of ExecutionEngine as PUBLIC

Expose the dependencies of LLVMExecutionEngine library as PUBLIC rather
than PRIVATE when building a shared library. This is necessary because
the library is not contained but exposes API of other LLVM libraries via
its headers.

This causes other libraries to fail to link if the linker verifies for
correctness of -l flags (i.e. fails on indirect dependencies). This e.g.
happens when building LLDB against shared LLVM:

  lib64/liblldbExpression.a(IRExecutionUnit.cpp.o):(.data.rel.ro._ZTIN4llvm18MCJITMemoryManagerE[_ZTIN4llvm18MCJITMemoryManagerE]+0x10): undefined reference to `typeinfo for llvm::RuntimeDyld::MemoryManager'
  lib64/liblldbExpression.a(IRExecutionUnit.cpp.o):(.data.rel.ro._ZTVN4llvm18MCJITMemoryManagerE[_ZTVN4llvm18MCJITMemoryManagerE]+0x60): undefined reference to `llvm::RuntimeDyld::MemoryManager::anchor()'
  lib64/liblldbExpression.a(IRExecutionUnit.cpp.o):(.data.rel.ro._ZTVN12lldb_private15IRExecutionUnit13MemoryManagerE[_ZTVN12lldb_private15IRExecutionUnit13MemoryManagerE]+0x48): undefined reference to `llvm::RTDyldMemoryManager::deregisterEHFrames()'
  lib64/liblldbExpression.a(IRExecutionUnit.cpp.o):(.data.rel.ro._ZTVN12lldb_private15IRExecutionUnit13MemoryManagerE[_ZTVN12lldb_private15IRExecutionUnit13MemoryManagerE]+0x60): undefined reference to `llvm::RuntimeDyld::MemoryManager::anchor()'
  lib64/liblldbExpression.a(IRExecutionUnit.cpp.o):(.data.rel.ro._ZTVN12lldb_private15IRExecutionUnit13MemoryManagerE[_ZTVN12lldb_private15IRExecutionUnit13MemoryManagerE]+0xd0): undefined reference to `llvm::JITSymbolResolver::anchor()'
  collect2: error: ld returned 1 exit status

Declaring the dependencies as PUBLIC guarantees that any package using
the ExecutionEngine library will also get explicit -l flags for
the dependent libraries guaranteeing that the symbols exposed in headers
could be resolved.

Patch originally written by NAKAMURA Takumi.

Differential Revision: https://reviews.llvm.org/D36211
------------------------------------------------------------------------

llvm-svn: 311376
2017-08-21 20:20:05 +00:00
Hans Wennborg
1de5a2f8d2 Merging r311229:
------------------------------------------------------------------------
r311229 | chandlerc | 2017-08-18 23:56:11 -0700 (Fri, 18 Aug 2017) | 19 lines

[Inliner] Fix a nasty bug when inlining a non-recursive trace of
a function into itself.

We tried to fix this before in r306495 but that got reverted as the
assert was actually hit.

This fixes the original bug (which we seem to have lost track of with
the revert) by blocking a second remapping when the function being
inlined is also the caller and the remapping could succeed but
erroneously.

The included test case would actually load from an inlined copy of the
alloca before this change, failing to load the stored value and
miscompiling.

Many thanks to Richard Smith for diagnosing a user miscompile to this
bug, and to Kyle for the first attempt and initial analysis and David Li
for remembering the issue and how to fix it and suggesting the patch.
I'm just stitching it together and landing it. =]
------------------------------------------------------------------------

llvm-svn: 311372
2017-08-21 20:07:38 +00:00
Hans Wennborg
766029eb1d Merging r311258:
------------------------------------------------------------------------
r311258 | mstorsjo | 2017-08-19 12:47:48 -0700 (Sat, 19 Aug 2017) | 9 lines

[ARM] Check the right order for halves of VZIP/VUZP if both parts are used

This is the exact same fix as in SVN r247254. In that commit, the fix was
applied only for isVTRNMask and isVTRN_v_undef_Mask, but the same issue
is present for VZIP/VUZP as well.

This fixes PR33921.

Differential Revision: https://reviews.llvm.org/D36899
------------------------------------------------------------------------

llvm-svn: 311369
2017-08-21 19:54:09 +00:00
Martin Storsjo
8d14b9ee18 Update Clang 5.0 release notes for ms_abi and __builtin_ms_va_list for aarch64
Differential Revision: https://reviews.llvm.org/D36931

llvm-svn: 311359
2017-08-21 18:45:39 +00:00
Alex Lorenz
3e60465393 Mention some warning-related additions and changes for LLVM 5
release notes

llvm-svn: 311357
2017-08-21 17:47:51 +00:00
Jonathan Coe
6353e2bfe3 Update LLVM 5.0 release notes for clang.cindex changes
Summary: This patch should be applied to clang 5.0 release notes, NOT to trunk.

Reviewers: rengolin, hans

Reviewed By: hans

Differential Revision: https://reviews.llvm.org/D36902

llvm-svn: 311219
2017-08-19 01:24:47 +00:00
Dominic Chen
714b50eb2d Add release notes for r299463.
Implement z3-based constraint solver backend for clang static analyzer.

llvm-svn: 311213
2017-08-19 00:09:24 +00:00
Hans Wennborg
7d00002115 Merging r309474:
------------------------------------------------------------------------
r309474 | smeenai | 2017-07-28 19:54:41 -0700 (Fri, 28 Jul 2017) | 9 lines

[libc++] Hoist extern template above first use

This function template is referenced inside class basic_string as a
friend function. The extern template declaration needs to be above that
friend declaration to actually take effect.

This is important because this function was marked as exported in
r307966, so without the extern template taking effect, it can leak into
other DSOs as a visible symbol.
------------------------------------------------------------------------

llvm-svn: 311197
2017-08-18 20:59:31 +00:00
Hans Wennborg
699d5871ef Merging r310262:
------------------------------------------------------------------------
r310262 | sdardis | 2017-08-07 08:37:57 -0700 (Mon, 07 Aug 2017) | 9 lines

[DebugInfo][DWARF] Correct some usages of PRIx32 to PRIx64

These lead to tests failing spuriously as the values after being rendered to a
string were incorrect.

Reviewers: clayborg

Differential Revision: https://reviews.llvm.org/D36319

------------------------------------------------------------------------

llvm-svn: 311196
2017-08-18 20:38:28 +00:00
Hans Wennborg
b6ec80b0b0 Merging r311087:
------------------------------------------------------------------------
r311087 | sdardis | 2017-08-17 07:14:25 -0700 (Thu, 17 Aug 2017) | 15 lines

[dfsan] Add explicit zero extensions for shadow parameters in function wrappers.

In the case where dfsan provides a custom wrapper for a function,
shadow parameters are added for each parameter of the function.
These parameters are i16s. For targets which do not consider this
a legal type, the lack of sign extension information would cause
LLVM to generate anyexts around their usage with phi variables
and calling convention logic.

Address this by introducing zero exts for each shadow parameter.

Reviewers: pcc, slthakur

Differential Revision: https://reviews.llvm.org/D33349

------------------------------------------------------------------------

llvm-svn: 311195
2017-08-18 20:35:42 +00:00
Hans Wennborg
cba3ce1350 Merging r311115:
------------------------------------------------------------------------
r311115 | rsmith | 2017-08-17 12:35:50 -0700 (Thu, 17 Aug 2017) | 2 lines

PR34161: support evaluation of 'void()' expressions in C++14 onwards.

------------------------------------------------------------------------

llvm-svn: 311194
2017-08-18 20:28:06 +00:00
Hans Wennborg
583cbee0c9 Merging r310066:
------------------------------------------------------------------------
r310066 | mcrosier | 2017-08-04 09:44:06 -0700 (Fri, 04 Aug 2017) | 4 lines

[AArch64] Fix an assertion for pre-index generation with unscaled loads/stores.

Differential Revision: https://reviews.llvm.org/D36248
PR34035
------------------------------------------------------------------------

llvm-svn: 311192
2017-08-18 20:25:45 +00:00
Hans Wennborg
be0f45d4f4 Merging r310498:
------------------------------------------------------------------------
r310498 | guyblank | 2017-08-09 10:21:01 -0700 (Wed, 09 Aug 2017) | 9 lines

[X86][AVX512] Choose correct registers in vpbroadcastb/w

Fixes the vpbroadcastb/w instructions which use GPRs as source operands, to use the correct registers.
The full GPR should be used, and not the subregister, as it happens before the patch.

Fixes pr33795

Differential Revision:
https://reviews.llvm.org/D36479
------------------------------------------------------------------------

llvm-svn: 311110
2017-08-17 17:42:21 +00:00
Hans Wennborg
c8242a10c8 Merging r309936:
------------------------------------------------------------------------
r309936 | chapuni | 2017-08-03 06:30:43 -0700 (Thu, 03 Aug 2017) | 1 line

ClangdTests: Try to unbreak the case CLANG_DEFAULT_CXX_STDLIB=libc++.
------------------------------------------------------------------------

llvm-svn: 311109
2017-08-17 17:39:17 +00:00
Hans Wennborg
6341352e3a Merging r310979:
------------------------------------------------------------------------
r310979 | qcolombet | 2017-08-15 17:17:05 -0700 (Tue, 15 Aug 2017) | 38 lines

[VirtRegRewriter] Properly model the register liveness on undef subreg definition

Undef subreg definition means that the content of the super register
doesn't matter at this point. While that's true for virtual registers,
this may not hold when replacing them with actual physical registers.
Indeed, some part of the physical register may be coalesced with the
related virtual register and thus, the values for those parts matter and
must be live.

The fix consists in checking whether or not subregs of the physical register
being assigned to an undef subreg definition are live through that def and
insert an implicit use if they are. Doing so, will keep them alive until
that point like they should be.

E.g., let vreg14 being assigned to R0_R1 then
%vreg14:gsub_0<def,read-undef> = COPY %R0 ; <-- R1 is still live here
%vreg14:gsub_1<def> = COPY %R1

Before this changes, the rewriter would change the code into:
%R0<def> = KILL %R0, %R0_R1<imp-def> ; <-- this tells R1 is redefined
%R1<def> = KILL %R1, %R0_R1<imp-def>, %R0_R1<imp-use> ; this value of this R1
                                                      ; is believed to come
                                                      ; from the previous
                                                      ; instruction

Because of this invalid liveness, later pass could make wrong choices and in
particular clobber live register as it happened with the register scavenger in
llvm.org/PR34107

Now we would generate:
%R0<def> = KILL %R0, %R0_R1<imp-def>, %R0_R1<imp-use> ; This tells R1 needs to
                                                      ; reach this point
%R1<def> = KILL %R1, %R0_R1<imp-def>, %R0_R1<imp-use>

The bug has been here forever, it got exposed recently because the register
scavenger got smarter.

Fixes llvm.org/PR34107
------------------------------------------------------------------------

llvm-svn: 311108
2017-08-17 17:36:27 +00:00
Hans Wennborg
a7f0cb5540 Merging r310906:
------------------------------------------------------------------------
r310906 | marsupial | 2017-08-14 19:25:36 -0700 (Mon, 14 Aug 2017) | 12 lines

Propagate error in LazyEmittingLayer::removeModule.

Summary:
Besides being the better thing to do, not doing so will triggers an assert with LLVM_ENABLE_ABI_BREAKING_CHECKS.

Reviewers: lhames

Reviewed By: lhames

Subscribers: llvm-commits

Differential Revision: https://reviews.llvm.org/D36700
------------------------------------------------------------------------

llvm-svn: 311107
2017-08-17 17:33:33 +00:00
Hans Wennborg
c37d2fbff8 Merging r310776:
------------------------------------------------------------------------
r310776 | rsmith | 2017-08-11 18:46:03 -0700 (Fri, 11 Aug 2017) | 8 lines

PR34163: Don't cache an incorrect key function for a class if queried between
the class becoming complete and its inline methods being parsed.

This replaces the hack of using the "late parsed template" flag to track member
functions with bodies we've not parsed yet; instead we now use the "will have
body" flag, which carries the desired implication that the function declaration
*is* a definition, and that we've just not parsed its body yet.

------------------------------------------------------------------------

llvm-svn: 311105
2017-08-17 17:26:33 +00:00
Hans Wennborg
721a2770e6 Merging r311068:
------------------------------------------------------------------------
r311068 | mstorsjo | 2017-08-16 22:58:27 -0700 (Wed, 16 Aug 2017) | 3 lines

[llvm-dlltool] Don't crash if no def file is provided or it can't be opened

Differential Revision: https://reviews.llvm.org/D36780
------------------------------------------------------------------------

llvm-svn: 311104
2017-08-17 17:15:08 +00:00
Hans Wennborg
10008f85e2 Merging r310992:
------------------------------------------------------------------------
r310992 | mstorsjo | 2017-08-15 22:23:00 -0700 (Tue, 15 Aug 2017) | 11 lines

[COFF] Don't produce weak aliases in import libraries

When creating an import library from lld, the cases with
Name != ExtName shouldn't end up as a weak alias, but as a real
export of the new name, which is what actually is exported from
the DLL.

This restores the behaviour of renamed exports to what it was in
4.0.

Differential Revision: https://reviews.llvm.org/D36634
------------------------------------------------------------------------

llvm-svn: 311101
2017-08-17 17:05:25 +00:00
Hans Wennborg
2f1546706b Merging r310991:
------------------------------------------------------------------------
r310991 | mstorsjo | 2017-08-15 22:22:49 -0700 (Tue, 15 Aug 2017) | 13 lines

[COFF] Make the weak aliases optional

When creating an import library from lld, the cases with
Name != ExtName shouldn't end up as a weak alias, but as a real
export of the new name, which is what actually is exported from
the DLL.

This restores the behaviour of renamed exports to what it was in
4.0.

The other half of this commit, including test, goes into lld.

Differential Revision: https://reviews.llvm.org/D36633
------------------------------------------------------------------------

llvm-svn: 311100
2017-08-17 17:04:53 +00:00
Hans Wennborg
61139ce45b Merging rr310989:
------------------------------------------------------------------------
r310989 | mstorsjo | 2017-08-15 22:13:25 -0700 (Tue, 15 Aug 2017) | 18 lines

[COFF] Fix the name type for stdcall functions in import libraries

Since SVN r303491 and r304573, LLD used the COFFImportLibrary
functions from LLVM. These only had two names, Name and ExtName,
which wasn't enough to convey all the details of stdcall functions.

Stdcall functions got the wrong symbol name in the import library
itself in r303491, which is why it was reverted in r304561. When
re-landed and fixed in r304573 (after adding a test in r304572),
the symbol name itself in the import library ended up right, but the
name type of the import library entry was wrong.

This had the effect that linking to the import library succeeded
(contrary to in r303491, where linking to such an import library
failed), but at runtime, the symbol wouldn't be found in the DLL
(since the caller linked to the stdcall decorated name).

Differential Revision: https://reviews.llvm.org/D36545
------------------------------------------------------------------------

llvm-svn: 311098
2017-08-17 16:58:21 +00:00
Hans Wennborg
e8c3291865 Merging r310988:
------------------------------------------------------------------------
r310988 | mstorsjo | 2017-08-15 22:13:16 -0700 (Tue, 15 Aug 2017) | 8 lines

[COFF] Add SymbolName as a distinct field in COFFImportFile

The previous Name and ExtName aren't enough to convey all the nuances
between weak aliases and stdcall decorated function names.

A test for this will be added in LLD.

Differential Revision: https://reviews.llvm.org/D36544
------------------------------------------------------------------------

llvm-svn: 311096
2017-08-17 16:57:03 +00:00
Hans Wennborg
62beb3789c Merging r310672:
------------------------------------------------------------------------
r310672 | ahatanak | 2017-08-10 17:06:49 -0700 (Thu, 10 Aug 2017) | 7 lines

[Sema][ObjC] Fix spurious -Wcast-qual warnings.

We do not meaningfully track object const-ness of Objective-C object
types. Silence the -Wcast-qual warning that is issued when casting to or
from Objective-C object types results in losing const qualification.

rdar://problem/33807915
------------------------------------------------------------------------

llvm-svn: 311095
2017-08-17 16:48:03 +00:00
Hans Wennborg
045029925e Merging r310939:
------------------------------------------------------------------------
r310939 | tstellar | 2017-08-15 11:11:56 -0700 (Tue, 15 Aug 2017) | 16 lines

test-release.sh: Move test-suite setup to beginning of the script

Summary:
We want to catch failures early before do the full 3 stage build.

The goal here is to avoid running through the whole build process and have
it fail at the end (and not create the binary packages), just because
some prerequisites failed to install.

Reviewers: rovka, hans

Reviewed By: hans

Subscribers: llvm-commits

Differential Revision: https://reviews.llvm.org/D36422
------------------------------------------------------------------------

llvm-svn: 311094
2017-08-17 16:45:36 +00:00
Hans Wennborg
4d4b771ab2 Merging r310926:
------------------------------------------------------------------------
r310926 | steven_wu | 2017-08-15 09:16:33 -0700 (Tue, 15 Aug 2017) | 13 lines

[Doc] Update LangRef for new Module Flag Behavior

Summary:
Add the documentation for the new module flag behavior. The new
ModFlagBehavior is added in r303590.

Reviewers: tejohnson

Reviewed By: tejohnson

Subscribers: llvm-commits

Differential Revision: https://reviews.llvm.org/D36557
------------------------------------------------------------------------

llvm-svn: 311092
2017-08-17 16:43:59 +00:00
Kai Nacke
c4900a6710 Add external project LDC to release notes.
LDC, the LLVM-based D compiler, is already ready for LLVM 5.0.

llvm-svn: 311064
2017-08-17 05:02:41 +00:00
Hans Wennborg
b3c3e54dca Merging r310706 and r310829:
------------------------------------------------------------------------
r310706 | arphaman | 2017-08-11 05:06:52 -0700 (Fri, 11 Aug 2017) | 11 lines

[modules] Set the lexical DC for dummy tag decls that refer to hidden
declarations that are made visible after the dummy is parsed and ODR verified

Prior to this commit the
"(getContainingDC(DC) == CurContext && "The next DeclContext should be lexically contained in the current one."),"
assertion failure was triggered during semantic analysis of the dummy
tag declaration that was declared in another tag declaration because its
lexical context did not point to the outer tag decl.

rdar://32292196

------------------------------------------------------------------------

------------------------------------------------------------------------
r310829 | arphaman | 2017-08-14 03:59:44 -0700 (Mon, 14 Aug 2017) | 5 lines

Set the lexical context for dummy tag decl inside createTagFromNewDecl

This is a follow-up to r310706. This change has been recommended by
Bruno Cardoso Lopes and Richard Smith.

------------------------------------------------------------------------

llvm-svn: 310902
2017-08-15 00:24:02 +00:00
Hans Wennborg
1c2df94e58 Merging r310796:
------------------------------------------------------------------------
r310796 | asb | 2017-08-13 11:49:33 -0700 (Sun, 13 Aug 2017) | 16 lines

Remove RISCV from LLVM_ALL_TARGETS in CMakeLists.txt

It was mistakenly added to that list in D23560 (committed in rL285712). RISCV 
is an experimental backend and should never have been in that list, I 
mistakenly interpreted LLVM_ALL_TARGETS as a list of all targets rather than 
targets to build by default. Unfortunately, because of this the RISCV backend 
has been building by default when it shouldn't be.

This commet adds a description comment, which should help to avoid such 
mistakes in the future.

See my message to llvm-dev for more information and analysis 
<http://lists.llvm.org/pipermail/llvm-dev/2017-August/116347.html>.

Differential Revision: https://reviews.llvm.org/D36538

------------------------------------------------------------------------

llvm-svn: 310900
2017-08-15 00:16:21 +00:00
Hans Wennborg
27b7770aed Merging r310784:
------------------------------------------------------------------------
r310784 | ctopper | 2017-08-12 13:19:44 -0700 (Sat, 12 Aug 2017) | 16 lines

[X86] When handling addcarry intrinsic, create the flag result with the correct type so we don't crash if we use a memory instruction

Summary:
Previously we were creating the flag result with MVT::Other which is interpretted as a Chain node. If we used a memory form of the instruction we would end up with a copyToReg that consumed the chain result of the adcx instruction instead of the flag result.

Pretty sure we should be using MVT::i32 here, that's what we do other places we create these node types.

We should probably consider this for 5.0 as well.

Reviewers: RKSimon, zvi, spatel

Reviewed By: RKSimon

Subscribers: llvm-commits

Differential Revision: https://reviews.llvm.org/D36645
------------------------------------------------------------------------

llvm-svn: 310899
2017-08-15 00:09:10 +00:00
Hans Wennborg
39b87c0ecb Merging r309945, r310779 and r310842:
------------------------------------------------------------------------
r309945 | spatel | 2017-08-03 08:07:37 -0700 (Thu, 03 Aug 2017) | 2 lines

[BDCE] add tests to show invalid/incomplete transforms

------------------------------------------------------------------------

------------------------------------------------------------------------
r310779 | spatel | 2017-08-12 09:41:08 -0700 (Sat, 12 Aug 2017) | 13 lines

[BDCE] clear poison generators after turning a value into zero (PR33695, PR34037)

nsw, nuw, and exact carry implicit assumptions about their operands, so we need
to clear those after trivializing a value. We decided there was no danger for
llvm.assume or metadata, so there's just a comment about that.

This fixes miscompiles as shown in:
https://bugs.llvm.org/show_bug.cgi?id=33695
https://bugs.llvm.org/show_bug.cgi?id=34037

Differential Revision: https://reviews.llvm.org/D36592


------------------------------------------------------------------------

------------------------------------------------------------------------
r310842 | spatel | 2017-08-14 08:13:46 -0700 (Mon, 14 Aug 2017) | 16 lines

[BDCE] reduce scope of an assert (PR34179)

The assert was added with r310779 and is usually correct,
but as the test shows, not always. The 'volatile' on the
load is needed to expose the faulty path because without
it, DemandedBits would return that the load is just dead
rather than not demanded, and so we wouldn't hit the
bogus assert.

Also, since the lambda is just a single-line now, get rid 
of it and inline the DB.isAllOnesValue() calls. 

This should fix (prevent execution of a faulty assert):
https://bugs.llvm.org/show_bug.cgi?id=34179


------------------------------------------------------------------------

llvm-svn: 310898
2017-08-15 00:06:23 +00:00
Hans Wennborg
151e73bc8b Merging r310804:
------------------------------------------------------------------------
r310804 | rsmith | 2017-08-13 15:26:53 -0700 (Sun, 13 Aug 2017) | 2 lines

Replace remaining user-visible mentions of C++1z with C++17.

------------------------------------------------------------------------

llvm-svn: 310862
2017-08-14 17:27:59 +00:00
Hans Wennborg
a9894d3090 Merging r310516:
------------------------------------------------------------------------
r310516 | hans | 2017-08-09 13:12:53 -0700 (Wed, 09 Aug 2017) | 13 lines

Make -std=c++17 an alias of -std=c++1z

As suggested on PR33912.

Trying to keep this small to make it easy to merge to the 5.0 branch. We
can do a follow-up with more thorough renaming (diagnostic text,
options, ids, etc.) later.

(For C++14 this was done in r215982, and I think a smaller patch for the
3.5 branch:
http://lists.llvm.org/pipermail/cfe-commits/Week-of-Mon-20140818/113013.html)

Differential Revision: https://reviews.llvm.org/D36532
------------------------------------------------------------------------

llvm-svn: 310848
2017-08-14 15:48:04 +00:00
Hans Wennborg
0d2706736f Merging r309044, r309071, r309120, r309122, r309140 and r309227 (PR34157)
------------------------------------------------------------------------
r309044 | mgorny | 2017-07-25 15:38:31 -0700 (Tue, 25 Jul 2017) | 14 lines

[lit] Fix UnboundLocalError for invalid shtest redirects

Replace the incorrect variable reference when invalid redirect is used.
This fixes the following issue:

  File "/usr/src/llvm/utils/lit/lit/TestRunner.py", line 316, in processRedirects
    raise InternalShellError(cmd, "Unsupported redirect: %r" % (r,))
UnboundLocalError: local variable 'r' referenced before assignment

which in turn broke shtest-shell.py and max-failures.py lit tests.

The breakage was introduced during refactoring in rL307310.

Differential Revision: https://reviews.llvm.org/D35857
------------------------------------------------------------------------

------------------------------------------------------------------------
r309071 | rnk | 2017-07-25 18:27:18 -0700 (Tue, 25 Jul 2017) | 1 line

[lit] Attempt to fix Python unittest adaptor logic
------------------------------------------------------------------------

------------------------------------------------------------------------
r309120 | modocache | 2017-07-26 07:59:36 -0700 (Wed, 26 Jul 2017) | 36 lines

Revert "[lit] Remove dead code not referenced in the LLVM SVN repo."

Summary:
This reverts rL306623, which removed `FileBasedTest`, an abstract base class,
but did not also remove the usages of that class in the lit unit tests.
The revert fixes four test failures in the lit unit test suite.

Test plan:
As per the instructions in `utils/lit/README.txt`, run the lit unit
test suite:

```
utils/lit/lit.py \
    --path /path/to/your/llvm/build/bin \
    utils/lit/tests
```

Verify that the following tests fail before applying this patch, and
pass once the patch is applied:

```
lit :: test-data.py
lit :: test-output.py
lit :: xunit-output.py
```

In addition, run `check-llvm` to make sure the existing LLVM test suite
executes normally.

Reviewers: george.karpenkov, mgorny, dlj

Reviewed By: mgorny

Subscribers: llvm-commits

Differential Revision: https://reviews.llvm.org/D35877
------------------------------------------------------------------------

------------------------------------------------------------------------
r309122 | modocache | 2017-07-26 08:02:05 -0700 (Wed, 26 Jul 2017) | 32 lines

[lit] Fix type error for parallelism groups

Summary:
Whereas rL299560 and rL309071 call `parallelism_groups.items()`, under the
assumption that `parallelism_groups` is a `dict` type, the default
parameter for that attribute is a `list`. Change the default to a
`dict` for type correctness.

This regression in the unit tests would have been caught if the
unit tests were being run continously. It also would have been caught
if the lit project used a Python type checker such as `mypy`.

Test Plan:
As per the instructions in `utils/lit/README.txt`, run the lit unit
test suite:

```
utils/lit/lit.py \
    --path /path/to/your/llvm/build/bin \
    utils/lit/tests
```

Verify that the test `lit :: unit/TestRunner.py` fails before applying this
patch, but passes once this patch is applied.

Reviewers: mgorny, rnk, rafael

Reviewed By: mgorny

Subscribers: llvm-commits

Differential Revision: https://reviews.llvm.org/D35878
------------------------------------------------------------------------

------------------------------------------------------------------------
r309140 | george.karpenkov | 2017-07-26 10:19:36 -0700 (Wed, 26 Jul 2017) | 3 lines

Fix LIT test breakage

Differential Revision: https://reviews.llvm.org/D35867
------------------------------------------------------------------------

------------------------------------------------------------------------
r309227 | rnk | 2017-07-26 15:57:32 -0700 (Wed, 26 Jul 2017) | 4 lines

[lit] Fix race between shtest-shell and max-failures tests

Previously these tests would use the same Output directory leading to
flaky non-deterministic failures.
------------------------------------------------------------------------

llvm-svn: 310730
2017-08-11 16:39:26 +00:00
Hans Wennborg
7f4385ac4b Merging r310704:
------------------------------------------------------------------------
r310704 | smaksimovic | 2017-08-11 04:39:07 -0700 (Fri, 11 Aug 2017) | 8 lines

Revert r302670 for the upcoming 5.0.0 release

This is causing failures when compiling clang with -O3
as one of the structures used by clang is passed by
value and uses the fastcc calling convention.

Faliures manifest for stage2 mips build.

------------------------------------------------------------------------

llvm-svn: 310728
2017-08-11 16:32:49 +00:00
Hans Wennborg
be53ea0774 Revert r310074 (see PR34067 #4)
llvm-svn: 310726
2017-08-11 16:30:46 +00:00
Hans Wennborg
54ef344e83 Merging r310700:
------------------------------------------------------------------------
r310700 | yamaguchi | 2017-08-11 02:44:42 -0700 (Fri, 11 Aug 2017) | 11 lines

[Bash-autocompletion] Add --autocomplete flag to 5.0 release notes

Summary:
I thought we should add this information to release notes, because we
added a new flag to clang driver.

Reviewers: v.g.vassilev, teemperor, ruiu

Subscribers: cfe-commits

Differential Revision: https://reviews.llvm.org/D36567
------------------------------------------------------------------------

llvm-svn: 310723
2017-08-11 16:18:44 +00:00
Hans Wennborg
29eb7a223d Merging r310694:
------------------------------------------------------------------------
r310694 | rsmith | 2017-08-10 20:39:40 -0700 (Thu, 10 Aug 2017) | 2 lines

Implement latest feature test macro recommendations, P0096R4.

------------------------------------------------------------------------

llvm-svn: 310722
2017-08-11 16:16:08 +00:00
Hans Wennborg
b04a78700a Merging r309054:
------------------------------------------------------------------------
r309054 | rsmith | 2017-07-25 16:31:42 -0700 (Tue, 25 Jul 2017) | 2 lines

Reorder tests to match latest SD-6 draft.

------------------------------------------------------------------------

llvm-svn: 310721
2017-08-11 16:14:07 +00:00
Hans Wennborg
7c22e5d252 Merging r310692:
------------------------------------------------------------------------
r310692 | rsmith | 2017-08-10 20:14:20 -0700 (Thu, 10 Aug 2017) | 2 lines

PR33850: Update cxx_dr_status for Clang 5 branch.

------------------------------------------------------------------------

llvm-svn: 310720
2017-08-11 16:07:17 +00:00
Hans Wennborg
e9b7a8c732 Merging r310691:
------------------------------------------------------------------------
r310691 | rsmith | 2017-08-10 19:04:19 -0700 (Thu, 10 Aug 2017) | 2 lines

PR33489: A function-style cast to a deduced class template specialization type is type-dependent if it can't be resolved due to a type-dependent argument.

------------------------------------------------------------------------

llvm-svn: 310719
2017-08-11 15:58:58 +00:00
Hans Wennborg
354119b492 Merging r310604:
------------------------------------------------------------------------
r310604 | niravd | 2017-08-10 08:12:32 -0700 (Thu, 10 Aug 2017) | 13 lines

[X86] Keep dependencies when constructing loads in combineStore

Summary:
Preserve chain dependecies between old and new loads constructed to
prevent loads from reordering below later stores.

Fixes PR34088.

Reviewers: craig.topper, spatel, RKSimon, efriedma

Subscribers: llvm-commits

Differential Revision: https://reviews.llvm.org/D36528
------------------------------------------------------------------------

llvm-svn: 310678
2017-08-11 01:53:40 +00:00
Hans Wennborg
6257aa2adc Merging r310006:
------------------------------------------------------------------------
r310006 | ahatanak | 2017-08-03 16:55:42 -0700 (Thu, 03 Aug 2017) | 22 lines

[Driver][Darwin] Pass -munwind-table when !UseSjLjExceptions.

This commit fixes a bug where clang/llvm doesn't emit an unwind table
for a function when it is marked noexcept. Without this patch, the
following code terminates with an uncaught exception on ARM64:

int foo1() noexcept {
  try {
    throw 0;
  } catch (int i) {
    return 0;
  }
  return 1;
}

int main() {
  return foo1();
}

rdar://problem/32411865

Differential Revision: https://reviews.llvm.org/D35693
------------------------------------------------------------------------

llvm-svn: 310677
2017-08-11 01:47:32 +00:00
Hans Wennborg
5b60b618e2 Merging r309633, r309636 and r309640:
------------------------------------------------------------------------
r309633 | ahatanak | 2017-07-31 15:19:34 -0700 (Mon, 31 Jul 2017) | 6 lines

[Driver] Make sure the deployment target is earlier than iOS 11 when
it is inferred from -isysroot.

This fixes a change that was inadvertently introduced in r309607.

rdar://problem/32230613
------------------------------------------------------------------------

------------------------------------------------------------------------
r309636 | ahatanak | 2017-07-31 15:46:00 -0700 (Mon, 31 Jul 2017) | 1 line

Silence warning -Wmissing-sysroot.
------------------------------------------------------------------------

------------------------------------------------------------------------
r309640 | ahatanak | 2017-07-31 16:08:52 -0700 (Mon, 31 Jul 2017) | 1 line

Use -target instead of -arch in test case.
------------------------------------------------------------------------

llvm-svn: 310676
2017-08-11 01:45:48 +00:00
Hans Wennborg
8765e1e328 Merging r309607:
------------------------------------------------------------------------
r309607 | ahatanak | 2017-07-31 12:16:40 -0700 (Mon, 31 Jul 2017) | 6 lines

[Driver] Allow users to silence the warning that is issued when the
deployment target is earlier than iOS 11 and the target is 32-bit.

This is a follow-up to r306922.

rdar://problem/32230613
------------------------------------------------------------------------

llvm-svn: 310675
2017-08-11 01:41:23 +00:00
Hans Wennborg
d17519a75c Merging r309569:
------------------------------------------------------------------------
r309569 | alexfh | 2017-07-31 08:21:26 -0700 (Mon, 31 Jul 2017) | 39 lines

Fix -Wshadow false positives with function-local classes.

Summary:
Fixes http://llvm.org/PR33947.

https://godbolt.org/g/54XRMT

void f(int a) {
  struct A {
    void g(int a) {}
    A() { int a; }
  };
}

3 : <source>:3:16: warning: declaration shadows a local variable [-Wshadow]
    void g(int a) {}
               ^
1 : <source>:1:12: note: previous declaration is here
void f(int a) {
           ^
4 : <source>:4:15: warning: declaration shadows a local variable [-Wshadow]
    A() { int a; }
              ^
1 : <source>:1:12: note: previous declaration is here
void f(int a) {
           ^
2 warnings generated.

The local variable `a` of the function `f` can't be accessed from a method of
the function-local class A, thus no shadowing occurs and no diagnostic is
needed.

Reviewers: rnk, rsmith, arphaman, Quuxplusone

Reviewed By: rnk, Quuxplusone

Subscribers: Quuxplusone, cfe-commits

Differential Revision: https://reviews.llvm.org/D35941
------------------------------------------------------------------------

llvm-svn: 310674
2017-08-11 01:00:59 +00:00
Hans Wennborg
2ab63b131f Merging r309614:
------------------------------------------------------------------------
r309614 | kbelochapka | 2017-07-31 13:11:49 -0700 (Mon, 31 Jul 2017) | 7 lines

[X86][MMX] Added custom lowering action for MMX SELECT (PR30418)
Fix for pr30418 - error in backend: Cannot select: t17: x86mmx = select_cc t2, Constant:i64<0>, t7, t8, seteq:ch
Differential Revision: https://reviews.llvm.org/D34661




------------------------------------------------------------------------

llvm-svn: 310673
2017-08-11 00:51:35 +00:00
Hans Wennborg
dddd37d9d6 Merging r310526:
------------------------------------------------------------------------
r310526 | ruiu | 2017-08-09 14:32:38 -0700 (Wed, 09 Aug 2017) | 3 lines

Add --icf=none option.

--icf=none negates --icf=all.
------------------------------------------------------------------------

llvm-svn: 310656
2017-08-10 20:04:41 +00:00
Hans Wennborg
cdfccb83fa Merging r310552:
------------------------------------------------------------------------
r310552 | eladcohen | 2017-08-10 00:44:23 -0700 (Thu, 10 Aug 2017) | 19 lines

[SelectionDAG] When scalarizing vselect, don't assert on
a legal cond operand.

When scalarizing the result of a vselect, the legalizer currently expects
to already have scalarized the operands. While this is true for the true/false
operands (which have the same type as the result), it is not case for the
condition operand. On X86 AVX512, v1i1 is legal - this leads to operations such
as '< N x type> vselect < N x i1> < N x type> < N x type>' where < N x type > is
illegal to hit an assertion during the scalarization.

The handling is similar to r205625.
This also exposes the fact that (v1i1 extract_subvector) should be legal
and selectable on AVX512 - We do this by custom lowering to vector_extract_elt.
This still leaves us in some cases with redundant dag nodes which will be
combined in a separate soon to come patch.

This fixes pr33349.

Differential revision: https://reviews.llvm.org/D36511
------------------------------------------------------------------------

llvm-svn: 310635
2017-08-10 17:36:36 +00:00
Hans Wennborg
1d6f2b307a Merging r310481, r310492 and r310510:
------------------------------------------------------------------------
r310481 | davide | 2017-08-09 08:13:50 -0700 (Wed, 09 Aug 2017) | 8 lines

[ValueTracking] Honour recursion limit.

The recently improved support for `icmp` in ValueTracking
(r307304) exposes the fact that `isImplied` condition doesn't
really bail out if we hit the recursion limit (and calls
`computeKnownBits` which increases the depth and asserts).

Differential Revision:  https://reviews.llvm.org/D36512
------------------------------------------------------------------------

------------------------------------------------------------------------
r310492 | davide | 2017-08-09 09:06:04 -0700 (Wed, 09 Aug 2017) | 1 line

[ValueTracking] Update tests to unbreak the bots.
------------------------------------------------------------------------

------------------------------------------------------------------------
r310510 | spatel | 2017-08-09 11:56:26 -0700 (Wed, 09 Aug 2017) | 6 lines

[SimplifyCFG] remove checks for crasher test from r310481

Not sure why the earlier version would fail, but trying to get the bots
(and my local machine) to pass again.


------------------------------------------------------------------------

llvm-svn: 310634
2017-08-10 17:33:55 +00:00
Hans Wennborg
2ef80ce81d Merging r308847:
------------------------------------------------------------------------
r308847 | mkazantsev | 2017-07-23 08:40:19 -0700 (Sun, 23 Jul 2017) | 24 lines

[SCEV] Limit max size of AddRecExpr during evolving

When SCEV calculates product of two SCEVAddRecs from the same loop, it
tries to combine them into one big AddRecExpr. If the sizes of the initial
SCEVs were `S1` and `S2`, the size of their product is `S1 + S2 - 1`, and every
operand of the resulting SCEV is combined from operands of initial SCEV and
has much higher complexity than they have.

As result, if we try to calculate something like:
  %x1 = {a,+,b}
  %x2 = mul i32 %x1, %x1
  %x3 = mul i32 %x2, %x1
  %x4 = mul i32 %x3, %x2
  ...
The size of such SCEVs grows as `2^N`, and the arguments
become more and more complex as we go forth. This leads
to long compilation and huge memory consumption.

This patch sets a limit after which we don't try to combine two
`SCEVAddRecExpr`s into one. By default, max allowed size of the
resulting AddRecExpr is set to 16.

Differential Revision: https://reviews.llvm.org/D35664

------------------------------------------------------------------------

llvm-svn: 310629
2017-08-10 17:15:06 +00:00
Hans Wennborg
375efaaaef Merging r310534:
------------------------------------------------------------------------
r310534 | matze | 2017-08-09 15:22:05 -0700 (Wed, 09 Aug 2017) | 20 lines

ARM: Fix CMP_SWAP expansion

Clean up after my misguided attempt in r304267 to "fix" CMP_SWAP
returning an uninitialized status value.

- I was always using tMOVi8 to zero the status register which cannot
  encode higher register numbers and llvm would silently miscompile)

- Nobody was ever looking at that status value outside the expansion.
  ARMDAGToDAGISel::SelectCMP_SWAP() the only place creating CMP_SWAP
  instructions was not mapping anything to it. (The cmpxchg status value
  from llvm IR is lowered to a manual comparison after the CMP_SWAP)

So this:
- Renames the register from "status" to "temp" it make it obvious that
  it isn't used outside the expansion.
- Remove the zeroing status/temp register.
- Keep the live-in list improvements from r304267

Fixes http://llvm.org/PR34056
------------------------------------------------------------------------

llvm-svn: 310628
2017-08-10 17:12:27 +00:00
Hans Wennborg
9364e3bffc Merging r309758:
------------------------------------------------------------------------
r309758 | sanjoy | 2017-08-01 15:37:58 -0700 (Tue, 01 Aug 2017) | 6 lines

[SCEV/IndVars] Always compute loop exiting values if the backedge count is 0

If SCEV can prove that the backedge taken count for a loop is zero, it does not
need to "understand" a recursive PHI to compute its exiting value.

This should fix PR33885.
------------------------------------------------------------------------

llvm-svn: 310538
2017-08-09 23:52:05 +00:00
Craig Topper
92f3b69a10 More x86 release notes.
llvm-svn: 310501
2017-08-09 17:53:58 +00:00
Hans Wennborg
d55dcea623 ReleaseNotes: Zig
llvm-svn: 310500
2017-08-09 17:36:00 +00:00
Hans Wennborg
1baca78934 Merging r310253 and r310267:
------------------------------------------------------------------------
r310253 | sdardis | 2017-08-07 06:30:03 -0700 (Mon, 07 Aug 2017) | 2 lines

[DebugInfo][DWARF] Use PRIx64 explicitly in output.

------------------------------------------------------------------------

------------------------------------------------------------------------
r310267 | sdardis | 2017-08-07 09:08:11 -0700 (Mon, 07 Aug 2017) | 2 lines

[DebugInfo][DWARF] Address paulr's comment on rL310253.

------------------------------------------------------------------------

llvm-svn: 310398
2017-08-08 18:43:25 +00:00
Hans Wennborg
62940d57ee Merging r310250:
------------------------------------------------------------------------
r310250 | sdardis | 2017-08-07 05:29:38 -0700 (Mon, 07 Aug 2017) | 2 lines

[llvm-objdump] Use PRIx64 for output of ARM64_RELOC_ADDEND

------------------------------------------------------------------------

llvm-svn: 310396
2017-08-08 18:40:46 +00:00
Hans Wennborg
dda69b2e87 Merging r308722:
------------------------------------------------------------------------
r308722 | ibiryukov | 2017-07-21 02:24:00 -0700 (Fri, 21 Jul 2017) | 13 lines

Fixed failing assert in code completion.

Summary:
The code was accessing uninstantiated default argument.
This resulted in failing assertion at ParmVarDecl::getDefaultArg().

Reviewers: erikjv, klimek, bkramer, krasimir

Reviewed By: krasimir

Subscribers: cfe-commits

Differential Revision: https://reviews.llvm.org/D35682
------------------------------------------------------------------------

llvm-svn: 310395
2017-08-08 18:38:07 +00:00
Hans Wennborg
91d29e7910 Merging r309263:
------------------------------------------------------------------------
r309263 | psmith | 2017-07-27 03:43:53 -0700 (Thu, 27 Jul 2017) | 6 lines

[CodeGen][ARM] ARM runtime helper functions are not always soft-fp

Re-commit r309257 with less precise register checks in arm-float-helpers.c
test.


------------------------------------------------------------------------

llvm-svn: 310393
2017-08-08 18:34:26 +00:00
Hans Wennborg
f475f73db0 Merging r310359:
------------------------------------------------------------------------
r310359 | n.bozhenov | 2017-08-08 07:13:50 -0700 (Tue, 08 Aug 2017) | 4 lines

[libclang] Fix PR34055 (incompatible update of clang-c/Index.h)

Fixes a regression introduced by r308218.

------------------------------------------------------------------------

llvm-svn: 310390
2017-08-08 18:15:02 +00:00
Hans Wennborg
d95203bab5 Merging r310240:
------------------------------------------------------------------------
r310240 | vitalybuka | 2017-08-07 00:12:33 -0700 (Mon, 07 Aug 2017) | 1 line

Add -asan-force-dynamic-shadow test
------------------------------------------------------------------------

llvm-svn: 310316
2017-08-07 22:11:20 +00:00
Hans Wennborg
f8f93f8466 Merging r310241 and r310242:
------------------------------------------------------------------------
r310241 | vitalybuka | 2017-08-07 00:12:34 -0700 (Mon, 07 Aug 2017) | 3 lines

[asan] Disable checking of arguments passed by value for --asan-force-dynamic-shadow

Fails with "Instruction does not dominate all uses!"
------------------------------------------------------------------------

------------------------------------------------------------------------
r310242 | vitalybuka | 2017-08-07 00:35:33 -0700 (Mon, 07 Aug 2017) | 1 line

[asan] Fix asan dynamic shadow check before copyArgsPassedByValToAllocas
------------------------------------------------------------------------

llvm-svn: 310309
2017-08-07 21:48:12 +00:00
Hans Wennborg
c8a6ff519d Merging r310158:
------------------------------------------------------------------------
r310158 | rtrieu | 2017-08-04 17:54:19 -0700 (Fri, 04 Aug 2017) | 8 lines

[ODRHash] Treat some non-templated classes as templated.

When using nested classes, if the inner class is not templated, but the outer
class is templated, the inner class will not be templated, but may have some
traits as if it were.  This is particularly evident if the inner class
refers to the outer class in some fashion.  Treat any class that is in the
context of a templated class as also a templated class.

------------------------------------------------------------------------

llvm-svn: 310302
2017-08-07 20:45:55 +00:00
Hans Wennborg
6f335f8bfb Merging r310191:
------------------------------------------------------------------------
r310191 | ctopper | 2017-08-05 16:35:54 -0700 (Sat, 05 Aug 2017) | 18 lines

[X86] Enable isel to use the PAUSE instruction even when SSE2 is disabled. Clang part

Summary:
On older processors this instruction encoding is treated as a NOP.

MSVC doesn't disable intrinsics based on features the way clang/gcc does. Because the PAUSE instruction encoding doesn't crash older processors, some software out there uses these intrinsics without checking for SSE2.

This change also seems to also be consistent with gcc behavior.

Fixes PR34079

Reviewers: RKSimon, zvi

Reviewed By: RKSimon

Subscribers: cfe-commits

Differential Revision: https://reviews.llvm.org/D36362
------------------------------------------------------------------------

llvm-svn: 310294
2017-08-07 20:15:58 +00:00
Hans Wennborg
03a96f4e84 Merging r310190:
------------------------------------------------------------------------
r310190 | ctopper | 2017-08-05 16:34:44 -0700 (Sat, 05 Aug 2017) | 18 lines

[X86] Enable isel to use the PAUSE instruction even when SSE2 is disabled

Summary:
On older processors this instruction encoding is treated as a NOP.

MSVC doesn't disable intrinsics based on features the way clang/gcc does. Because the PAUSE instruction encoding doesn't crash older processors, some software out there uses these intrinsics without checking for SSE2.

This change also seems to also be consistent with gcc behavior.

Fixes PR34079

Reviewers: RKSimon, zvi

Reviewed By: RKSimon

Subscribers: llvm-commits

Differential Revision: https://reviews.llvm.org/D36361
------------------------------------------------------------------------

llvm-svn: 310293
2017-08-07 20:14:13 +00:00
Hans Wennborg
6e83d91d75 Merging r310071:
------------------------------------------------------------------------
r310071 | rnk | 2017-08-04 10:09:11 -0700 (Fri, 04 Aug 2017) | 8 lines

[ArgPromotion] Preserve alignment of byval argument in new alloca

The frontend may have requested a higher alignment for any reason, and
downstream optimizations may already have taken advantage of it.  We
should keep the same alignment when moving the allocation from the
parameter area to the local variable area.

Fixes PR34038
------------------------------------------------------------------------

llvm-svn: 310292
2017-08-07 20:06:54 +00:00
Hans Wennborg
8bfea7d1fe Merging r309851:
------------------------------------------------------------------------
r309851 | marshall | 2017-08-02 11:21:34 -0700 (Wed, 02 Aug 2017) | 1 line

Fix shadowing warning
------------------------------------------------------------------------

llvm-svn: 310288
2017-08-07 19:49:31 +00:00
Hans Wennborg
c4081cdc76 Merging r309838:
------------------------------------------------------------------------
r309838 | marshall | 2017-08-02 10:31:09 -0700 (Wed, 02 Aug 2017) | 1 line

Fix PR33727: std::basic_stringbuf only works with DefaultConstructible allocators. Thanks to Jonathan Wakely for the report and suggested fix
------------------------------------------------------------------------

llvm-svn: 310287
2017-08-07 19:49:04 +00:00
Hans Wennborg
c57773fee1 Merging r309296 and r309307:
------------------------------------------------------------------------
r309296 | marshall | 2017-07-27 10:44:03 -0700 (Thu, 27 Jul 2017) | 1 line

Implement P0739R0: 'Some improvements to class template argument deduction integration into the standard library' This is an API change (not ABI change) due to a late change in the c++17 standard
------------------------------------------------------------------------

------------------------------------------------------------------------
r309307 | marshall | 2017-07-27 11:47:35 -0700 (Thu, 27 Jul 2017) | 1 line

Disable the deduction guide test I added in 309296 for the moment, while I figure out which compilers don't support deduction guides
------------------------------------------------------------------------

llvm-svn: 310286
2017-08-07 19:48:12 +00:00
Hans Wennborg
cec266a0fa Merging r310057:
------------------------------------------------------------------------
r310057 | smaksimovic | 2017-08-04 05:37:34 -0700 (Fri, 04 Aug 2017) | 8 lines

Revert r304953 for release 5.0.0

This is causing failures when compiling clang with -O3
as one of the structures used by clang is passed by
value and uses the fastcc calling convention.

Faliures manifest for stage2 mips build.

------------------------------------------------------------------------

llvm-svn: 310074
2017-08-04 17:19:44 +00:00
Hans Wennborg
63657a11b8 Merging r309920:
------------------------------------------------------------------------
r309920 | ericwf | 2017-08-02 21:28:10 -0700 (Wed, 02 Aug 2017) | 5 lines

Fix libcxx build with glibc 2.26+ by removing xlocale.h include.

Patch by Khem Raj. Reviewed as D35697. Also see PR33729.


------------------------------------------------------------------------

llvm-svn: 310068
2017-08-04 16:52:25 +00:00
Hans Wennborg
b3e50e6ab2 Merging r309975: (except the docs/ part)
------------------------------------------------------------------------
r309975 | rsmith | 2017-08-03 12:24:27 -0700 (Thu, 03 Aug 2017) | 4 lines

Don't emit undefined-internal warnings for CXXDeductionGuideDecls.

Patch by ~paul (cynecx on phabricator)! Some test massaging by me.

------------------------------------------------------------------------

llvm-svn: 310067
2017-08-04 16:48:43 +00:00
Hans Wennborg
335fe85c68 Merging r309928:
------------------------------------------------------------------------
r309928 | ewancrawford | 2017-08-03 02:23:03 -0700 (Thu, 03 Aug 2017) | 56 lines

[Cloning] Move distinct GlobalVariable debug info metadata in CloneModule

Duplicating the distinct Subprogram and CU metadata nodes seems like the incorrect thing to do in CloneModule for GlobalVariable debug info. As it results in the scope of the GlobalVariable DI no longer being consistent with the rest of the module, and the new CU is absent from llvm.dbg.cu.

Fixed by adding RF_MoveDistinctMDs to MapMetadata flags for GlobalVariables.

Current unit test IR after clone:
```
@gv = global i32 1, comdat($comdat), !dbg !0, !type !5

define private void @f() comdat($comdat) personality void ()* @persfn !dbg !14 {

!llvm.dbg.cu = !{!10}

!0 = !DIGlobalVariableExpression(var: !1)
!1 = distinct !DIGlobalVariable(name: "gv", linkageName: "gv", scope: !2, file: !3, line: 1, type: !9, isLocal: false, isDefinition: true)
!2 = distinct !DISubprogram(name: "f", linkageName: "f", scope: null, file: !3, line: 4, type: !4, isLocal: true, isDefinition: true, scopeLine: 3, isOptimized: false, unit: !6, variables: !5)
!3 = !DIFile(filename: "filename.c", directory: "/file/dir/")
!4 = !DISubroutineType(types: !5)
!5 = !{}
!6 = distinct !DICompileUnit(language: DW_LANG_C99, file: !7, producer: "CloneModule", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !5, globals: !8)
!7 = !DIFile(filename: "filename.c", directory: "/file/dir")
!8 = !{!0}
!9 = !DIBasicType(tag: DW_TAG_unspecified_type, name: "decltype(nullptr)")
!10 = distinct !DICompileUnit(language: DW_LANG_C99, file: !7, producer: "CloneModule", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !5, globals: !11)
!11 = !{!12}
!12 = !DIGlobalVariableExpression(var: !13)
!13 = distinct !DIGlobalVariable(name: "gv", linkageName: "gv", scope: !14, file: !3, line: 1, type: !9, isLocal: false, isDefinition: true)
!14 = distinct !DISubprogram(name: "f", linkageName: "f", scope: null, file: !3, line: 4, type: !4, isLocal: true, isDefinition: true, scopeLine: 3, isOptimized: false, unit: !10, variables: !5)
```

Patched IR after clone:
```
@gv = global i32 1, comdat($comdat), !dbg !0, !type !5

define private void @f() comdat($comdat) personality void ()* @persfn !dbg !2 {

!llvm.dbg.cu = !{!6}

!0 = !DIGlobalVariableExpression(var: !1)
!1 = distinct !DIGlobalVariable(name: "gv", linkageName: "gv", scope: !2, file: !3, line: 1, type: !9, isLocal: false, isDefinition: true)
!2 = distinct !DISubprogram(name: "f", linkageName: "f", scope: null, file: !3, line: 4, type: !4, isLocal: true, isDefinition: true, scopeLine: 3, isOptimized: false, unit: !6, variables: !5)
!3 = !DIFile(filename: "filename.c", directory: "/file/dir/")
!4 = !DISubroutineType(types: !5)
!5 = !{}
!6 = distinct !DICompileUnit(language: DW_LANG_C99, file: !7, producer: "CloneModule", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !5, globals: !8)
!7 = !DIFile(filename: "filename.c", directory: "/file/dir")
!8 = !{!0}
!9 = !DIBasicType(tag: DW_TAG_unspecified_type, name: "decltype(nullptr)")
```

Reviewers: aprantl, probinson, dblaikie, echristo, loladiro
Reviewed By: aprantl
Subscribers: llvm-commits
Differential Revision: https://reviews.llvm.org/D36082

------------------------------------------------------------------------

llvm-svn: 309965
2017-08-03 17:15:38 +00:00
Hans Wennborg
add6d42a95 Merging r309917:
------------------------------------------------------------------------
r309917 | ericwf | 2017-08-02 19:50:43 -0700 (Wed, 02 Aug 2017) | 4 lines

Add system header pragma to BSD locale fallback headers.

This prevent leaking warnings to the user about use of C++11
extensions in C++03.
------------------------------------------------------------------------

llvm-svn: 309958
2017-08-03 16:34:10 +00:00
Hans Wennborg
5341de3ad3 Merging r309651 and r309849:
------------------------------------------------------------------------
r309651 | inouehrs | 2017-07-31 20:32:15 -0700 (Mon, 31 Jul 2017) | 16 lines

[StackColoring] Update AliasAnalysis information in stack coloring pass

Stack coloring pass need to maintain AliasAnalysis information when merging stack slots of different types.
Actually, there is a FIXME comment in StackColoring.cpp

// FIXME: In order to enable the use of TBAA when using AA in CodeGen,
// we'll also need to update the TBAA nodes in MMOs with values
// derived from the merged allocas.

But, TBAA has been already enabled in CodeGen without fixing this pass.
The incorrect TBAA metadata results in recent failures in bootstrap test on ppc64le (PR33928) by allowing unsafe instruction scheduling.
Although we observed the problem on ppc64le, this is a platform neutral issue.

This patch makes the stack coloring pass maintains AliasAnalysis information when merging multiple stack slots.
------------------------------------------------------------------------

------------------------------------------------------------------------
r309849 | inouehrs | 2017-08-02 11:16:32 -0700 (Wed, 02 Aug 2017) | 19 lines

[StackColoring] Update AliasAnalysis information in stack coloring pass (part 2)

This patch is update after the first patch (https://reviews.llvm.org/rL309651) based on the post-commit comments.

Stack coloring pass need to maintain AliasAnalysis information when merging stack slots of different types.
Actually, there is a FIXME comment in StackColoring.cpp

// FIXME: In order to enable the use of TBAA when using AA in CodeGen,
// we'll also need to update the TBAA nodes in MMOs with values
// derived from the merged allocas.

But, TBAA has been already enabled in CodeGen without fixing this pass.
The incorrect TBAA metadata results in recent failures in bootstrap test on ppc64le (PR33928) by allowing unsafe instruction scheduling.
Although we observed the problem on ppc64le, this is a platform neutral issue.

This patch makes the stack coloring pass maintains AliasAnalysis information when merging multiple stack slots.

This patch fixes PR33928.
------------------------------------------------------------------------

llvm-svn: 309957
2017-08-03 16:31:39 +00:00
Hans Wennborg
6df79000c1 Merging r309930:
------------------------------------------------------------------------
r309930 | sdardis | 2017-08-03 02:38:46 -0700 (Thu, 03 Aug 2017) | 19 lines

[SelectionDAG] Resolve PR33978.

rL306209 taught SelectionDAG how to add the dereferenceable flag when
expanding memcpy and memmove. The fix however contained a nit where
the offset + size was constructed as an APInt of PointerSize rather
than PointerSizeInBits.

This lead to isDereferenceableAndAlignedPointer() get truncated values or
values which would be sign extended within that function leading to
incorrect results.

Thanks to Alex Crichton for reporting the issue!

This resolves PR33978.

Reviewers: inouehrs

Differential Revision: https://reviews.llvm.org/D36236

------------------------------------------------------------------------

llvm-svn: 309956
2017-08-03 16:24:57 +00:00
Hans Wennborg
db948f8755 Merging r308996:
------------------------------------------------------------------------
r308996 | gornishanov | 2017-07-25 11:01:49 -0700 (Tue, 25 Jul 2017) | 9 lines

[coroutines] Add serialization/deserialization of coroutines

Reviewers: rsmith

Reviewed By: rsmith

Subscribers: EricWF, cfe-commits

Differential Revision: https://reviews.llvm.org/D35383
------------------------------------------------------------------------

llvm-svn: 309954
2017-08-03 16:12:51 +00:00
Hans Wennborg
4a02632ddf Merging r309523:
------------------------------------------------------------------------
r309523 | brad | 2017-07-30 14:13:59 -0700 (Sun, 30 Jul 2017) | 2 lines

Also pass -pie back to the linker when linking on OpenBSD.

------------------------------------------------------------------------

llvm-svn: 309844
2017-08-02 17:42:08 +00:00
Hans Wennborg
44b69d03b9 Merging r309744:
------------------------------------------------------------------------
r309744 | mstorsjo | 2017-08-01 14:13:54 -0700 (Tue, 01 Aug 2017) | 29 lines

[AArch64] Rewrite stack frame handling for win64 vararg functions

The previous attempt, which made do with a single offset in
computeCalleeSaveRegisterPairs, wasn't quite enough. The previous
attempt only worked as long as CombineSPBump == true (since the
offset would be adjusted later in fixupCalleeSaveRestoreStackOffset).

Instead include the size for the fixed stack area used for win64
varargs in calculations in emitPrologue/emitEpilogue. The stack
consists of mainly three parts;
- AFI->getLocalStackSize()
- AFI->getCalleeSavedStackSize()
- FixedObject

Most of the places in the code which previously used the CSStackSize
now use PrologueSaveSize instead, which is the sum of the latter
two, while some cases which need exactly the middle one use
AFI->getCalleeSavedStackSize() explicitly instead of a local variable.

In addition to moving the offsetting into emitPrologue/emitEpilogue
(which fixes functions with CombineSPBump == false), also set the
frame pointer to point to the right location, where the frame pointer
and link register actually are stored. In addition to the prologue/epilogue,
this also requires changes to resolveFrameIndexReference.

Add tests for a function that keeps a frame pointer and another one
that uses a VLA.

Differential Revision: https://reviews.llvm.org/D35919
------------------------------------------------------------------------

llvm-svn: 309843
2017-08-02 17:38:46 +00:00
Hans Wennborg
de7a97cde6 Merging r309555:
------------------------------------------------------------------------
r309555 | mstorsjo | 2017-07-31 04:18:41 -0700 (Mon, 31 Jul 2017) | 10 lines

[llvm-dlltool] Write correct weak externals

Previously, the created object files for the import library were broken.
Write the symbol table before the string table. Simplify the code by
using a separate variable Prefix instead of duplicating a few lines.

Also update the coff-weak-exports to actually check that the generated
weak symbols can be found as intended.

Differential Revision: https://reviews.llvm.org/D36065
------------------------------------------------------------------------

llvm-svn: 309837
2017-08-02 17:31:02 +00:00
Hans Wennborg
cfa7f080af Merging r309594:
------------------------------------------------------------------------
r309594 | majnemer | 2017-07-31 10:47:07 -0700 (Mon, 31 Jul 2017) | 4 lines

[IPSCCP] Guard a user of getInitializer with hasDefinitiveInitializer

We are not allowed to reason about an initializer value without first
consulting hasDefinitiveInitializer.
------------------------------------------------------------------------

llvm-svn: 309827
2017-08-02 15:52:32 +00:00
Hans Wennborg
051f01d96f Merging r309722:
------------------------------------------------------------------------
r309722 | bruno | 2017-08-01 12:05:25 -0700 (Tue, 01 Aug 2017) | 7 lines

[Sema] Fix lax conversion between non ext vectors

r282968 introduced a regression due to the lack of proper testing.
Re-add lax conversion support between non ext vectors for compound
assignments and add a test for that.

rdar://problem/28639467
------------------------------------------------------------------------

llvm-svn: 309770
2017-08-01 23:54:32 +00:00
Hans Wennborg
5b6cab7692 Merging r309561:
------------------------------------------------------------------------
r309561 | sdardis | 2017-07-31 07:06:58 -0700 (Mon, 31 Jul 2017) | 14 lines

[SelectionDAG][mips] Fix PR33883

PR33883 shows that calls to intrinsic functions should not have their vector
arguments or returns subject to ABI changes required by the target.

This resolves PR33883.

Thanks to Alex Crichton for reporting the issue!

Reviewers: zoran.jovanovic, atanasyan

Differential Revision: https://reviews.llvm.org/D35765


------------------------------------------------------------------------

llvm-svn: 309767
2017-08-01 23:44:38 +00:00
Hans Wennborg
7c727a77cd Merging r309495:
------------------------------------------------------------------------
r309495 | fhahn | 2017-07-29 13:35:28 -0700 (Sat, 29 Jul 2017) | 30 lines

[AArch64] Tie source and destination operands for AESMC/AESIMC. 

Summary:
Most CPUs implementing AES fusion require instruction pairs of the form
    AESE Vn, _
    AESMC Vn, Vn
and
    AESD Vn, _
    AESIMC Vn, Vn

The constraint is added to AES(I)MC instructions which use the result of
an AES(E|D) instruction by using AES(I)MCTrr pseudo instructions, which
constraint source and destination registers to be the same.

A nice side effect of this change is that now all possible pairs are
scheduled back-to-back on the exynos-m1 for the misched-fusion-aes.ll
test case.

I had to update aes_load_store. The version I added initially was very
reduced and with the new constraint, AESE/AESMC could not be scheduled
back-to-back. I updated the test to be more realistic and still expose
the same scheduling problem as the initial test case.

Reviewers: t.p.northover, rengolin, evandro, kristof.beyls, silviu.baranga

Reviewed By: t.p.northover, evandro

Subscribers: aemerson, javed.absar, llvm-commits

Differential Revision: https://reviews.llvm.org/D35299
------------------------------------------------------------------------

llvm-svn: 309765
2017-08-01 23:38:46 +00:00
Hans Wennborg
2c061970f3 Merging r309752:
------------------------------------------------------------------------
r309752 | bruno | 2017-08-01 15:10:36 -0700 (Tue, 01 Aug 2017) | 6 lines

[Headers][Darwin] Allow #include_next<float.h> to work on Darwin prior to 10.7

This fixes PR31504 and it's a follow up from adding #include_next<float.h>
for Darwin in r289018.

rdar://problem/29856682
------------------------------------------------------------------------

llvm-svn: 309764
2017-08-01 23:32:23 +00:00
Singapuram Sanjay Srivallabh
6982cfcfbd [release 5.0][Release Notes] Polly-ACC works with Julia
Summary: Polly can now offload Julia to GPUs. This was enabled by the pull requests https://github.com/JuliaLang/julia/pull/21736 and https://github.com/JuliaLang/julia/pull/22036.

Reviewers: grosser, bollu

Subscribers: pollydev

Tags: #polly

Differential Revision: https://reviews.llvm.org/D36050

llvm-svn: 309656
2017-08-01 05:02:26 +00:00
Hans Wennborg
fa77bc40d4 Merging r309330:
------------------------------------------------------------------------
r309330 | davide | 2017-07-27 15:20:44 -0700 (Thu, 27 Jul 2017) | 13 lines

[ConstantFolder] Don't try to fold gep when the idx is a vector.

The code in ConstantFoldGetElementPtr() assumes integers, and
therefore it crashes trying to get the integer bidwith of a vector
type (in this case <4 x i32>. I just changed the code to prevent
the folding in case of vectors and I didn't bother to generalize
as this doesn't seem to me something that really happens in
practice, but I'm willing to change the patch if you think
it's worth it.
This is hard to trigger from -instsimplify or -instcombine
only as the second instruction is dead, so the test uses loop-unroll.

Differential Revision:  https://reviews.llvm.org/D35956
------------------------------------------------------------------------

llvm-svn: 309595
2017-07-31 17:47:41 +00:00
Hans Wennborg
0c9fb55ff9 Revert r304837
llvm-svn: 309593
2017-07-31 17:42:25 +00:00
Hans Wennborg
3285f10b34 Merging r309481:
------------------------------------------------------------------------
r309481 | mgorny | 2017-07-28 23:46:45 -0700 (Fri, 28 Jul 2017) | 13 lines

[OCaml] Install dynamic libraries in 'stubdirs' directory

Install the OCaml dynamic libraries in the 'stubdirs' directory rather
than the llvm subdirectory in order to fix running executables created
by ocamlc. Otherwise, the executables fail to run being unable to locate
the libraries (unless the LLVM directory is explicitly added to
LD_LIBRARY_PATH).

The staging directories are not altered since they work for our
development setup anyway, and installing into two directories would
unnecessarily make the code more complex.

Differential Revision: https://reviews.llvm.org/D35995
------------------------------------------------------------------------

llvm-svn: 309592
2017-07-31 17:40:02 +00:00
Hans Wennborg
1bdc313bbd Merging r309483:
------------------------------------------------------------------------
r309483 | mgorny | 2017-07-29 01:10:24 -0700 (Sat, 29 Jul 2017) | 7 lines

[OCaml] Pass -D/-UNDEBUG through to ocamlc

Detect [/-][DU]NDEBUG in CMAKE_C_FLAGS* and pass them through to ocamlc.
This is necessary because their value might affect visibility of dump
functions in LLVM and ocamlc uses its own compiler and flags by default.

Differential Revision: https://reviews.llvm.org/D35898
------------------------------------------------------------------------

llvm-svn: 309591
2017-07-31 17:39:07 +00:00
Hans Wennborg
47928b12a8 Merging r309321:
------------------------------------------------------------------------
r309321 | mgorny | 2017-07-27 14:13:25 -0700 (Thu, 27 Jul 2017) | 12 lines

[OCaml] Fix undefined reference to LLVMDumpType() with NDEBUG

Account for the possibility of LLVMDumpType() not being available with
NDEBUG in the OCaml bindings. If it is not built into LLVM, make
the dump function raise an exception.

Since rL293359, the dump functions are built only if either NDEBUG is
not defined, or LLVM_ENABLE_DUMP is defined. As a result, if the dump
functions are not built in LLVM, the dynamic OCaml libraries fail to
load due to undefined LLVMDumpType symbol.

Differential Revision: https://reviews.llvm.org/D35899
------------------------------------------------------------------------

llvm-svn: 309590
2017-07-31 17:37:45 +00:00
Hans Wennborg
bc3365120a Merging r309382:
------------------------------------------------------------------------
r309382 | rksimon | 2017-07-28 06:47:02 -0700 (Fri, 28 Jul 2017) | 3 lines

[X86] Add tests showing inability of vector non-temporal load/store intrinsic to force pointer alignment (PR33830)

Clang specifies a max type alignment of 16 bytes on darwin targets, meaning that the builtin nontemporal stores don't correctly align the loads/stores to 32 or 64 bytes when required, resulting in lowering to temporal unaligned loads/stores.
------------------------------------------------------------------------
Merging r309383:
------------------------------------------------------------------------
r309383 | rksimon | 2017-07-28 07:01:51 -0700 (Fri, 28 Jul 2017) | 1 line

Strip trailing whitespace. NFCI.
------------------------------------------------------------------------
Merging r309488:
------------------------------------------------------------------------
r309488 | rksimon | 2017-07-29 08:33:34 -0700 (Sat, 29 Jul 2017) | 7 lines

[X86][AVX] Ensure vector non-temporal load/store intrinsics force pointer alignment (PR33830)

Clang specifies a max type alignment of 16 bytes on darwin targets (annoyingly in the driver not via cc1), meaning that the builtin nontemporal stores don't correctly align the loads/stores to 32 or 64 bytes when required, resulting in lowering to temporal unaligned loads/stores.

This patch casts the vectors to explicitly aligned types prior to the load/store to ensure that the require alignment is respected.

Differential Revision: https://reviews.llvm.org/D35996
------------------------------------------------------------------------

llvm-svn: 309588
2017-07-31 17:29:29 +00:00
Hans Wennborg
5e1268485b Merging r309325:
------------------------------------------------------------------------
r309325 | ab | 2017-07-27 14:28:59 -0700 (Thu, 27 Jul 2017) | 8 lines

[X86] Don't lie about legality to TLI's demanded bits.

Like r309323, X86 had a typo where it passed the wrong flags to TLO.

Found by inspection; I haven't been able to tickle this into having
observable behavior.  I don't think it does, given that X86 doesn't have
custom demanded bits logic, and the generic logic doesn't have a lot of
exposure to illegal constructs.
------------------------------------------------------------------------

llvm-svn: 309587
2017-07-31 17:19:51 +00:00
Hans Wennborg
df0edb8d89 Merging r309323:
------------------------------------------------------------------------
r309323 | ab | 2017-07-27 14:27:25 -0700 (Thu, 27 Jul 2017) | 12 lines

[AArch64] Fix legality info passed to demanded bits for TBI opt.

The (seldom-used) TBI-aware optimization had a typo lying dormant since
it was first introduced, in r252573:  when asking for demanded bits, it
told TLI that it was running after legalize, where the opposite was
true.

This is an important piece of information, that the demanded bits
analysis uses to make assumptions about the node.  r301019 added such an
assumption, which was broken by the TBI combine.

Instead, pass the correct flags to TLO.
------------------------------------------------------------------------

llvm-svn: 309586
2017-07-31 17:17:43 +00:00
Hans Wennborg
35e148b4a6 Merging r309503:
------------------------------------------------------------------------
r309503 | rsmith | 2017-07-29 23:31:29 -0700 (Sat, 29 Jul 2017) | 6 lines

PR33902: Invalidate line number cache when adding more text to existing buffer.

This led to crashes as the line number cache would report a bogus line number
for a line of code, and we'd try to find a nonexistent column within the line
when printing diagnostics.

------------------------------------------------------------------------

llvm-svn: 309580
2017-07-31 17:00:55 +00:00
Hans Wennborg
31853240f3 Merging r309343:
------------------------------------------------------------------------
r309343 | rnk | 2017-07-27 17:58:35 -0700 (Thu, 27 Jul 2017) | 16 lines

[X86] Fix latent bug in sibcall eligibility logic

The X86 tail call eligibility logic was correct when it was written, but
the addition of inalloca and argument copy elision broke its
assumptions. It was assuming that fixed stack objects were immutable.

Currently, we aim to emit a tail call if no arguments have to be
re-arranged in memory. This code would trace the outgoing argument
values back to check if they are loads from an incoming stack object.
If the stack argument is immutable, then we won't need to store it back
to the stack when we tail call.

Fortunately, stack objects track their mutability, so we can just make
the obvious check to fix the bug.

This was http://crbug.com/749826
------------------------------------------------------------------------

llvm-svn: 309577
2017-07-31 16:45:02 +00:00
Hans Wennborg
0452399485 Merging r309422:
------------------------------------------------------------------------
r309422 | rnk | 2017-07-28 12:48:40 -0700 (Fri, 28 Jul 2017) | 25 lines

Fix conditional tail call branch folding when both edges are the same

The conditional tail call logic did the wrong thing when both
destinations of a conditional branch were the same:

BB#1: derived from LLVM BB %entry
    Live Ins: %EFLAGS
    Predecessors according to CFG: BB#0
        JE_1 <BB#5>, %EFLAGS<imp-use,kill>
        JMP_1 <BB#5>

BB#5: derived from LLVM BB %sw.epilog
    Predecessors according to CFG: BB#1
        TCRETURNdi64 <ga:@mergeable_conditional_tailcall>, 0, ...

We would fold the JE_1 to a TCRETURNdi64cc, and then remove our BB#5
successor. Then BB#5 would be deleted as it had no predecessors, leaving
a dangling "JMP_1 <BB#5>" reference behind to cause assertions later.

This patch checks that both conditional branch destinations are
different before doing the transform. The standard branch folding logic
is able to remove both the JMP_1 and the JE_1, and for my test case we
end up forming a better conditional tail call later.

Fixes PR33980
------------------------------------------------------------------------

llvm-svn: 309574
2017-07-31 16:41:22 +00:00
Dylan McKay
397fe0b393 [AVR] Add release notes for 5.0
llvm-svn: 309513
2017-07-30 15:14:22 +00:00
Hans Wennborg
5408e6d648 Merging r309353 and r309355:
------------------------------------------------------------------------
r309353 | davide | 2017-07-27 19:57:43 -0700 (Thu, 27 Jul 2017) | 3 lines

[JumpThreading] Add an option to dump LazyValueInfo after the run.

Differential Revision:  https://reviews.llvm.org/D35973
------------------------------------------------------------------------

------------------------------------------------------------------------
r309355 | davide | 2017-07-27 20:10:43 -0700 (Thu, 27 Jul 2017) | 24 lines

[JumpThreading] Stop falsely preserving LazyValueInfo.

JumpThreading claims to preserve LVI, but it doesn't preserve
the analyses which LVI holds a reference to (e.g. the Dominator).
In the current pass manager infrastructure, after JT runs, the
PM frees these analyses (including DominatorTree) but preserves
LVI.

CorrelatedValuePropagation runs immediately after and queries
a corrupted domtree, causing weird miscompiles.

This commit disables the preservation of LVI for the time being.
Eventually, we should either move LVI to a proper dependency
tracking mechanism (i.e. an analyses shouldn't hold references
to other analyses and compute them on demand if needed), or
we should teach all the passes preserving LVI to preserve the
analyses LVI depends on.

The new pass manager has a mechanism to invalidate LVI in case
one of the analyses it depends on becomes invalid, so this problem
shouldn't exist (at least not in this immediate form), but handling
of analyses holding references is still a very delicate subject.

Fixes PR33917 (and rustc).
------------------------------------------------------------------------

llvm-svn: 309439
2017-07-28 21:36:30 +00:00
Hans Wennborg
22f08d0358 Merging r309113:
------------------------------------------------------------------------
r309113 | yamaguchi | 2017-07-26 06:36:58 -0700 (Wed, 26 Jul 2017) | 19 lines

[Bash-autocompletion] Show HelpText with possible flags

Summary:
`clang --autocomplete=-std` will show
```
-std:   Language standard to compile for
-std=   Language standard to compile for
-stdlib=        C++ standard library to use
```
after this change.

However, showing HelpText with completion in bash seems super tricky, so
this feature will be used in other shells (fish, zsh...).

Reviewers: v.g.vassilev, teemperor, ruiu

Subscribers: cfe-commits, hiraditya

Differential Revision: https://reviews.llvm.org/D35759
------------------------------------------------------------------------

llvm-svn: 309438
2017-07-28 21:31:07 +00:00
Hans Wennborg
19f0654d11 Merging r309113:
------------------------------------------------------------------------
r309113 | yamaguchi | 2017-07-26 06:36:58 -0700 (Wed, 26 Jul 2017) | 19 lines

[Bash-autocompletion] Show HelpText with possible flags

Summary:
`clang --autocomplete=-std` will show
```
-std:   Language standard to compile for
-std=   Language standard to compile for
-stdlib=        C++ standard library to use
```
after this change.

However, showing HelpText with completion in bash seems super tricky, so
this feature will be used in other shells (fish, zsh...).

Reviewers: v.g.vassilev, teemperor, ruiu

Subscribers: cfe-commits, hiraditya

Differential Revision: https://reviews.llvm.org/D35759
------------------------------------------------------------------------

llvm-svn: 309437
2017-07-28 21:29:27 +00:00
Hans Wennborg
b1e6ce651e Merging r309112:
------------------------------------------------------------------------
r309112 | yamaguchi | 2017-07-26 06:30:36 -0700 (Wed, 26 Jul 2017) | 7 lines

[Bash-completion] Fixed a bug that file doesn't autocompleted after =

Summary:
File path wasn't autocompleted after `-fmodule-cache-path=[tab]`, so
fixed this bug by checking if $flags contains only a newline or not.

Differential Revision: https://reviews.llvm.org/D35763
------------------------------------------------------------------------

llvm-svn: 309435
2017-07-28 21:25:21 +00:00
Hans Wennborg
336501921c Merging r309302:
------------------------------------------------------------------------
r309302 | rksimon | 2017-07-27 11:15:54 -0700 (Thu, 27 Jul 2017) | 3 lines

[SelectionDAG] Improve DAGTypeLegalizer::convertMask assertion (PR33960)

Improve DAGTypeLegalizer::convertMask's isSETCCorConvertedSETCC assertion to properly check for any mixture of SETCC or BUILD_VECTOR of constants, or a logical mask op of them.
------------------------------------------------------------------------

llvm-svn: 309348
2017-07-28 01:32:26 +00:00
Hans Wennborg
55265143ae Merging r309327:
------------------------------------------------------------------------
r309327 | compnerd | 2017-07-27 14:56:25 -0700 (Thu, 27 Jul 2017) | 5 lines

Headers: fix _Unwind_{G,S}etGR for non-EHABI targets

The EHABI definition was being inlined into the users even when EHABI
was not in use.  Adjust the condition to ensure that the right version
is defined.
------------------------------------------------------------------------

llvm-svn: 309328
2017-07-27 22:08:00 +00:00
Hans Wennborg
ebfe7efd15 Merging r309300:
------------------------------------------------------------------------
r309300 | hans | 2017-07-27 11:14:00 -0700 (Thu, 27 Jul 2017) | 1 line

Tiny docs fix
------------------------------------------------------------------------

llvm-svn: 309301
2017-07-27 18:14:22 +00:00
Hans Wennborg
eb1131e1b0 Merging r308505:
------------------------------------------------------------------------
r308505 | efriedma | 2017-07-19 11:18:37 -0700 (Wed, 19 Jul 2017) | 5 lines

[docs] Minor formatting fixes.

Patch by Tarun Rajendran.


------------------------------------------------------------------------

llvm-svn: 309299
2017-07-27 18:13:18 +00:00
Hans Wennborg
22daae4004 Merging r309226:
------------------------------------------------------------------------
r309226 | compnerd | 2017-07-26 15:55:23 -0700 (Wed, 26 Jul 2017) | 13 lines

Headers: improve ARM EHABI coverage of unwind.h

Ensure that we define the `_Unwind_Control_Block` structure used on ARM
EHABI targets.  This is needed for building libc++abi with the unwind.h
from the resource dir.  A minor fallout of this is that we needed to
create a typedef for _Unwind_Exception to work across ARM EHABI and
non-EHABI targets.  The structure definitions here are based originally
on the documentation from ARM under the "Exception Handling ABI for the
ARM® Architecture" Section 7.2.  They are then adjusted to more closely
reflect the definition in libunwind from LLVM.  Those changes are
compatible in layout but permit easier use in libc++abi and help
maintain compatibility between libunwind and the compiler provided
definition.
------------------------------------------------------------------------

llvm-svn: 309290
2017-07-27 16:45:43 +00:00
Hans Wennborg
3071cbf297 Revert r304835: It's not clear printing all targets with --version is the right thing to do (see discussion on D33900)
llvm-svn: 309286
2017-07-27 16:21:47 +00:00
Hans Wennborg
8ca696481b Revert r304899 and r304836: It's not clear printing all targets with --version is the right thing to do (see discussion on D33900)
llvm-svn: 309285
2017-07-27 16:20:45 +00:00
Hans Wennborg
71ae69fb1f Merging r308978:
------------------------------------------------------------------------
r308978 | fedor.sergeev | 2017-07-25 08:28:28 -0700 (Tue, 25 Jul 2017) | 16 lines

[Sparc] invalid adjustments in TLS_LE/TLS_LDO relocations removed

Summary:
Some SPARC TLS relocations were applying nontrivial adjustments
to zero value, leading to unexpected non-zero values in ELF and then
Solaris linker failures.

Getting rid of these adjustments.

Fixes PR33825.

Reviewers: rafael, asb, jyknight

Subscribers: joerg, jyknight, llvm-commits

Differential Revision: https://reviews.llvm.org/D35567
------------------------------------------------------------------------

llvm-svn: 309187
2017-07-26 21:36:49 +00:00
Hans Wennborg
f48bf900c1 Merging r308808, r308813 and r308906:
------------------------------------------------------------------------
r308808 | arsenm | 2017-07-21 16:56:13 -0700 (Fri, 21 Jul 2017) | 6 lines

RA: Remove assert on empty live intervals

This is possible if there is an undef use when
splitting the vreg during spilling.

Fixes bug 33620.
------------------------------------------------------------------------

------------------------------------------------------------------------
r308813 | arsenm | 2017-07-21 17:24:01 -0700 (Fri, 21 Jul 2017) | 6 lines

RA: Remove another assert on empty intervals

This case is similar to the one fixed in r308808,
except when rematerializing.

Fixes bug 33884.
------------------------------------------------------------------------

------------------------------------------------------------------------
r308906 | arsenm | 2017-07-24 11:07:55 -0700 (Mon, 24 Jul 2017) | 6 lines

RA: Replace asserts related to empty live intervals

These don't exactly assert the same thing anymore, and
allow empty live intervals with non-empty uses.

Removed in r308808 and r308813.
------------------------------------------------------------------------

llvm-svn: 309171
2017-07-26 20:34:36 +00:00
Matt Arsenault
c4c93b7459 Merging rr308903:
------------------------------------------------------------------------
r308903 | arsenm | 2017-07-24 11:06:15 -0700 (Mon, 24 Jul 2017) | 5 lines

AMDGPU: Fix allocating pseudo-registers

There's no need for these to be part of a class since
they are immediately replaced. New unreachable hit in
existing tests.'
------------------------------------------------------------------------

llvm-svn: 309157
2017-07-26 18:59:42 +00:00
Hans Wennborg
91174ebd87 Merging r309147:
------------------------------------------------------------------------
r309147 | jroelofs | 2017-07-26 11:13:57 -0700 (Wed, 26 Jul 2017) | 4 lines

Partial fix for PR33858

https://reviews.llvm.org/D35848

------------------------------------------------------------------------

llvm-svn: 309150
2017-07-26 18:30:42 +00:00
Hans Wennborg
c68cac0907 Merging r308871:
------------------------------------------------------------------------
r308871 | chill | 2017-07-24 02:19:32 -0700 (Mon, 24 Jul 2017) | 17 lines

[libunwind] Handle .ARM.exidx tables without sentinel last entry

UnwindCursor<A, R>::getInfoFromEHABISection assumes the last
entry in the index table never corresponds to a real function.
Indeed, GNU ld always inserts an EXIDX_CANTUNWIND entry,
containing the end of the .text section. However, the EHABI specification
(http://infocenter.arm.com/help/topic/com.arm.doc.ihi0038b/IHI0038B_ehabi.pdf)
does not seem to contain text that requires the presence of a sentinel entry.
In that sense the libunwind implementation isn't compliant with the specification.

This patch makes getInfoFromEHABISection examine the last entry in the index
table if upper_bound returns the end iterator.

Fixes https://bugs.llvm.org/show_bug.cgi?id=31091

Differential revision: https://reviews.llvm.org/D35265

------------------------------------------------------------------------

llvm-svn: 309143
2017-07-26 17:57:50 +00:00
Hans Wennborg
819eb09fb2 Merging r309058:
------------------------------------------------------------------------
r309058 | majnemer | 2017-07-25 16:33:58 -0700 (Tue, 25 Jul 2017) | 9 lines

[CodeGen] Correctly model std::byte's aliasing properties

std::byte, when defined as an enum, needs to be given special treatment
with regards to its aliasing properties. An array of std::byte is
allowed to be used as storage for other types.

This fixes PR33916.

Differential Revision: https://reviews.llvm.org/D35824
------------------------------------------------------------------------

llvm-svn: 309135
2017-07-26 16:35:53 +00:00
Hans Wennborg
dfe8875cdb Merging r308950:
------------------------------------------------------------------------
r308950 | mstorsjo | 2017-07-24 22:20:01 -0700 (Mon, 24 Jul 2017) | 22 lines

[AArch64] Reserve a 16 byte aligned amount of fixed stack for win64 varargs

Create a dummy 8 byte fixed object for the unused slot below the first
stored vararg.

Alternative ideas tested but skipped: One could try to align the whole
fixed object to 16, but I haven't found how to add an offset to the stack
frame used in LowerWin64_VASTART.

If only the size of the fixed stack object size is padded but not the offset, via
MFI.CreateFixedObject(alignTo(GPRSaveSize, 16), -(int)GPRSaveSize, false),
PrologEpilogInserter crashes due to "Attempted to reset backwards range!".

This fixes misconceptions about where registers are spilled, since
AArch64FrameLowering.cpp assumes the offset from fixed objects is
aligned to 16 bytes (and the Win64 case there already manually aligns
the offset to 16 bytes).

This fixes cases where local stack allocations could overwrite callee
saved registers on the stack.

Differential Revision: https://reviews.llvm.org/D35720
------------------------------------------------------------------------

llvm-svn: 309132
2017-07-26 16:25:26 +00:00
Hans Wennborg
f94d921e4b Merging r308891:
------------------------------------------------------------------------
r308891 | d0k | 2017-07-24 09:18:09 -0700 (Mon, 24 Jul 2017) | 16 lines

[CodeGenPrepare] Cut off FindAllMemoryUses if there are too many uses.

This avoids excessive compile time. The case I'm looking at is
Function.cpp from an old version of LLVM that still had the giant memcmp
string matcher in it. Before r308322 this compiled in about 2 minutes,
after it, clang takes infinite* time to compile it. With this patch
we're at 5 min, which is still bad but this is a pathological case.

The cut off at 20 uses was chosen by looking at other cut-offs in LLVM
for user scanning. It's probably too high, but does the job and is very
unlikely to regress anything.

Fixes PR33900.

* I'm impatient and aborted after 15 minutes, on the bug report it was
  killed after 2h.
------------------------------------------------------------------------

llvm-svn: 309131
2017-07-26 16:19:02 +00:00
Hans Wennborg
5f3aa46d7d Merging r308824:
------------------------------------------------------------------------
r308824 | yamaguchi | 2017-07-22 05:35:15 -0700 (Sat, 22 Jul 2017) | 5 lines

[Bash-autocompletion] Fixed typo and add '-' after -Wno

Summary: -Wno-<warning> was autocompleted as -Wno<warning>, so fixed this typo.

Differential Revision: https://reviews.llvm.org/D35762
------------------------------------------------------------------------

llvm-svn: 309130
2017-07-26 16:15:18 +00:00
Hans Wennborg
6a7307eacb Merging r308998 and r309002:
------------------------------------------------------------------------
r308998 | nico | 2017-07-25 11:08:03 -0700 (Tue, 25 Jul 2017) | 7 lines

lld: only write .manifest files if /manifest is passed, PR33925

Also emit an error if /manifestinput: is used without /manifest:embed.
Increases compatibility with link.exe

https://reviews.llvm.org/D35842

------------------------------------------------------------------------

------------------------------------------------------------------------
r309002 | nico | 2017-07-25 11:39:38 -0700 (Tue, 25 Jul 2017) | 6 lines

Attempt to fix lld tests on Windows after 308998.

The test used /manifestinput: without /manifest:embed, which isn't actually
supported.  Just remove this part of the test for now; if it's important to
check this the llvm-readobj part should be extended to check this.

------------------------------------------------------------------------

llvm-svn: 309128
2017-07-26 16:07:19 +00:00
Hans Wennborg
01884d2429 Merging r308986 and r308963:
------------------------------------------------------------------------
r308963 | rksimon | 2017-07-25 03:33:36 -0700 (Tue, 25 Jul 2017) | 1 line

[X86] Add 24-byte memcmp tests (PR33914)
------------------------------------------------------------------------

------------------------------------------------------------------------
r308986 | rksimon | 2017-07-25 10:04:37 -0700 (Tue, 25 Jul 2017) | 9 lines

[X86][CGP] Reduce memcmp() expansion to 2 load pairs (PR33914)

D35067/rL308322 attempted to support up to 4 load pairs for memcmp inlining which resulted in regressions for some optimized libc memcmp implementations (PR33914).

Until we can match these more optimal cases, this patch reduces the memcmp expansion to a maximum of 2 load pairs (which matches what we do for -Os).

This patch should be considered for the 5.0.0 release branch as well

Differential Revision: https://reviews.llvm.org/D35830
------------------------------------------------------------------------

llvm-svn: 309127
2017-07-26 16:03:00 +00:00
Hans Wennborg
5e62a55b8a Merging r309115:
------------------------------------------------------------------------
r309115 | hahnfeld | 2017-07-26 06:55:00 -0700 (Wed, 26 Jul 2017) | 15 lines

[CMake] Disable building libomptarget and add CMake switch

Introduce OPENMP_ENABLE_LIBOMPTARGET which defaults to OFF at the moment.

libomptarget is not yet ready for prime time:
 - Offloading to NVIDIA GPUs is not completed yet (compiler, device RTL)
 - The generic ELF plugin for offloading to the host (meant for testing)
   uses a single instance of the OpenMP runtime (libomp). That is why
   omp_is_initial_device() returns 1 which makes the tests fail.
Because of these reasons, we want to disable building (and testing!)
for release 5.0.

See https://bugs.llvm.org/show_bug.cgi?id=33859

Differential Revision: https://reviews.llvm.org/D35719
------------------------------------------------------------------------

llvm-svn: 309126
2017-07-26 15:47:03 +00:00
Tom Stellard
f53e32121c Merging r308912:
------------------------------------------------------------------------
r308912 | tstellar | 2017-07-24 15:28:30 -0400 (Mon, 24 Jul 2017) | 14 lines

test-release.sh: Fix phase2 and phase3 binary comparision

Summary:
scudo_utils.cpp.o from compiler-rt has one of the host compiler's builtin
include paths stored in the .debug_line section.  So we need to do
sed 's,Phase1,Phase2,g` on the Phase2 object file so it matches Phase3.

Reviewers: hans

Reviewed By: hans

Subscribers: llvm-commits

Differential Revision: https://reviews.llvm.org/D34989
------------------------------------------------------------------------

llvm-svn: 309003
2017-07-25 19:01:47 +00:00
Hans Wennborg
2ca86003ab Merging r308897:
------------------------------------------------------------------------
r308897 | nico | 2017-07-24 09:54:11 -0700 (Mon, 24 Jul 2017) | 9 lines

Work around an MSVC2017 update 3 codegen bug.

C2017 update 3 produces a clang that crashes when compiling clang. Disabling
optimizations for StmtProfiler::VisitCXXOperatorCallExpr() makes the crash go
away.

Patch from Bruce Dawson <brucedawson@chromium.org>!
https://reviews.llvm.org/D35757

------------------------------------------------------------------------

llvm-svn: 308988
2017-07-25 17:10:17 +00:00
Rui Ueyama
c5bf9e227e Merging r308935:
------------------------------------------------------------------------
r308935 | tstellar | 2017-07-24 16:13:31 -0700 (Mon, 24 Jul 2017) | 13 lines

Fix ObjCPass on big-endian host

Summary:
This fixes test/mach-o/objc-image-info-pass-output.yaml on
big-endian hosts.

Reviewers: lhames, kledzik, ruiu

Reviewed By: ruiu

Subscribers: llvm-commits

Differential Revision: https://reviews.llvm.org/D35052
------------------------------------------------------------------------

llvm-svn: 308937
2017-07-24 23:33:06 +00:00
Rui Ueyama
dfc549020c Fix typos and grammatical errors.
Pointed out by Nico Weber.

llvm-svn: 308934
2017-07-24 22:54:04 +00:00
Craig Topper
a2e23a88da [Docs] Add some release notes for X86 target.
llvm-svn: 308831
2017-07-22 22:32:30 +00:00
Rui Ueyama
674d6c528e Merging r308492:
------------------------------------------------------------------------
r308492 | rafael | 2017-07-19 09:45:05 -0700 (Wed, 19 Jul 2017) | 20 lines

Bring back r307364.

In addition this includes a change to prefer symbols with a default
version @@ over unversioned symbols.

Original commit message:

[ELF] - Handle symbols with default version early.

This fixes last testcase provided in PR28414.
In short issue is next: when we had X@@Version symbol in object A,
we did not resolve it to X early. Then when in another object B
we had reference to undefined X, symbol X from archive was fetched.
Since both archive and object A contains another symbol Z, duplicate
symbol definition was triggered as a result.

Correct behavior is to use X@@Version from object A instead and do not fetch
any symbols from archive.

Differential revision: https://reviews.llvm.org/D35059
------------------------------------------------------------------------

llvm-svn: 308788
2017-07-21 21:38:59 +00:00
Rui Ueyama
d9bbfe9dc5 Merging r308728:
------------------------------------------------------------------------
r308728 | ikudrin | 2017-07-21 04:26:08 -0700 (Fri, 21 Jul 2017) | 3 lines

[ELF] Avoid data race in ObjectFile<ELFT>::getDILineInfo().

Differential Revision: https://reviews.llvm.org/D35537
------------------------------------------------------------------------

llvm-svn: 308786
2017-07-21 21:36:54 +00:00
Rui Ueyama
0f8b85b55c Add more contents to lld 5.0 release notes.
llvm-svn: 308778
2017-07-21 21:04:18 +00:00
Hans Wennborg
aaa5fa6aab ReleaseNotes: fix sphinx error
llvm-svn: 308730
2017-07-21 12:25:53 +00:00
Hans Wennborg
177e29dabf Regenerate ClangCommandLineReference.rst
I ran:

$ bin/clang-tblgen -gen-opt-docs -I../cfe.src/include \
    -I../cfe.src/include/clang/Driver -I../llvm.src/include \
    ../cfe.src/include/clang/Driver/ClangOptionDocs.td \
    -o ../cfe.src/docs/ClangCommandLineReference.rst

llvm-svn: 308720
2017-07-21 08:17:53 +00:00
Hans Wennborg
1852dd26e0 Merging r308503:
------------------------------------------------------------------------
r308503 | davide | 2017-07-19 11:09:46 -0700 (Wed, 19 Jul 2017) | 3 lines

[X86] Don't try to scale down if that exceeds the bitwidth.

Fixes the crash reported in PR33844.
------------------------------------------------------------------------

llvm-svn: 308718
2017-07-21 08:01:42 +00:00
Hans Wennborg
22c994fbf6 Merging r308512:
------------------------------------------------------------------------
r308512 | pfaffe | 2017-07-19 12:20:58 -0700 (Wed, 19 Jul 2017) | 4 lines

[CMake] Fix r307650: Readd missing dependency.

The commit erroneously removed the dependency of the Polly tests on
things like opt and FileCheck. Add that dependency back.
------------------------------------------------------------------------

llvm-svn: 308717
2017-07-21 07:53:25 +00:00
Rui Ueyama
cc566f1e64 Add contents to lld 5.0's release notes.
llvm-svn: 308700
2017-07-21 00:28:02 +00:00
Hans Wennborg
44df7006f6 Revert the whitespace change
llvm-svn: 308628
2017-07-20 16:32:10 +00:00
Hans Wennborg
aa697b3ba5 Whitespace change to trigger the branch showing in git
llvm-svn: 308627
2017-07-20 16:32:02 +00:00
Hans Wennborg
aa4b557456 Merging r308484:
------------------------------------------------------------------------
r308484 | hans | 2017-07-19 08:06:31 -0700 (Wed, 19 Jul 2017) | 1 line

Defeat another -Wunused-but-set-variable warning
------------------------------------------------------------------------

llvm-svn: 308488
2017-07-19 15:45:56 +00:00
Hans Wennborg
4936ca494d Merging r308483:
------------------------------------------------------------------------
r308483 | hans | 2017-07-19 08:03:38 -0700 (Wed, 19 Jul 2017) | 12 lines

Defeat a GCC -Wunused-result warning

It was warning like:

../llvm-project/llvm/lib/Support/ErrorHandling.cpp:172:51: warning:
ignoring return value of ‘ssize_t write(int, const void*, size_t)’,
         declared with attribute warn_unused_result [-Wunused-result]
            (void)::write(2, OOMMessage, strlen(OOMMessage));

Work around the warning by storing the return value in a variable and
casting that to void instead. We already did this for the other write()
call in this file.
------------------------------------------------------------------------

llvm-svn: 308487
2017-07-19 15:45:34 +00:00
Matt Arsenault
cb6592cf0c Add some 5.0 release notes
Note speculatable and alloca address space change.

llvm-svn: 308482
2017-07-19 14:56:08 +00:00
Hans Wennborg
03601601ac Generate docs/AttributeReference.rst
$ bin/clang-tblgen -gen-attr-docs -I../cfe.src/include \
    ../cfe.src/include/clang/Basic/Attr.td \
    -o ../cfe.src/docs/AttributeReference.rst

llvm-svn: 308481
2017-07-19 14:44:30 +00:00
Hans Wennborg
9bfb21b723 Drop 'svn' suffix from version number.
llvm-svn: 308472
2017-07-19 14:04:52 +00:00
Hans Wennborg
fad0760ebc Drop 'svn' suffix from version number.
llvm-svn: 308471
2017-07-19 14:04:38 +00:00
Hans Wennborg
58b68590a6 Drop 'svn' suffix from version number.
llvm-svn: 308470
2017-07-19 14:04:19 +00:00
Hans Wennborg
2ad6823efe Drop 'svn' suffix from version number.
llvm-svn: 308469
2017-07-19 14:03:56 +00:00
Hans Wennborg
da85f00deb Merging r308455:
------------------------------------------------------------------------
r308455 | hans | 2017-07-19 05:31:01 -0700 (Wed, 19 Jul 2017) | 16 lines

Revert r308441 "Recommit r308327: Add a warning for missing '#pragma pack (pop)' and suspicious uses of '#pragma pack' in included files"

This seems to have broken the sanitizer-x86_64-linux buildbot. Reverting until
it's fixed, especially since this landed just before the 5.0 branch.

> This commit adds a new -Wpragma-pack warning. It warns in the following cases:
>
> - When a translation unit is missing terminating #pragma pack (pop) directives.
> - When entering an included file if the current alignment value as determined
>   by '#pragma pack' directives is different from the default alignment value.
> - When leaving an included file that changed the state of the current alignment
>   value.
>
> rdar://10184173
>
> Differential Revision: https://reviews.llvm.org/D35484
------------------------------------------------------------------------

llvm-svn: 308457
2017-07-19 13:02:51 +00:00
Hans Wennborg
6006246822 Creating release_50 branch off revision 308441
llvm-svn: 308454
llvm-svn: 308453
llvm-svn: 308452
llvm-svn: 308451
llvm-svn: 308450
llvm-svn: 308449
llvm-svn: 308448
llvm-svn: 308447
llvm-svn: 308446
llvm-svn: 308444
llvm-svn: 308443
2017-07-19 12:20:59 +00:00
17847 changed files with 444676 additions and 1207960 deletions

View File

@@ -1,4 +1,4 @@
{
"repository.callsign" : "CTE",
"project_id" : "clang-tools-extra",
"conduit_uri" : "https://reviews.llvm.org/"
}

View File

@@ -15,7 +15,8 @@ add_subdirectory(pp-trace)
add_subdirectory(tool-template)
# Add the common testsuite after all the tools.
if(CLANG_INCLUDE_TESTS)
# TODO: Support tests with more granularity when features are off?
if(CLANG_ENABLE_STATIC_ANALYZER AND CLANG_INCLUDE_TESTS)
add_subdirectory(test)
add_subdirectory(unittests)
endif()

View File

@@ -427,8 +427,7 @@ void ChangeNamespaceTool::registerMatchers(ast_matchers::MatchFinder *Finder) {
unless(templateSpecializationType())))))),
hasParent(nestedNameSpecifierLoc()),
hasAncestor(isImplicit()),
hasAncestor(UsingShadowDeclInClass),
hasAncestor(functionDecl(isDefaulted())))),
hasAncestor(UsingShadowDeclInClass))),
hasAncestor(decl().bind("dc")))
.bind("type"),
this);
@@ -452,7 +451,6 @@ void ChangeNamespaceTool::registerMatchers(ast_matchers::MatchFinder *Finder) {
specifiesType(hasDeclaration(DeclMatcher.bind("from_decl"))))),
unless(anyOf(hasAncestor(isImplicit()),
hasAncestor(UsingShadowDeclInClass),
hasAncestor(functionDecl(isDefaulted())),
hasAncestor(typeLoc(loc(qualType(hasDeclaration(
decl(equalsBoundNode("from_decl"))))))))))
.bind("nested_specifier_loc"),
@@ -552,10 +550,6 @@ void ChangeNamespaceTool::run(
if (Loc.getTypeLocClass() == TypeLoc::Elaborated) {
NestedNameSpecifierLoc NestedNameSpecifier =
Loc.castAs<ElaboratedTypeLoc>().getQualifierLoc();
// This happens for friend declaration of a base class with injected class
// name.
if (!NestedNameSpecifier.getNestedNameSpecifier())
return;
const Type *SpecifierType =
NestedNameSpecifier.getNestedNameSpecifier()->getAsType();
if (SpecifierType && SpecifierType->isRecordType())

View File

@@ -8,7 +8,6 @@ add_clang_executable(clang-change-namespace
ClangChangeNamespace.cpp
)
target_link_libraries(clang-change-namespace
PRIVATE
clangAST
clangASTMatchers
clangBasic

View File

@@ -288,12 +288,13 @@ bool mergeAndDeduplicate(const TUReplacements &TUs,
for (const tooling::Replacement &R : TU.Replacements) {
// Use the file manager to deduplicate paths. FileEntries are
// automatically canonicalized.
if (const FileEntry *Entry = SM.getFileManager().getFile(R.getFilePath())) {
GroupedReplacements[Entry].push_back(R);
} else if (Warned.insert(R.getFilePath()).second) {
errs() << "Described file '" << R.getFilePath()
<< "' doesn't exist. Ignoring...\n";
const FileEntry *Entry = SM.getFileManager().getFile(R.getFilePath());
if (!Entry && Warned.insert(R.getFilePath()).second) {
errs() << "Described file '" << R.getFilePath()
<< "' doesn't exist. Ignoring...\n";
continue;
}
GroupedReplacements[Entry].push_back(R);
}
}
@@ -313,12 +314,13 @@ bool mergeAndDeduplicate(const TUDiagnostics &TUs,
for (const tooling::Replacement &R : Fix.second) {
// Use the file manager to deduplicate paths. FileEntries are
// automatically canonicalized.
if (const FileEntry *Entry = SM.getFileManager().getFile(R.getFilePath())) {
GroupedReplacements[Entry].push_back(R);
} else if (Warned.insert(R.getFilePath()).second) {
errs() << "Described file '" << R.getFilePath()
<< "' doesn't exist. Ignoring...\n";
const FileEntry *Entry = SM.getFileManager().getFile(R.getFilePath());
if (!Entry && Warned.insert(R.getFilePath()).second) {
errs() << "Described file '" << R.getFilePath()
<< "' doesn't exist. Ignoring...\n";
continue;
}
GroupedReplacements[Entry].push_back(R);
}
}
}

View File

@@ -6,7 +6,6 @@ add_clang_executable(clang-apply-replacements
ClangApplyReplacementsMain.cpp
)
target_link_libraries(clang-apply-replacements
PRIVATE
clangApplyReplacements
clangBasic
clangFormat

View File

@@ -82,8 +82,8 @@ private:
};
} // namespace
static void printVersion(raw_ostream &OS) {
OS << "clang-apply-replacements version " CLANG_VERSION_STRING << "\n";
static void printVersion() {
outs() << "clang-apply-replacements version " CLANG_VERSION_STRING << "\n";
}
/// \brief Convenience function to get rewritten content for \c Filename from
@@ -199,7 +199,7 @@ applyFormatting(const std::vector<tooling::Replacement> &Replacements,
int main(int argc, char **argv) {
cl::HideUnrelatedOptions(makeArrayRef(VisibleCategories));
cl::SetVersionPrinter(printVersion);
cl::SetVersionPrinter(&printVersion);
cl::ParseCommandLineOptions(argc, argv);
IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions());

View File

@@ -5,7 +5,6 @@ add_clang_executable(clang-move
)
target_link_libraries(clang-move
PRIVATE
clangAST
clangASTMatchers
clangBasic

View File

@@ -2,7 +2,6 @@ include_directories(${CMAKE_CURRENT_SOURCE_DIR}/..)
add_clang_executable(clang-query ClangQuery.cpp)
target_link_libraries(clang-query
PRIVATE
clangAST
clangASTMatchers
clangBasic

View File

@@ -22,23 +22,21 @@
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Lex/Lexer.h"
#include "clang/Tooling/Refactoring.h"
#include "llvm/ADT/SetVector.h"
#include <algorithm>
#include <string>
namespace clang {
namespace reorder_fields {
using namespace clang::ast_matchers;
using llvm::SmallSetVector;
/// \brief Finds the definition of a record by name.
///
/// \returns nullptr if the name is ambiguous or not found.
static const RecordDecl *findDefinition(StringRef RecordName,
ASTContext &Context) {
auto Results =
match(recordDecl(hasName(RecordName), isDefinition()).bind("recordDecl"),
Context);
static const CXXRecordDecl *findDefinition(StringRef RecordName,
ASTContext &Context) {
auto Results = match(
recordDecl(hasName(RecordName), isDefinition()).bind("cxxRecordDecl"),
Context);
if (Results.empty()) {
llvm::errs() << "Definition of " << RecordName << " not found\n";
return nullptr;
@@ -48,14 +46,14 @@ static const RecordDecl *findDefinition(StringRef RecordName,
<< " is ambiguous, several definitions found\n";
return nullptr;
}
return selectFirst<RecordDecl>("recordDecl", Results);
return selectFirst<CXXRecordDecl>("cxxRecordDecl", Results);
}
/// \brief Calculates the new order of fields.
///
/// \returns empty vector if the list of fields doesn't match the definition.
static SmallVector<unsigned, 4>
getNewFieldsOrder(const RecordDecl *Definition,
getNewFieldsOrder(const CXXRecordDecl *Definition,
ArrayRef<std::string> DesiredFieldsOrder) {
assert(Definition && "Definition is null");
@@ -93,35 +91,13 @@ addReplacement(SourceRange Old, SourceRange New, const ASTContext &Context,
consumeError(Replacements[R.getFilePath()].add(R));
}
/// \brief Find all member fields used in the given init-list initializer expr
/// that belong to the same record
///
/// \returns a set of field declarations, empty if none were present
static SmallSetVector<FieldDecl *, 1>
findMembersUsedInInitExpr(const CXXCtorInitializer *Initializer,
ASTContext &Context) {
SmallSetVector<FieldDecl *, 1> Results;
// Note that this does not pick up member fields of base classes since
// for those accesses Sema::PerformObjectMemberConversion always inserts an
// UncheckedDerivedToBase ImplicitCastExpr between the this expr and the
// object expression
auto FoundExprs =
match(findAll(memberExpr(hasObjectExpression(cxxThisExpr())).bind("ME")),
*Initializer->getInit(), Context);
for (BoundNodes &BN : FoundExprs)
if (auto *MemExpr = BN.getNodeAs<MemberExpr>("ME"))
if (auto *FD = dyn_cast<FieldDecl>(MemExpr->getMemberDecl()))
Results.insert(FD);
return Results;
}
/// \brief Reorders fields in the definition of a struct/class.
///
/// At the moment reodering of fields with
/// different accesses (public/protected/private) is not supported.
/// \returns true on success.
static bool reorderFieldsInDefinition(
const RecordDecl *Definition, ArrayRef<unsigned> NewFieldsOrder,
const CXXRecordDecl *Definition, ArrayRef<unsigned> NewFieldsOrder,
const ASTContext &Context,
std::map<std::string, tooling::Replacements> &Replacements) {
assert(Definition && "Definition is null");
@@ -153,12 +129,11 @@ static bool reorderFieldsInDefinition(
/// \brief Reorders initializers in a C++ struct/class constructor.
///
/// A constructor can have initializers for an arbitrary subset of the class's
/// fields. Thus, we need to ensure that we reorder just the initializers that
/// are present.
/// A constructor can have initializers for an arbitrary subset of the class's fields.
/// Thus, we need to ensure that we reorder just the initializers that are present.
static void reorderFieldsInConstructor(
const CXXConstructorDecl *CtorDecl, ArrayRef<unsigned> NewFieldsOrder,
ASTContext &Context,
const ASTContext &Context,
std::map<std::string, tooling::Replacements> &Replacements) {
assert(CtorDecl && "Constructor declaration is null");
if (CtorDecl->isImplicit() || CtorDecl->getNumCtorInitializers() <= 1)
@@ -176,26 +151,8 @@ static void reorderFieldsInConstructor(
SmallVector<const CXXCtorInitializer *, 10> OldWrittenInitializersOrder;
SmallVector<const CXXCtorInitializer *, 10> NewWrittenInitializersOrder;
for (const auto *Initializer : CtorDecl->inits()) {
if (!Initializer->isMemberInitializer() || !Initializer->isWritten())
if (!Initializer->isWritten())
continue;
// Warn if this reordering violates initialization expr dependencies.
const FieldDecl *ThisM = Initializer->getMember();
const auto UsedMembers = findMembersUsedInInitExpr(Initializer, Context);
for (const FieldDecl *UM : UsedMembers) {
if (NewFieldsPositions[UM->getFieldIndex()] >
NewFieldsPositions[ThisM->getFieldIndex()]) {
DiagnosticsEngine &DiagEngine = Context.getDiagnostics();
auto Description = ("reordering field " + UM->getName() + " after " +
ThisM->getName() + " makes " + UM->getName() +
" uninitialized when used in init expression")
.str();
unsigned ID = DiagEngine.getDiagnosticIDs()->getCustomDiagID(
DiagnosticIDs::Warning, Description);
DiagEngine.Report(Initializer->getSourceLocation(), ID);
}
}
OldWrittenInitializersOrder.push_back(Initializer);
NewWrittenInitializersOrder.push_back(Initializer);
}
@@ -225,12 +182,12 @@ static bool reorderFieldsInInitListExpr(
const ASTContext &Context,
std::map<std::string, tooling::Replacements> &Replacements) {
assert(InitListEx && "Init list expression is null");
// We care only about InitListExprs which originate from source code.
// We care only about InitListExprs which originate from source code.
// Implicit InitListExprs are created by the semantic analyzer.
if (!InitListEx->isExplicit())
return true;
// The method InitListExpr::getSyntacticForm may return nullptr indicating
// that the current initializer list also serves as its syntactic form.
// The method InitListExpr::getSyntacticForm may return nullptr indicating that
// the current initializer list also serves as its syntactic form.
if (const auto *SyntacticForm = InitListEx->getSyntacticForm())
InitListEx = SyntacticForm;
// If there are no initializers we do not need to change anything.
@@ -242,9 +199,10 @@ static bool reorderFieldsInInitListExpr(
}
for (unsigned i = 0, e = InitListEx->getNumInits(); i < e; ++i)
if (i != NewFieldsOrder[i])
addReplacement(InitListEx->getInit(i)->getSourceRange(),
InitListEx->getInit(NewFieldsOrder[i])->getSourceRange(),
Context, Replacements);
addReplacement(
InitListEx->getInit(i)->getSourceRange(),
InitListEx->getInit(NewFieldsOrder[i])->getSourceRange(), Context,
Replacements);
return true;
}
@@ -265,7 +223,7 @@ public:
ReorderingConsumer &operator=(const ReorderingConsumer &) = delete;
void HandleTranslationUnit(ASTContext &Context) override {
const RecordDecl *RD = findDefinition(RecordName, Context);
const CXXRecordDecl *RD = findDefinition(RecordName, Context);
if (!RD)
return;
SmallVector<unsigned, 4> NewFieldsOrder =
@@ -274,21 +232,16 @@ public:
return;
if (!reorderFieldsInDefinition(RD, NewFieldsOrder, Context, Replacements))
return;
for (const auto *C : RD->ctors())
if (const auto *D = dyn_cast<CXXConstructorDecl>(C->getDefinition()))
reorderFieldsInConstructor(cast<const CXXConstructorDecl>(D),
NewFieldsOrder, Context, Replacements);
// CXXRD will be nullptr if C code (not C++) is being processed.
const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
if (CXXRD)
for (const auto *C : CXXRD->ctors())
if (const auto *D = dyn_cast<CXXConstructorDecl>(C->getDefinition()))
reorderFieldsInConstructor(cast<const CXXConstructorDecl>(D),
NewFieldsOrder, Context, Replacements);
// We only need to reorder init list expressions for
// plain C structs or C++ aggregate types.
// We only need to reorder init list expressions for aggregate types.
// For other types the order of constructor parameters is used,
// which we don't change at the moment.
// Now (v0) partial initialization is not supported.
if (!CXXRD || CXXRD->isAggregate())
if (RD->isAggregate())
for (auto Result :
match(initListExpr(hasType(equalsNode(RD))).bind("initListExpr"),
Context))

View File

@@ -1,7 +1,6 @@
add_clang_tool(clang-reorder-fields ClangReorderFields.cpp)
add_clang_executable(clang-reorder-fields ClangReorderFields.cpp)
target_link_libraries(clang-reorder-fields
PRIVATE
clangBasic
clangFrontend
clangReorderFields
@@ -9,3 +8,5 @@ target_link_libraries(clang-reorder-fields
clangTooling
clangToolingCore
)
install(TARGETS clang-reorder-fields RUNTIME DESTINATION bin)

View File

@@ -31,14 +31,12 @@ add_subdirectory(boost)
add_subdirectory(bugprone)
add_subdirectory(cert)
add_subdirectory(cppcoreguidelines)
add_subdirectory(fuchsia)
add_subdirectory(google)
add_subdirectory(hicpp)
add_subdirectory(llvm)
add_subdirectory(misc)
add_subdirectory(modernize)
add_subdirectory(mpi)
add_subdirectory(objc)
add_subdirectory(performance)
add_subdirectory(plugin)
add_subdirectory(readability)

View File

@@ -21,7 +21,6 @@
#include "clang/AST/ASTDiagnostic.h"
#include "clang/Basic/DiagnosticOptions.h"
#include "clang/Frontend/DiagnosticRenderer.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallString.h"
#include <tuple>
#include <vector>
@@ -116,7 +115,7 @@ ClangTidyError::ClangTidyError(StringRef CheckName,
// Returns true if GlobList starts with the negative indicator ('-'), removes it
// from the GlobList.
static bool ConsumeNegativeIndicator(StringRef &GlobList) {
GlobList = GlobList.trim(" \r\n");
GlobList = GlobList.trim(' ');
if (GlobList.startswith("-")) {
GlobList = GlobList.substr(1);
return true;
@@ -291,38 +290,7 @@ void ClangTidyDiagnosticConsumer::finalizeLastError() {
LastErrorPassesLineFilter = false;
}
static bool IsNOLINTFound(StringRef NolintDirectiveText, StringRef Line,
unsigned DiagID, const ClangTidyContext &Context) {
const size_t NolintIndex = Line.find(NolintDirectiveText);
if (NolintIndex == StringRef::npos)
return false;
size_t BracketIndex = NolintIndex + NolintDirectiveText.size();
// Check if the specific checks are specified in brackets.
if (BracketIndex < Line.size() && Line[BracketIndex] == '(') {
++BracketIndex;
const size_t BracketEndIndex = Line.find(')', BracketIndex);
if (BracketEndIndex != StringRef::npos) {
StringRef ChecksStr =
Line.substr(BracketIndex, BracketEndIndex - BracketIndex);
// Allow disabling all the checks with "*".
if (ChecksStr != "*") {
StringRef CheckName = Context.getCheckName(DiagID);
// Allow specifying a few check names, delimited with comma.
SmallVector<StringRef, 1> Checks;
ChecksStr.split(Checks, ',', -1, false);
llvm::transform(Checks, Checks.begin(),
[](StringRef S) { return S.trim(); });
return llvm::find(Checks, CheckName) != Checks.end();
}
}
}
return true;
}
static bool LineIsMarkedWithNOLINT(SourceManager &SM, SourceLocation Loc,
unsigned DiagID,
const ClangTidyContext &Context) {
static bool LineIsMarkedWithNOLINT(SourceManager &SM, SourceLocation Loc) {
bool Invalid;
const char *CharacterData = SM.getCharacterData(Loc, &Invalid);
if (Invalid)
@@ -333,7 +301,8 @@ static bool LineIsMarkedWithNOLINT(SourceManager &SM, SourceLocation Loc,
while (*P != '\0' && *P != '\r' && *P != '\n')
++P;
StringRef RestOfLine(CharacterData, P - CharacterData + 1);
if (IsNOLINTFound("NOLINT", RestOfLine, DiagID, Context))
// FIXME: Handle /\bNOLINT\b(\([^)]*\))?/ as cpplint.py does.
if (RestOfLine.find("NOLINT") != StringRef::npos)
return true;
// Check if there's a NOLINTNEXTLINE on the previous line.
@@ -360,17 +329,16 @@ static bool LineIsMarkedWithNOLINT(SourceManager &SM, SourceLocation Loc,
--P;
RestOfLine = StringRef(P, LineEnd - P + 1);
if (IsNOLINTFound("NOLINTNEXTLINE", RestOfLine, DiagID, Context))
if (RestOfLine.find("NOLINTNEXTLINE") != StringRef::npos)
return true;
return false;
}
static bool LineIsMarkedWithNOLINTinMacro(SourceManager &SM, SourceLocation Loc,
unsigned DiagID,
const ClangTidyContext &Context) {
static bool LineIsMarkedWithNOLINTinMacro(SourceManager &SM,
SourceLocation Loc) {
while (true) {
if (LineIsMarkedWithNOLINT(SM, Loc, DiagID, Context))
if (LineIsMarkedWithNOLINT(SM, Loc))
return true;
if (!Loc.isMacroID())
return false;
@@ -387,8 +355,7 @@ void ClangTidyDiagnosticConsumer::HandleDiagnostic(
if (Info.getLocation().isValid() && DiagLevel != DiagnosticsEngine::Error &&
DiagLevel != DiagnosticsEngine::Fatal &&
LineIsMarkedWithNOLINTinMacro(Diags->getSourceManager(),
Info.getLocation(), Info.getID(),
Context)) {
Info.getLocation())) {
++Context.Stats.ErrorsIgnoredNOLINT;
// Ignored a warning, should ignore related notes as well
LastErrorWasIgnored = true;

View File

@@ -51,7 +51,7 @@ def write_header(module_path, module, check_name, check_name_camel):
print('Creating %s...' % filename)
with open(filename, 'wb') as f:
header_guard = ('LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_' + module.upper() + '_'
+ check_name_camel.upper() + '_H')
+ check_name.upper().replace('-', '_') + '_H')
f.write('//===--- ')
f.write(os.path.basename(filename))
f.write(' - clang-tidy')

View File

@@ -10,16 +10,8 @@
#include "../ClangTidy.h"
#include "../ClangTidyModule.h"
#include "../ClangTidyModuleRegistry.h"
#include "CloexecAccept4Check.h"
#include "CloexecAcceptCheck.h"
#include "CloexecCreatCheck.h"
#include "CloexecEpollCreate1Check.h"
#include "CloexecEpollCreateCheck.h"
#include "CloexecDupCheck.h"
#include "CloexecFopenCheck.h"
#include "CloexecInotifyInit1Check.h"
#include "CloexecInotifyInitCheck.h"
#include "CloexecMemfdCreateCheck.h"
#include "CloexecOpenCheck.h"
#include "CloexecSocketCheck.h"
@@ -33,21 +25,8 @@ namespace android {
class AndroidModule : public ClangTidyModule {
public:
void addCheckFactories(ClangTidyCheckFactories &CheckFactories) override {
CheckFactories.registerCheck<CloexecAccept4Check>("android-cloexec-accept4");
CheckFactories.registerCheck<CloexecAcceptCheck>("android-cloexec-accept");
CheckFactories.registerCheck<CloexecCreatCheck>("android-cloexec-creat");
CheckFactories.registerCheck<CloexecEpollCreate1Check>(
"android-cloexec-epoll-create1");
CheckFactories.registerCheck<CloexecEpollCreateCheck>(
"android-cloexec-epoll-create");
CheckFactories.registerCheck<CloexecDupCheck>("android-cloexec-dup");
CheckFactories.registerCheck<CloexecFopenCheck>("android-cloexec-fopen");
CheckFactories.registerCheck<CloexecInotifyInitCheck>(
"android-cloexec-inotify-init");
CheckFactories.registerCheck<CloexecInotifyInit1Check>(
"android-cloexec-inotify-init1");
CheckFactories.registerCheck<CloexecMemfdCreateCheck>(
"android-cloexec-memfd-create");
CheckFactories.registerCheck<CloexecOpenCheck>("android-cloexec-open");
CheckFactories.registerCheck<CloexecSocketCheck>("android-cloexec-socket");
}

View File

@@ -2,17 +2,8 @@ set(LLVM_LINK_COMPONENTS support)
add_clang_library(clangTidyAndroidModule
AndroidTidyModule.cpp
CloexecAccept4Check.cpp
CloexecAcceptCheck.cpp
CloexecCheck.cpp
CloexecCreatCheck.cpp
CloexecEpollCreate1Check.cpp
CloexecEpollCreateCheck.cpp
CloexecDupCheck.cpp
CloexecFopenCheck.cpp
CloexecInotifyInit1Check.cpp
CloexecInotifyInitCheck.cpp
CloexecMemfdCreateCheck.cpp
CloexecOpenCheck.cpp
CloexecSocketCheck.cpp

View File

@@ -1,40 +0,0 @@
//===--- CloexecAccept4Check.cpp - clang-tidy------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "CloexecAccept4Check.h"
#include "../utils/ASTUtils.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
using namespace clang::ast_matchers;
namespace clang {
namespace tidy {
namespace android {
void CloexecAccept4Check::registerMatchers(MatchFinder *Finder) {
auto SockAddrPointerType =
hasType(pointsTo(recordDecl(isStruct(), hasName("sockaddr"))));
auto SockLenPointerType = hasType(pointsTo(namedDecl(hasName("socklen_t"))));
registerMatchersImpl(Finder,
functionDecl(returns(isInteger()), hasName("accept4"),
hasParameter(0, hasType(isInteger())),
hasParameter(1, SockAddrPointerType),
hasParameter(2, SockLenPointerType),
hasParameter(3, hasType(isInteger()))));
}
void CloexecAccept4Check::check(const MatchFinder::MatchResult &Result) {
insertMacroFlag(Result, /*MarcoFlag=*/"SOCK_CLOEXEC", /*ArgPos=*/3);
}
} // namespace android
} // namespace tidy
} // namespace clang

View File

@@ -1,35 +0,0 @@
//===--- CloexecAccept4Check.h - clang-tidy----------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ANDROID_CLOEXEC_ACCEPT4_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ANDROID_CLOEXEC_ACCEPT4_H
#include "CloexecCheck.h"
namespace clang {
namespace tidy {
namespace android {
/// Finds code that uses accept4() without using the SOCK_CLOEXEC flag.
///
/// For the user-facing documentation see:
/// http://clang.llvm.org/extra/clang-tidy/checks/android-cloexec-accept4.html
class CloexecAccept4Check : public CloexecCheck {
public:
CloexecAccept4Check(StringRef Name, ClangTidyContext *Context)
: CloexecCheck(Name, Context) {}
void registerMatchers(ast_matchers::MatchFinder *Finder) override;
void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
};
} // namespace android
} // namespace tidy
} // namespace clang
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ANDROID_CLOEXEC_ACCEPT4_H

View File

@@ -1,47 +0,0 @@
//===--- CloexecAcceptCheck.cpp - clang-tidy-------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "CloexecAcceptCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
using namespace clang::ast_matchers;
namespace clang {
namespace tidy {
namespace android {
void CloexecAcceptCheck::registerMatchers(MatchFinder *Finder) {
auto SockAddrPointerType =
hasType(pointsTo(recordDecl(isStruct(), hasName("sockaddr"))));
auto SockLenPointerType = hasType(pointsTo(namedDecl(hasName("socklen_t"))));
registerMatchersImpl(Finder,
functionDecl(returns(isInteger()), hasName("accept"),
hasParameter(0, hasType(isInteger())),
hasParameter(1, SockAddrPointerType),
hasParameter(2, SockLenPointerType)));
}
void CloexecAcceptCheck::check(const MatchFinder::MatchResult &Result) {
const std::string &ReplacementText =
(Twine("accept4(") + getSpellingArg(Result, 0) + ", " +
getSpellingArg(Result, 1) + ", " + getSpellingArg(Result, 2) +
", SOCK_CLOEXEC)")
.str();
replaceFunc(
Result,
"prefer accept4() to accept() because accept4() allows SOCK_CLOEXEC",
ReplacementText);
}
} // namespace android
} // namespace tidy
} // namespace clang

View File

@@ -1,35 +0,0 @@
//===--- CloexecAcceptCheck.h - clang-tidy-----------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ANDROID_CLOEXEC_ACCEPT_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ANDROID_CLOEXEC_ACCEPT_H
#include "CloexecCheck.h"
namespace clang {
namespace tidy {
namespace android {
/// accept() is better to be replaced by accept4().
///
/// For the user-facing documentation see:
/// http://clang.llvm.org/extra/clang-tidy/checks/android-cloexec-accept.html
class CloexecAcceptCheck : public CloexecCheck {
public:
CloexecAcceptCheck(StringRef Name, ClangTidyContext *Context)
: CloexecCheck(Name, Context) {}
void registerMatchers(ast_matchers::MatchFinder *Finder) override;
void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
};
} // namespace android
} // namespace tidy
} // namespace clang
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ANDROID_CLOEXEC_ACCEPT_H

View File

@@ -1,114 +0,0 @@
//===--- CloexecCheck.cpp - clang-tidy-------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "CloexecCheck.h"
#include "../utils/ASTUtils.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Lex/Lexer.h"
using namespace clang::ast_matchers;
namespace clang {
namespace tidy {
namespace android {
namespace {
// Helper function to form the correct string mode for Type3.
// Build the replace text. If it's string constant, add <Mode> directly in the
// end of the string. Else, add <Mode>.
std::string buildFixMsgForStringFlag(const Expr *Arg, const SourceManager &SM,
const LangOptions &LangOpts, char Mode) {
if (Arg->getLocStart().isMacroID())
return (Lexer::getSourceText(
CharSourceRange::getTokenRange(Arg->getSourceRange()), SM,
LangOpts) +
" \"" + Twine(Mode) + "\"")
.str();
StringRef SR = cast<StringLiteral>(Arg->IgnoreParenCasts())->getString();
return ("\"" + SR + Twine(Mode) + "\"").str();
}
} // namespace
const char *CloexecCheck::FuncDeclBindingStr = "funcDecl";
const char *CloexecCheck::FuncBindingStr ="func";
void CloexecCheck::registerMatchersImpl(
MatchFinder *Finder, internal::Matcher<FunctionDecl> Function) {
// We assume all the checked APIs are C functions.
Finder->addMatcher(
callExpr(
callee(functionDecl(isExternC(), Function).bind(FuncDeclBindingStr)))
.bind(FuncBindingStr),
this);
}
void CloexecCheck::insertMacroFlag(const MatchFinder::MatchResult &Result,
StringRef MacroFlag, int ArgPos) {
const auto *MatchedCall = Result.Nodes.getNodeAs<CallExpr>(FuncBindingStr);
const auto *FlagArg = MatchedCall->getArg(ArgPos);
const auto *FD = Result.Nodes.getNodeAs<FunctionDecl>(FuncDeclBindingStr);
SourceManager &SM = *Result.SourceManager;
if (utils::exprHasBitFlagWithSpelling(FlagArg->IgnoreParenCasts(), SM,
Result.Context->getLangOpts(),
MacroFlag))
return;
SourceLocation EndLoc =
Lexer::getLocForEndOfToken(SM.getFileLoc(FlagArg->getLocEnd()), 0, SM,
Result.Context->getLangOpts());
diag(EndLoc, "%0 should use %1 where possible")
<< FD << MacroFlag
<< FixItHint::CreateInsertion(EndLoc, (Twine(" | ") + MacroFlag).str());
}
void CloexecCheck::replaceFunc(const MatchFinder::MatchResult &Result,
StringRef WarningMsg, StringRef FixMsg) {
const auto *MatchedCall = Result.Nodes.getNodeAs<CallExpr>(FuncBindingStr);
diag(MatchedCall->getLocStart(), WarningMsg)
<< FixItHint::CreateReplacement(MatchedCall->getSourceRange(), FixMsg);
}
void CloexecCheck::insertStringFlag(
const ast_matchers::MatchFinder::MatchResult &Result, const char Mode,
const int ArgPos) {
const auto *MatchedCall = Result.Nodes.getNodeAs<CallExpr>(FuncBindingStr);
const auto *FD = Result.Nodes.getNodeAs<FunctionDecl>(FuncDeclBindingStr);
const auto *ModeArg = MatchedCall->getArg(ArgPos);
// Check if the <Mode> may be in the mode string.
const auto *ModeStr = dyn_cast<StringLiteral>(ModeArg->IgnoreParenCasts());
if (!ModeStr || (ModeStr->getString().find(Mode) != StringRef::npos))
return;
const std::string &ReplacementText = buildFixMsgForStringFlag(
ModeArg, *Result.SourceManager, Result.Context->getLangOpts(), Mode);
diag(ModeArg->getLocStart(), "use %0 mode '%1' to set O_CLOEXEC")
<< FD << std::string(1, Mode)
<< FixItHint::CreateReplacement(ModeArg->getSourceRange(),
ReplacementText);
}
StringRef CloexecCheck::getSpellingArg(const MatchFinder::MatchResult &Result,
int N) const {
const auto *MatchedCall = Result.Nodes.getNodeAs<CallExpr>(FuncBindingStr);
const SourceManager &SM = *Result.SourceManager;
return Lexer::getSourceText(
CharSourceRange::getTokenRange(MatchedCall->getArg(N)->getSourceRange()),
SM, Result.Context->getLangOpts());
}
} // namespace android
} // namespace tidy
} // namespace clang

View File

@@ -1,105 +0,0 @@
//===--- CloexecCheck.h - clang-tidy-----------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// This file contains the declaration of the CloexecCheck class, which is the
/// base class for all of the close-on-exec checks in Android module.
///
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ANDROID_CLOEXEC_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ANDROID_CLOEXEC_H
#include "../ClangTidy.h"
namespace clang {
namespace tidy {
namespace android {
/// \brief The base class for all close-on-exec checks in Android module.
/// To be specific, there are some functions that need the close-on-exec flag to
/// prevent the file descriptor leakage on fork+exec and this class provides
/// utilities to identify and fix these C functions.
class CloexecCheck : public ClangTidyCheck {
public:
CloexecCheck(StringRef Name, ClangTidyContext *Context)
: ClangTidyCheck(Name, Context) {}
protected:
void
registerMatchersImpl(ast_matchers::MatchFinder *Finder,
ast_matchers::internal::Matcher<FunctionDecl> Function);
/// Currently, we have three types of fixes.
///
/// Type1 is to insert the necessary macro flag in the flag argument. For
/// example, 'O_CLOEXEC' is required in function 'open()', so
/// \code
/// open(file, O_RDONLY);
/// \endcode
/// should be
/// \code
/// open(file, O_RDONLY | O_CLOEXE);
/// \endcode
///
/// \param [out] Result MatchResult from AST matcher.
/// \param MacroFlag The macro name of the flag.
/// \param ArgPos The 0-based position of the flag argument.
void insertMacroFlag(const ast_matchers::MatchFinder::MatchResult &Result,
StringRef MacroFlag, int ArgPos);
/// Type2 is to replace the API to another function that has required the
/// ability. For example:
/// \code
/// creat(path, mode);
/// \endcode
/// should be
/// \code
/// open(path, O_CREAT | O_WRONLY | O_TRUNC | O_CLOEXEC, mode)
/// \endcode
///
/// \param [out] Result MatchResult from AST matcher.
/// \param WarningMsg The warning message.
/// \param FixMsg The fix message.
void replaceFunc(const ast_matchers::MatchFinder::MatchResult &Result,
StringRef WarningMsg, StringRef FixMsg);
/// Type3 is also to add a flag to the corresponding argument, but this time,
/// the flag is some string and each char represents a mode rather than a
/// macro. For example, 'fopen' needs char 'e' in its mode argument string, so
/// \code
/// fopen(in_file, "r");
/// \endcode
/// should be
/// \code
/// fopen(in_file, "re");
/// \endcode
///
/// \param [out] Result MatchResult from AST matcher.
/// \param Mode The required mode char.
/// \param ArgPos The 0-based position of the flag argument.
void insertStringFlag(const ast_matchers::MatchFinder::MatchResult &Result,
const char Mode, const int ArgPos);
/// Helper function to get the spelling of a particular argument.
StringRef getSpellingArg(const ast_matchers::MatchFinder::MatchResult &Result,
int N) const;
/// Binding name of the FuncDecl of a function call.
static const char *FuncDeclBindingStr;
/// Binding name of the function call expression.
static const char *FuncBindingStr;
};
} // namespace android
} // namespace tidy
} // namespace clang
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ANDROID_CLOEXEC_H

View File

@@ -10,6 +10,7 @@
#include "CloexecCreatCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Lex/Lexer.h"
using namespace clang::ast_matchers;
@@ -20,22 +21,37 @@ namespace android {
void CloexecCreatCheck::registerMatchers(MatchFinder *Finder) {
auto CharPointerType = hasType(pointerType(pointee(isAnyCharacter())));
auto MODETType = hasType(namedDecl(hasName("mode_t")));
registerMatchersImpl(Finder,
functionDecl(isExternC(), returns(isInteger()),
hasName("creat"),
hasParameter(0, CharPointerType),
hasParameter(1, MODETType)));
Finder->addMatcher(
callExpr(callee(functionDecl(isExternC(), returns(isInteger()),
hasName("creat"),
hasParameter(0, CharPointerType),
hasParameter(1, MODETType))
.bind("funcDecl")))
.bind("creatFn"),
this);
}
void CloexecCreatCheck::check(const MatchFinder::MatchResult &Result) {
const auto *MatchedCall = Result.Nodes.getNodeAs<CallExpr>("creatFn");
const SourceManager &SM = *Result.SourceManager;
const std::string &ReplacementText =
(Twine("open (") + getSpellingArg(Result, 0) +
(Twine("open (") +
Lexer::getSourceText(CharSourceRange::getTokenRange(
MatchedCall->getArg(0)->getSourceRange()),
SM, Result.Context->getLangOpts()) +
", O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, " +
getSpellingArg(Result, 1) + ")")
Lexer::getSourceText(CharSourceRange::getTokenRange(
MatchedCall->getArg(1)->getSourceRange()),
SM, Result.Context->getLangOpts()) +
")")
.str();
replaceFunc(Result,
"prefer open() to creat() because open() allows O_CLOEXEC",
ReplacementText);
diag(MatchedCall->getLocStart(),
"prefer open() to creat() because open() allows O_CLOEXEC")
<< FixItHint::CreateReplacement(MatchedCall->getSourceRange(),
ReplacementText);
}
} // namespace android

View File

@@ -10,7 +10,7 @@
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ANDROID_CLOEXEC_CREAT_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ANDROID_CLOEXEC_CREAT_H
#include "CloexecCheck.h"
#include "../ClangTidy.h"
namespace clang {
namespace tidy {
@@ -20,10 +20,10 @@ namespace android {
/// Find the usage of creat() and redirect user to use open().
/// http://clang.llvm.org/extra/clang-tidy/checks/android-cloexec-creat.html
class CloexecCreatCheck : public CloexecCheck {
class CloexecCreatCheck : public ClangTidyCheck {
public:
CloexecCreatCheck(StringRef Name, ClangTidyContext *Context)
: CloexecCheck(Name, Context) {}
: ClangTidyCheck(Name, Context) {}
void registerMatchers(ast_matchers::MatchFinder *Finder) override;
void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
};

View File

@@ -1,38 +0,0 @@
//===--- CloexecDupCheck.cpp - clang-tidy----------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "CloexecDupCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
using namespace clang::ast_matchers;
namespace clang {
namespace tidy {
namespace android {
void CloexecDupCheck::registerMatchers(MatchFinder *Finder) {
registerMatchersImpl(Finder,
functionDecl(returns(isInteger()), hasName("dup"),
hasParameter(0, hasType(isInteger()))));
}
void CloexecDupCheck::check(const MatchFinder::MatchResult &Result) {
const std::string &ReplacementText =
(Twine("fcntl(") + getSpellingArg(Result, 0) + ", F_DUPFD_CLOEXEC)")
.str();
replaceFunc(Result,
"prefer fcntl() to dup() because fcntl() allows F_DUPFD_CLOEXEC",
ReplacementText);
}
} // namespace android
} // namespace tidy
} // namespace clang

View File

@@ -1,36 +0,0 @@
//===--- CloexecDupCheck.h - clang-tidy-------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ANDROID_CLOEXEC_DUP_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ANDROID_CLOEXEC_DUP_H
#include "CloexecCheck.h"
namespace clang {
namespace tidy {
namespace android {
/// dup() is better to be replaced by fcntl(), which has close-on-exec flag.
/// Find the usage of dup() and redirect user to use fcntl().
///
/// For the user-facing documentation see:
/// http://clang.llvm.org/extra/clang-tidy/checks/android-cloexec-dup.html
class CloexecDupCheck : public CloexecCheck {
public:
CloexecDupCheck(StringRef Name, ClangTidyContext *Context)
: CloexecCheck(Name, Context) {}
void registerMatchers(ast_matchers::MatchFinder *Finder) override;
void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
};
} // namespace android
} // namespace tidy
} // namespace clang
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ANDROID_CLOEXEC_DUP_H

View File

@@ -1,33 +0,0 @@
//===--- CloexecEpollCreate1Check.cpp - clang-tidy-------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "CloexecEpollCreate1Check.h"
#include "../utils/ASTUtils.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
using namespace clang::ast_matchers;
namespace clang {
namespace tidy {
namespace android {
void CloexecEpollCreate1Check::registerMatchers(MatchFinder *Finder) {
registerMatchersImpl(
Finder, functionDecl(returns(isInteger()), hasName("epoll_create1"),
hasParameter(0, hasType(isInteger()))));
}
void CloexecEpollCreate1Check::check(const MatchFinder::MatchResult &Result) {
insertMacroFlag(Result, /*MarcoFlag=*/"EPOLL_CLOEXEC", /*ArgPos=*/0);
}
} // namespace android
} // namespace tidy
} // namespace clang

View File

@@ -1,35 +0,0 @@
//===--- CloexecEpollCreate1Check.h - clang-tidy-----------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ANDROID_CLOEXEC_EPOLL_CREATE1_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ANDROID_CLOEXEC_EPOLL_CREATE1_H
#include "CloexecCheck.h"
namespace clang {
namespace tidy {
namespace android {
/// Finds code that uses epoll_create1() without using the EPOLL_CLOEXEC flag.
///
/// For the user-facing documentation see:
/// http://clang.llvm.org/extra/clang-tidy/checks/android-cloexec-epoll-create1.html
class CloexecEpollCreate1Check : public CloexecCheck {
public:
CloexecEpollCreate1Check(StringRef Name, ClangTidyContext *Context)
: CloexecCheck(Name, Context) {}
void registerMatchers(ast_matchers::MatchFinder *Finder) override;
void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
};
} // namespace android
} // namespace tidy
} // namespace clang
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ANDROID_CLOEXEC_EPOLL_CREATE1_H

View File

@@ -1,36 +0,0 @@
//===--- CloexecEpollCreateCheck.cpp - clang-tidy--------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "CloexecEpollCreateCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
using namespace clang::ast_matchers;
namespace clang {
namespace tidy {
namespace android {
void CloexecEpollCreateCheck::registerMatchers(MatchFinder *Finder) {
registerMatchersImpl(
Finder, functionDecl(returns(isInteger()), hasName("epoll_create"),
hasParameter(0, hasType(isInteger()))));
}
void CloexecEpollCreateCheck::check(const MatchFinder::MatchResult &Result) {
replaceFunc(Result,
"prefer epoll_create() to epoll_create1() "
"because epoll_create1() allows "
"EPOLL_CLOEXEC",
"epoll_create1(EPOLL_CLOEXEC)");
}
} // namespace android
} // namespace tidy
} // namespace clang

View File

@@ -1,35 +0,0 @@
//===--- CloexecEpollCreateCheck.h - clang-tidy------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ANDROID_CLOEXEC_EPOLL_CREATE_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ANDROID_CLOEXEC_EPOLL_CREATE_H
#include "CloexecCheck.h"
namespace clang {
namespace tidy {
namespace android {
/// epoll_create() is better to be replaced by epoll_create1().
///
/// For the user-facing documentation see:
/// http://clang.llvm.org/extra/clang-tidy/checks/android-cloexec-epoll-create.html
class CloexecEpollCreateCheck : public CloexecCheck {
public:
CloexecEpollCreateCheck(StringRef Name, ClangTidyContext *Context)
: CloexecCheck(Name, Context) {}
void registerMatchers(ast_matchers::MatchFinder *Finder) override;
void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
};
} // namespace android
} // namespace tidy
} // namespace clang
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ANDROID_CLOEXEC_EPOLL_CREATE_H

View File

@@ -18,17 +18,55 @@ namespace clang {
namespace tidy {
namespace android {
namespace {
static const char MODE = 'e';
// Build the replace text. If it's string constant, add 'e' directly in the end
// of the string. Else, add "e".
std::string BuildReplaceText(const Expr *Arg, const SourceManager &SM,
const LangOptions &LangOpts) {
if (Arg->getLocStart().isMacroID())
return (Lexer::getSourceText(
CharSourceRange::getTokenRange(Arg->getSourceRange()), SM,
LangOpts) +
" \"" + Twine(MODE) + "\"")
.str();
StringRef SR = cast<StringLiteral>(Arg->IgnoreParenCasts())->getString();
return ("\"" + SR + Twine(MODE) + "\"").str();
}
} // namespace
void CloexecFopenCheck::registerMatchers(MatchFinder *Finder) {
auto CharPointerType = hasType(pointerType(pointee(isAnyCharacter())));
registerMatchersImpl(Finder,
functionDecl(isExternC(), returns(asString("FILE *")),
hasName("fopen"),
hasParameter(0, CharPointerType),
hasParameter(1, CharPointerType)));
Finder->addMatcher(
callExpr(callee(functionDecl(isExternC(), returns(asString("FILE *")),
hasName("fopen"),
hasParameter(0, CharPointerType),
hasParameter(1, CharPointerType))
.bind("funcDecl")))
.bind("fopenFn"),
this);
}
void CloexecFopenCheck::check(const MatchFinder::MatchResult &Result) {
insertStringFlag(Result, /*Mode=*/'e', /*ArgPos=*/1);
const auto *MatchedCall = Result.Nodes.getNodeAs<CallExpr>("fopenFn");
const auto *FD = Result.Nodes.getNodeAs<FunctionDecl>("funcDecl");
const Expr *ModeArg = MatchedCall->getArg(1);
// Check if the 'e' may be in the mode string.
const auto *ModeStr = dyn_cast<StringLiteral>(ModeArg->IgnoreParenCasts());
if (!ModeStr || (ModeStr->getString().find(MODE) != StringRef::npos))
return;
const std::string &ReplacementText = BuildReplaceText(
ModeArg, *Result.SourceManager, Result.Context->getLangOpts());
diag(ModeArg->getLocStart(), "use %0 mode 'e' to set O_CLOEXEC")
<< FD
<< FixItHint::CreateReplacement(ModeArg->getSourceRange(),
ReplacementText);
}
} // namespace android

View File

@@ -10,7 +10,7 @@
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ANDROID_CLOEXEC_FOPEN_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ANDROID_CLOEXEC_FOPEN_H
#include "CloexecCheck.h"
#include "../ClangTidy.h"
namespace clang {
namespace tidy {
@@ -23,10 +23,10 @@ namespace android {
/// constant propagation.
///
/// http://clang.llvm.org/extra/clang-tidy/checks/android-cloexec-fopen.html
class CloexecFopenCheck : public CloexecCheck {
class CloexecFopenCheck : public ClangTidyCheck {
public:
CloexecFopenCheck(StringRef Name, ClangTidyContext *Context)
: CloexecCheck(Name, Context) {}
: ClangTidyCheck(Name, Context) {}
void registerMatchers(ast_matchers::MatchFinder *Finder) override;
void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
};

View File

@@ -1,33 +0,0 @@
//===--- CloexecInotifyInit1Check.cpp - clang-tidy-------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "CloexecInotifyInit1Check.h"
#include "../utils/ASTUtils.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
using namespace clang::ast_matchers;
namespace clang {
namespace tidy {
namespace android {
void CloexecInotifyInit1Check::registerMatchers(MatchFinder *Finder) {
registerMatchersImpl(
Finder, functionDecl(returns(isInteger()), hasName("inotify_init1"),
hasParameter(0, hasType(isInteger()))));
}
void CloexecInotifyInit1Check::check(const MatchFinder::MatchResult &Result) {
insertMacroFlag(Result, /*MarcoFlag=*/"IN_CLOEXEC", /*ArgPos=*/0);
}
} // namespace android
} // namespace tidy
} // namespace clang

View File

@@ -1,35 +0,0 @@
//===--- CloexecInotifyInit1Check.h - clang-tidy-----------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ANDROID_CLOEXEC_INOTIFY_INIT1_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ANDROID_CLOEXEC_INOTIFY_INIT1_H
#include "CloexecCheck.h"
namespace clang {
namespace tidy {
namespace android {
/// Finds code that uses inotify_init1() without using the IN_CLOEXEC flag.
///
/// For the user-facing documentation see:
/// http://clang.llvm.org/extra/clang-tidy/checks/android-cloexec-inotify-init1.html
class CloexecInotifyInit1Check : public CloexecCheck {
public:
CloexecInotifyInit1Check(StringRef Name, ClangTidyContext *Context)
: CloexecCheck(Name, Context) {}
void registerMatchers(ast_matchers::MatchFinder *Finder) override;
void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
};
} // namespace android
} // namespace tidy
} // namespace clang
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ANDROID_CLOEXEC_INOTIFY_INIT1_H

View File

@@ -1,34 +0,0 @@
//===--- CloexecInotifyInitCheck.cpp - clang-tidy--------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "CloexecInotifyInitCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
using namespace clang::ast_matchers;
namespace clang {
namespace tidy {
namespace android {
void CloexecInotifyInitCheck::registerMatchers(MatchFinder *Finder) {
registerMatchersImpl(
Finder, functionDecl(returns(isInteger()), hasName("inotify_init")));
}
void CloexecInotifyInitCheck::check(const MatchFinder::MatchResult &Result) {
replaceFunc(Result, /*WarningMsg=*/
"prefer inotify_init() to inotify_init1() "
"because inotify_init1() allows IN_CLOEXEC",
/*FixMsg=*/"inotify_init1(IN_CLOEXEC)");
}
} // namespace android
} // namespace tidy
} // namespace clang

View File

@@ -1,35 +0,0 @@
//===--- CloexecInotifyInitCheck.h - clang-tidy------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ANDROID_CLOEXEC_INOTIFY_INIT_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ANDROID_CLOEXEC_INOTIFY_INIT_H
#include "CloexecCheck.h"
namespace clang {
namespace tidy {
namespace android {
/// inotify_init() is better to be replaced by inotify_init1().
///
/// For the user-facing documentation see:
/// http://clang.llvm.org/extra/clang-tidy/checks/android-cloexec-inotify-init.html
class CloexecInotifyInitCheck : public CloexecCheck {
public:
CloexecInotifyInitCheck(StringRef Name, ClangTidyContext *Context)
: CloexecCheck(Name, Context) {}
void registerMatchers(ast_matchers::MatchFinder *Finder) override;
void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
};
} // namespace android
} // namespace tidy
} // namespace clang
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ANDROID_CLOEXEC_INOTIFY_INIT_H

View File

@@ -1,32 +0,0 @@
//===--- CloexecMemfdCreateCheck.cpp - clang-tidy--------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "CloexecMemfdCreateCheck.h"
using namespace clang::ast_matchers;
namespace clang {
namespace tidy {
namespace android {
void CloexecMemfdCreateCheck::registerMatchers(MatchFinder *Finder) {
auto CharPointerType = hasType(pointerType(pointee(isAnyCharacter())));
registerMatchersImpl(
Finder, functionDecl(returns(isInteger()), hasName("memfd_create"),
hasParameter(0, CharPointerType),
hasParameter(1, hasType(isInteger()))));
}
void CloexecMemfdCreateCheck::check(const MatchFinder::MatchResult &Result) {
insertMacroFlag(Result, "MFD_CLOEXEC", /*ArgPos=*/1);
}
} // namespace android
} // namespace tidy
} // namespace clang

View File

@@ -1,35 +0,0 @@
//===--- CloexecMemfdCreateCheck.h - clang-tidy-----------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ANDROID_CLOEXEC_MEMFD_CREATE_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ANDROID_CLOEXEC_MEMFD_CREATE_H
#include "CloexecCheck.h"
namespace clang {
namespace tidy {
namespace android {
/// Finds code that uses memfd_create() without using the MFD_CLOEXEC flag.
///
/// For the user-facing documentation see:
/// http://clang.llvm.org/extra/clang-tidy/checks/android-cloexec-memfd-create.html
class CloexecMemfdCreateCheck : public CloexecCheck {
public:
CloexecMemfdCreateCheck(StringRef Name, ClangTidyContext *Context)
: CloexecCheck(Name, Context) {}
void registerMatchers(ast_matchers::MatchFinder *Finder) override;
void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
};
} // namespace android
} // namespace tidy
} // namespace clang
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ANDROID_CLOEXEC_MEMFD_CREATE_H

View File

@@ -8,8 +8,10 @@
//===----------------------------------------------------------------------===//
#include "CloexecOpenCheck.h"
#include "../utils/ASTUtils.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Lex/Lexer.h"
using namespace clang::ast_matchers;
@@ -17,26 +19,54 @@ namespace clang {
namespace tidy {
namespace android {
static constexpr const char *O_CLOEXEC = "O_CLOEXEC";
void CloexecOpenCheck::registerMatchers(MatchFinder *Finder) {
auto CharPointerType = hasType(pointerType(pointee(isAnyCharacter())));
registerMatchersImpl(Finder,
functionDecl(isExternC(), returns(isInteger()),
hasAnyName("open", "open64"),
hasParameter(0, CharPointerType),
hasParameter(1, hasType(isInteger()))));
registerMatchersImpl(Finder,
functionDecl(isExternC(), returns(isInteger()),
hasName("openat"),
hasParameter(0, hasType(isInteger())),
hasParameter(1, CharPointerType),
hasParameter(2, hasType(isInteger()))));
Finder->addMatcher(
callExpr(callee(functionDecl(isExternC(), returns(isInteger()),
hasAnyName("open", "open64"),
hasParameter(0, CharPointerType),
hasParameter(1, hasType(isInteger())))
.bind("funcDecl")))
.bind("openFn"),
this);
Finder->addMatcher(
callExpr(callee(functionDecl(isExternC(), returns(isInteger()),
hasName("openat"),
hasParameter(0, hasType(isInteger())),
hasParameter(1, CharPointerType),
hasParameter(2, hasType(isInteger())))
.bind("funcDecl")))
.bind("openatFn"),
this);
}
void CloexecOpenCheck::check(const MatchFinder::MatchResult &Result) {
const auto *FD = Result.Nodes.getNodeAs<FunctionDecl>(FuncDeclBindingStr);
assert(FD->param_size() > 1);
int ArgPos = (FD->param_size() > 2) ? 2 : 1;
insertMacroFlag(Result, /*MarcoFlag=*/"O_CLOEXEC", ArgPos);
const Expr *FlagArg = nullptr;
if (const auto *OpenFnCall = Result.Nodes.getNodeAs<CallExpr>("openFn"))
FlagArg = OpenFnCall->getArg(1);
else if (const auto *OpenFnCall =
Result.Nodes.getNodeAs<CallExpr>("openatFn"))
FlagArg = OpenFnCall->getArg(2);
assert(FlagArg);
const auto *FD = Result.Nodes.getNodeAs<FunctionDecl>("funcDecl");
// Check the required flag.
SourceManager &SM = *Result.SourceManager;
if (utils::exprHasBitFlagWithSpelling(FlagArg->IgnoreParenCasts(), SM,
Result.Context->getLangOpts(), O_CLOEXEC))
return;
SourceLocation EndLoc =
Lexer::getLocForEndOfToken(SM.getFileLoc(FlagArg->getLocEnd()), 0, SM,
Result.Context->getLangOpts());
diag(EndLoc, "%0 should use %1 where possible")
<< FD << O_CLOEXEC
<< FixItHint::CreateInsertion(EndLoc, (Twine(" | ") + O_CLOEXEC).str());
}
} // namespace android

View File

@@ -10,7 +10,7 @@
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ANDROID_CLOEXEC_OPEN_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ANDROID_CLOEXEC_OPEN_H
#include "CloexecCheck.h"
#include "../ClangTidy.h"
namespace clang {
namespace tidy {
@@ -25,10 +25,10 @@ namespace android {
///
/// Only the symbolic 'O_CLOEXEC' macro definition is checked, not the concrete
/// value.
class CloexecOpenCheck : public CloexecCheck {
class CloexecOpenCheck : public ClangTidyCheck {
public:
CloexecOpenCheck(StringRef Name, ClangTidyContext *Context)
: CloexecCheck(Name, Context) {}
: ClangTidyCheck(Name, Context) {}
void registerMatchers(ast_matchers::MatchFinder *Finder) override;
void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
};

View File

@@ -8,6 +8,7 @@
//===----------------------------------------------------------------------===//
#include "CloexecSocketCheck.h"
#include "../utils/ASTUtils.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
@@ -17,17 +18,38 @@ namespace clang {
namespace tidy {
namespace android {
static constexpr const char *SOCK_CLOEXEC = "SOCK_CLOEXEC";
void CloexecSocketCheck::registerMatchers(MatchFinder *Finder) {
registerMatchersImpl(Finder,
functionDecl(isExternC(), returns(isInteger()),
hasName("socket"),
hasParameter(0, hasType(isInteger())),
hasParameter(1, hasType(isInteger())),
hasParameter(2, hasType(isInteger()))));
Finder->addMatcher(
callExpr(callee(functionDecl(isExternC(), returns(isInteger()),
hasName("socket"),
hasParameter(0, hasType(isInteger())),
hasParameter(1, hasType(isInteger())),
hasParameter(2, hasType(isInteger())))
.bind("funcDecl")))
.bind("socketFn"),
this);
}
void CloexecSocketCheck::check(const MatchFinder::MatchResult &Result) {
insertMacroFlag(Result, /*MarcoFlag=*/"SOCK_CLOEXEC", /*ArgPos=*/1);
const auto *MatchedCall = Result.Nodes.getNodeAs<CallExpr>("socketFn");
const auto *FD = Result.Nodes.getNodeAs<FunctionDecl>("funcDecl");
const Expr *FlagArg = MatchedCall->getArg(1);
SourceManager &SM = *Result.SourceManager;
if (utils::exprHasBitFlagWithSpelling(FlagArg->IgnoreParenCasts(), SM,
Result.Context->getLangOpts(), SOCK_CLOEXEC))
return;
SourceLocation EndLoc =
Lexer::getLocForEndOfToken(SM.getFileLoc(FlagArg->getLocEnd()), 0, SM,
Result.Context->getLangOpts());
diag(EndLoc, "%0 should use %1 where possible")
<< FD << SOCK_CLOEXEC
<< FixItHint::CreateInsertion(EndLoc,
(Twine(" | ") + SOCK_CLOEXEC).str());
}
} // namespace android

View File

@@ -10,7 +10,7 @@
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ANDROID_CLOEXEC_SOCKET_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ANDROID_CLOEXEC_SOCKET_H
#include "CloexecCheck.h"
#include "../ClangTidy.h"
namespace clang {
namespace tidy {
@@ -20,10 +20,10 @@ namespace android {
///
/// For the user-facing documentation see:
/// http://clang.llvm.org/extra/clang-tidy/checks/android-cloexec-socket.html
class CloexecSocketCheck : public CloexecCheck {
class CloexecSocketCheck : public ClangTidyCheck {
public:
CloexecSocketCheck(StringRef Name, ClangTidyContext *Context)
: CloexecCheck(Name, Context) {}
: ClangTidyCheck(Name, Context) {}
void registerMatchers(ast_matchers::MatchFinder *Finder) override;
void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
};

View File

@@ -10,23 +10,8 @@
#include "../ClangTidy.h"
#include "../ClangTidyModule.h"
#include "../ClangTidyModuleRegistry.h"
#include "ArgumentCommentCheck.h"
#include "AssertSideEffectCheck.h"
#include "BoolPointerImplicitConversionCheck.h"
#include "CopyConstructorInitCheck.h"
#include "DanglingHandleCheck.h"
#include "FoldInitTypeCheck.h"
#include "ForwardDeclarationNamespaceCheck.h"
#include "InaccurateEraseCheck.h"
#include "IntegerDivisionCheck.h"
#include "MisplacedOperatorInStrlenInAllocCheck.h"
#include "MoveForwardingReferenceCheck.h"
#include "MultipleStatementMacroCheck.h"
#include "StringConstructorCheck.h"
#include "SuspiciousMemsetUsageCheck.h"
#include "UndefinedMemoryManipulationCheck.h"
#include "UseAfterMoveCheck.h"
#include "VirtualNearMissCheck.h"
namespace clang {
namespace tidy {
@@ -35,40 +20,10 @@ namespace bugprone {
class BugproneModule : public ClangTidyModule {
public:
void addCheckFactories(ClangTidyCheckFactories &CheckFactories) override {
CheckFactories.registerCheck<ArgumentCommentCheck>(
"bugprone-argument-comment");
CheckFactories.registerCheck<AssertSideEffectCheck>(
"bugprone-assert-side-effect");
CheckFactories.registerCheck<BoolPointerImplicitConversionCheck>(
"bugprone-bool-pointer-implicit-conversion");
CheckFactories.registerCheck<CopyConstructorInitCheck>(
"bugprone-copy-constructor-init");
CheckFactories.registerCheck<DanglingHandleCheck>(
"bugprone-dangling-handle");
CheckFactories.registerCheck<FoldInitTypeCheck>(
"bugprone-fold-init-type");
CheckFactories.registerCheck<ForwardDeclarationNamespaceCheck>(
"bugprone-forward-declaration-namespace");
CheckFactories.registerCheck<InaccurateEraseCheck>(
"bugprone-inaccurate-erase");
CheckFactories.registerCheck<IntegerDivisionCheck>(
"bugprone-integer-division");
CheckFactories.registerCheck<MisplacedOperatorInStrlenInAllocCheck>(
"bugprone-misplaced-operator-in-strlen-in-alloc");
CheckFactories.registerCheck<MoveForwardingReferenceCheck>(
"bugprone-move-forwarding-reference");
CheckFactories.registerCheck<MultipleStatementMacroCheck>(
"bugprone-multiple-statement-macro");
CheckFactories.registerCheck<StringConstructorCheck>(
"bugprone-string-constructor");
CheckFactories.registerCheck<SuspiciousMemsetUsageCheck>(
"bugprone-suspicious-memset-usage");
CheckFactories.registerCheck<UndefinedMemoryManipulationCheck>(
"bugprone-undefined-memory-manipulation");
CheckFactories.registerCheck<UseAfterMoveCheck>(
"bugprone-use-after-move");
CheckFactories.registerCheck<VirtualNearMissCheck>(
"bugprone-virtual-near-miss");
}
};

View File

@@ -1,24 +1,9 @@
set(LLVM_LINK_COMPONENTS support)
add_clang_library(clangTidyBugproneModule
ArgumentCommentCheck.cpp
AssertSideEffectCheck.cpp
BoolPointerImplicitConversionCheck.cpp
BugproneTidyModule.cpp
CopyConstructorInitCheck.cpp
DanglingHandleCheck.cpp
FoldInitTypeCheck.cpp
ForwardDeclarationNamespaceCheck.cpp
InaccurateEraseCheck.cpp
IntegerDivisionCheck.cpp
MisplacedOperatorInStrlenInAllocCheck.cpp
MoveForwardingReferenceCheck.cpp
MultipleStatementMacroCheck.cpp
StringConstructorCheck.cpp
SuspiciousMemsetUsageCheck.cpp
UndefinedMemoryManipulationCheck.cpp
UseAfterMoveCheck.cpp
VirtualNearMissCheck.cpp
LINK_LIBS
clangAnalysis

View File

@@ -1,121 +0,0 @@
//===--- CopyConstructorInitCheck.cpp - clang-tidy-------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "CopyConstructorInitCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Lex/Lexer.h"
using namespace clang::ast_matchers;
namespace clang {
namespace tidy {
namespace bugprone {
void CopyConstructorInitCheck::registerMatchers(MatchFinder *Finder) {
if (!getLangOpts().CPlusPlus)
return;
// In the future this might be extended to move constructors?
Finder->addMatcher(
cxxConstructorDecl(
isCopyConstructor(),
hasAnyConstructorInitializer(cxxCtorInitializer(
isBaseInitializer(),
withInitializer(cxxConstructExpr(hasDeclaration(
cxxConstructorDecl(isDefaultConstructor())))))),
unless(isInstantiated()))
.bind("ctor"),
this);
}
void CopyConstructorInitCheck::check(const MatchFinder::MatchResult &Result) {
const auto *Ctor = Result.Nodes.getNodeAs<CXXConstructorDecl>("ctor");
std::string ParamName = Ctor->getParamDecl(0)->getNameAsString();
// We want only one warning (and FixIt) for each ctor.
std::string FixItInitList;
bool HasRelevantBaseInit = false;
bool ShouldNotDoFixit = false;
bool HasWrittenInitializer = false;
SmallVector<FixItHint, 2> SafeFixIts;
for (const auto *Init : Ctor->inits()) {
bool CtorInitIsWritten = Init->isWritten();
HasWrittenInitializer = HasWrittenInitializer || CtorInitIsWritten;
if (!Init->isBaseInitializer())
continue;
const Type *BaseType = Init->getBaseClass();
// Do not do fixits if there is a type alias involved or one of the bases
// are explicitly initialized. In the latter case we not do fixits to avoid
// -Wreorder warnings.
if (const auto *TempSpecTy = dyn_cast<TemplateSpecializationType>(BaseType))
ShouldNotDoFixit = ShouldNotDoFixit || TempSpecTy->isTypeAlias();
ShouldNotDoFixit = ShouldNotDoFixit || isa<TypedefType>(BaseType);
ShouldNotDoFixit = ShouldNotDoFixit || CtorInitIsWritten;
const CXXRecordDecl *BaseClass =
BaseType->getAsCXXRecordDecl()->getDefinition();
if (BaseClass->field_empty() &&
BaseClass->forallBases(
[](const CXXRecordDecl *Class) { return Class->field_empty(); }))
continue;
bool NonCopyableBase = false;
for (const auto *Ctor : BaseClass->ctors()) {
if (Ctor->isCopyConstructor() &&
(Ctor->getAccess() == AS_private || Ctor->isDeleted())) {
NonCopyableBase = true;
break;
}
}
if (NonCopyableBase)
continue;
const auto *CExpr = dyn_cast<CXXConstructExpr>(Init->getInit());
if (!CExpr || !CExpr->getConstructor()->isDefaultConstructor())
continue;
HasRelevantBaseInit = true;
if (CtorInitIsWritten) {
if (!ParamName.empty())
SafeFixIts.push_back(
FixItHint::CreateInsertion(CExpr->getLocEnd(), ParamName));
} else {
if (Init->getSourceLocation().isMacroID() ||
Ctor->getLocation().isMacroID() || ShouldNotDoFixit)
break;
FixItInitList += BaseClass->getNameAsString();
FixItInitList += "(" + ParamName + "), ";
}
}
if (!HasRelevantBaseInit)
return;
auto Diag = diag(Ctor->getLocation(),
"calling a base constructor other than the copy constructor")
<< SafeFixIts;
if (FixItInitList.empty() || ParamName.empty() || ShouldNotDoFixit)
return;
std::string FixItMsg{FixItInitList.substr(0, FixItInitList.size() - 2)};
SourceLocation FixItLoc;
// There is no initialization list in this constructor.
if (!HasWrittenInitializer) {
FixItLoc = Ctor->getBody()->getLocStart();
FixItMsg = " : " + FixItMsg;
} else {
// We apply the missing ctors at the beginning of the initialization list.
FixItLoc = (*Ctor->init_begin())->getSourceLocation();
FixItMsg += ',';
}
FixItMsg += ' ';
Diag << FixItHint::CreateInsertion(FixItLoc, FixItMsg);
} // namespace misc
} // namespace misc
} // namespace tidy
} // namespace clang

View File

@@ -1,36 +0,0 @@
//===--- CopyConstructorInitCheck.h - clang-tidy--------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_COPY_CONSTRUCTOR_INIT_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_COPY_CONSTRUCTOR_INIT_H
#include "../ClangTidy.h"
namespace clang {
namespace tidy {
namespace bugprone {
/// Finds copy constructors where the ctor don't call the copy constructor of
/// the base class.
///
/// For the user-facing documentation see:
/// http://clang.llvm.org/extra/clang-tidy/checks/misc-copy-constructor-init.html
class CopyConstructorInitCheck : public ClangTidyCheck {
public:
CopyConstructorInitCheck(StringRef Name, ClangTidyContext *Context)
: ClangTidyCheck(Name, Context) {}
void registerMatchers(ast_matchers::MatchFinder *Finder) override;
void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
};
} // namespace misc
} // namespace tidy
} // namespace clang
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_COPY_CONSTRUCTOR_INIT_H

View File

@@ -1,57 +0,0 @@
//===--- IntegerDivisionCheck.cpp - clang-tidy-----------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "IntegerDivisionCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
using namespace clang::ast_matchers;
namespace clang {
namespace tidy {
namespace bugprone {
void IntegerDivisionCheck::registerMatchers(MatchFinder *Finder) {
const auto IntType = hasType(isInteger());
const auto BinaryOperators = binaryOperator(anyOf(
hasOperatorName("%"), hasOperatorName("<<"), hasOperatorName(">>"),
hasOperatorName("<<"), hasOperatorName("^"), hasOperatorName("|"),
hasOperatorName("&"), hasOperatorName("||"), hasOperatorName("&&"),
hasOperatorName("<"), hasOperatorName(">"), hasOperatorName("<="),
hasOperatorName(">="), hasOperatorName("=="), hasOperatorName("!=")));
const auto UnaryOperators =
unaryOperator(anyOf(hasOperatorName("~"), hasOperatorName("!")));
const auto Exceptions =
anyOf(BinaryOperators, conditionalOperator(), binaryConditionalOperator(),
callExpr(IntType), explicitCastExpr(IntType), UnaryOperators);
Finder->addMatcher(
binaryOperator(
hasOperatorName("/"), hasLHS(expr(IntType)), hasRHS(expr(IntType)),
hasAncestor(
castExpr(hasCastKind(CK_IntegralToFloating)).bind("FloatCast")),
unless(hasAncestor(
expr(Exceptions,
hasAncestor(castExpr(equalsBoundNode("FloatCast")))))))
.bind("IntDiv"),
this);
}
void IntegerDivisionCheck::check(const MatchFinder::MatchResult &Result) {
const auto *IntDiv = Result.Nodes.getNodeAs<BinaryOperator>("IntDiv");
diag(IntDiv->getLocStart(), "result of integer division used in a floating "
"point context; possible loss of precision");
}
} // namespace bugprone
} // namespace tidy
} // namespace clang

View File

@@ -1,36 +0,0 @@
//===--- IntegerDivisionCheck.h - clang-tidy---------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_INTEGER_DIVISION_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_INTEGER_DIVISION_H
#include "../ClangTidy.h"
namespace clang {
namespace tidy {
namespace bugprone {
/// Finds cases where integer division in a floating point context is likely to
/// cause unintended loss of precision.
///
/// For the user-facing documentation see:
/// http://clang.llvm.org/extra/clang-tidy/checks/bugprone-integer-division.html
class IntegerDivisionCheck : public ClangTidyCheck {
public:
IntegerDivisionCheck(StringRef Name, ClangTidyContext *Context)
: ClangTidyCheck(Name, Context) {}
void registerMatchers(ast_matchers::MatchFinder *Finder) override;
void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
};
} // namespace bugprone
} // namespace tidy
} // namespace clang
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_INTEGER_DIVISION_H

View File

@@ -1,112 +0,0 @@
//===--- MisplacedOperatorInStrlenInAllocCheck.cpp - clang-tidy------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "MisplacedOperatorInStrlenInAllocCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
using namespace clang::ast_matchers;
namespace clang {
namespace tidy {
namespace bugprone {
void MisplacedOperatorInStrlenInAllocCheck::registerMatchers(
MatchFinder *Finder) {
const auto StrLenFunc = functionDecl(anyOf(
hasName("::strlen"), hasName("::std::strlen"), hasName("::strnlen"),
hasName("::std::strnlen"), hasName("::strnlen_s"),
hasName("::std::strnlen_s"), hasName("::wcslen"),
hasName("::std::wcslen"), hasName("::wcsnlen"), hasName("::std::wcsnlen"),
hasName("::wcsnlen_s"), hasName("std::wcsnlen_s")));
const auto BadUse =
callExpr(callee(StrLenFunc),
hasAnyArgument(ignoringImpCasts(
binaryOperator(allOf(hasOperatorName("+"),
hasRHS(ignoringParenImpCasts(
integerLiteral(equals(1))))))
.bind("BinOp"))))
.bind("StrLen");
const auto BadArg = anyOf(
allOf(hasDescendant(BadUse),
unless(binaryOperator(allOf(
hasOperatorName("+"), hasLHS(BadUse),
hasRHS(ignoringParenImpCasts(integerLiteral(equals(1)))))))),
BadUse);
const auto Alloc0Func =
functionDecl(anyOf(hasName("::malloc"), hasName("std::malloc"),
hasName("::alloca"), hasName("std::alloca")));
const auto Alloc1Func =
functionDecl(anyOf(hasName("::calloc"), hasName("std::calloc"),
hasName("::realloc"), hasName("std::realloc")));
const auto Alloc0FuncPtr =
varDecl(hasType(isConstQualified()),
hasInitializer(ignoringParenImpCasts(
declRefExpr(hasDeclaration(Alloc0Func)))));
const auto Alloc1FuncPtr =
varDecl(hasType(isConstQualified()),
hasInitializer(ignoringParenImpCasts(
declRefExpr(hasDeclaration(Alloc1Func)))));
Finder->addMatcher(callExpr(callee(decl(anyOf(Alloc0Func, Alloc0FuncPtr))),
hasArgument(0, BadArg))
.bind("Alloc"),
this);
Finder->addMatcher(callExpr(callee(decl(anyOf(Alloc1Func, Alloc1FuncPtr))),
hasArgument(1, BadArg))
.bind("Alloc"),
this);
Finder->addMatcher(
cxxNewExpr(isArray(), hasArraySize(BadArg)).bind("Alloc"), this);
}
void MisplacedOperatorInStrlenInAllocCheck::check(
const MatchFinder::MatchResult &Result) {
const Expr *Alloc = Result.Nodes.getNodeAs<CallExpr>("Alloc");
if (!Alloc)
Alloc = Result.Nodes.getNodeAs<CXXNewExpr>("Alloc");
assert(Alloc && "Matched node bound by 'Alloc' shoud be either 'CallExpr'"
" or 'CXXNewExpr'");
const auto *StrLen = Result.Nodes.getNodeAs<CallExpr>("StrLen");
const auto *BinOp = Result.Nodes.getNodeAs<BinaryOperator>("BinOp");
const StringRef StrLenText = Lexer::getSourceText(
CharSourceRange::getTokenRange(StrLen->getSourceRange()),
*Result.SourceManager, getLangOpts());
const StringRef Arg0Text = Lexer::getSourceText(
CharSourceRange::getTokenRange(StrLen->getArg(0)->getSourceRange()),
*Result.SourceManager, getLangOpts());
const StringRef StrLenBegin = StrLenText.substr(0, StrLenText.find(Arg0Text));
const StringRef StrLenEnd = StrLenText.substr(
StrLenText.find(Arg0Text) + Arg0Text.size(), StrLenText.size());
const StringRef LHSText = Lexer::getSourceText(
CharSourceRange::getTokenRange(BinOp->getLHS()->getSourceRange()),
*Result.SourceManager, getLangOpts());
const StringRef RHSText = Lexer::getSourceText(
CharSourceRange::getTokenRange(BinOp->getRHS()->getSourceRange()),
*Result.SourceManager, getLangOpts());
auto Hint = FixItHint::CreateReplacement(
StrLen->getSourceRange(),
(StrLenBegin + LHSText + StrLenEnd + " + " + RHSText).str());
diag(Alloc->getLocStart(),
"addition operator is applied to the argument of %0 instead of its "
"result") << StrLen->getDirectCallee()->getName() << Hint;
}
} // namespace bugprone
} // namespace tidy
} // namespace clang

View File

@@ -1,37 +0,0 @@
//===--- MisplacedOperatorInStrlenInAllocCheck.h - clang-tidy----*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_MISPLACED_OPERATOR_IN_STRLEN_IN_ALLOC_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_MISPLACED_OPERATOR_IN_STRLEN_IN_ALLOC_H
#include "../ClangTidy.h"
namespace clang {
namespace tidy {
namespace bugprone {
/// Finds cases where ``1`` is added to the string in the argument to a function
/// in the ``strlen()`` family instead of the result and value is used as an
/// argument to a memory allocation function.
///
/// For the user-facing documentation see:
/// http://clang.llvm.org/extra/clang-tidy/checks/bugprone-misplaced-operator-in-strlen-in-alloc.html
class MisplacedOperatorInStrlenInAllocCheck : public ClangTidyCheck {
public:
MisplacedOperatorInStrlenInAllocCheck(StringRef Name, ClangTidyContext *Context)
: ClangTidyCheck(Name, Context) {}
void registerMatchers(ast_matchers::MatchFinder *Finder) override;
void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
};
} // namespace bugprone
} // namespace tidy
} // namespace clang
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_MISPLACED_OPERATOR_IN_STRLEN_IN_ALLOC_H

View File

@@ -1,37 +0,0 @@
//===--- MultipleStatementMacroCheck.h - clang-tidy--------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_MULTIPLE_STATEMENT_MACRO_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_MULTIPLE_STATEMENT_MACRO_H
#include "../ClangTidy.h"
namespace clang {
namespace tidy {
namespace bugprone {
/// Detect multiple statement macros that are used in unbraced conditionals.
/// Only the first statement of the macro will be inside the conditional and the
/// other ones will be executed unconditionally.
///
/// For the user-facing documentation see:
/// http://clang.llvm.org/extra/clang-tidy/checks/bugprone-multiple-statement-macro.html
class MultipleStatementMacroCheck : public ClangTidyCheck {
public:
MultipleStatementMacroCheck(StringRef Name, ClangTidyContext *Context)
: ClangTidyCheck(Name, Context) {}
void registerMatchers(ast_matchers::MatchFinder *Finder) override;
void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
};
} // namespace bugprone
} // namespace tidy
} // namespace clang
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_MULTIPLE_STATEMENT_MACRO_H

View File

@@ -1,39 +0,0 @@
//===--- StringConstructorCheck.h - clang-tidy-------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_STRING_CONSTRUCTOR_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_STRING_CONSTRUCTOR_H
#include "../ClangTidy.h"
namespace clang {
namespace tidy {
namespace bugprone {
/// Finds suspicious string constructor and check their parameters.
///
/// For the user-facing documentation see:
/// http://clang.llvm.org/extra/clang-tidy/checks/bugprone-string-constructor.html
class StringConstructorCheck : public ClangTidyCheck {
public:
StringConstructorCheck(StringRef Name, ClangTidyContext *Context);
void storeOptions(ClangTidyOptions::OptionMap &Opts) override;
void registerMatchers(ast_matchers::MatchFinder *Finder) override;
void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
private:
const bool WarnOnLargeLength;
const unsigned int LargeLengthThreshold;
};
} // namespace bugprone
} // namespace tidy
} // namespace clang
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_STRING_CONSTRUCTOR_H

View File

@@ -19,15 +19,13 @@ namespace bugprone {
namespace {
AST_MATCHER(CXXRecordDecl, isNotTriviallyCopyable) {
// For incomplete types, assume they are TriviallyCopyable.
return Node.hasDefinition() ? !Node.isTriviallyCopyable() : false;
return !Node.isTriviallyCopyable();
}
} // namespace
void UndefinedMemoryManipulationCheck::registerMatchers(MatchFinder *Finder) {
const auto NotTriviallyCopyableObject =
hasType(ast_matchers::hasCanonicalType(
pointsTo(cxxRecordDecl(isNotTriviallyCopyable()))));
hasType(pointsTo(cxxRecordDecl(isNotTriviallyCopyable())));
// Check whether destination object is not TriviallyCopyable.
// Applicable to all three memory manipulation functions.
@@ -48,21 +46,13 @@ void UndefinedMemoryManipulationCheck::registerMatchers(MatchFinder *Finder) {
void UndefinedMemoryManipulationCheck::check(
const MatchFinder::MatchResult &Result) {
if (const auto *Call = Result.Nodes.getNodeAs<CallExpr>("dest")) {
QualType DestType = Call->getArg(0)->IgnoreImplicit()->getType();
if (!DestType->getPointeeType().isNull())
DestType = DestType->getPointeeType();
diag(Call->getLocStart(), "undefined behavior, destination object type %0 "
"is not TriviallyCopyable")
<< DestType;
if (const auto *Destination = Result.Nodes.getNodeAs<CallExpr>("dest")) {
diag(Destination->getLocStart(), "undefined behavior, destination "
"object is not TriviallyCopyable");
}
if (const auto *Call = Result.Nodes.getNodeAs<CallExpr>("src")) {
QualType SourceType = Call->getArg(1)->IgnoreImplicit()->getType();
if (!SourceType->getPointeeType().isNull())
SourceType = SourceType->getPointeeType();
diag(Call->getLocStart(),
"undefined behavior, source object type %0 is not TriviallyCopyable")
<< SourceType;
if (const auto *Source = Result.Nodes.getNodeAs<CallExpr>("src")) {
diag(Source->getLocStart(), "undefined behavior, source object is not "
"TriviallyCopyable");
}
}

View File

@@ -1,36 +0,0 @@
//===--- UseAfterMoveCheck.h - clang-tidy ---------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_USEAFTERMOVECHECK_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_USEAFTERMOVECHECK_H
#include "../ClangTidy.h"
namespace clang {
namespace tidy {
namespace bugprone {
/// The check warns if an object is used after it has been moved, without an
/// intervening reinitialization.
///
/// For details, see the user-facing documentation:
/// http://clang.llvm.org/extra/clang-tidy/checks/bugprone-use-after-move.html
class UseAfterMoveCheck : public ClangTidyCheck {
public:
UseAfterMoveCheck(StringRef Name, ClangTidyContext *Context)
: ClangTidyCheck(Name, Context) {}
void registerMatchers(ast_matchers::MatchFinder *Finder) override;
void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
};
} // namespace bugprone
} // namespace tidy
} // namespace clang
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_USEAFTERMOVECHECK_H

View File

@@ -11,11 +11,11 @@
#include "../ClangTidyModule.h"
#include "../ClangTidyModuleRegistry.h"
#include "../google/UnnamedNamespaceInHeaderCheck.h"
#include "../misc/MoveConstructorInitCheck.h"
#include "../misc/NewDeleteOverloadsCheck.h"
#include "../misc/NonCopyableObjects.h"
#include "../misc/StaticAssertCheck.h"
#include "../misc/ThrowByValueCatchByReferenceCheck.h"
#include "../performance/MoveConstructorInitCheck.h"
#include "CommandProcessorCheck.h"
#include "DontModifyStdNamespaceCheck.h"
#include "FloatLoopCounter.h"
@@ -46,7 +46,7 @@ public:
CheckFactories.registerCheck<google::build::UnnamedNamespaceInHeaderCheck>(
"cert-dcl59-cpp");
// OOP
CheckFactories.registerCheck<performance::MoveConstructorInitCheck>(
CheckFactories.registerCheck<misc::MoveConstructorInitCheck>(
"cert-oop11-cpp");
// ERR
CheckFactories.registerCheck<misc::ThrowByValueCatchByReferenceCheck>(

View File

@@ -22,6 +22,5 @@ add_clang_library(clangTidyCERTModule
clangTidy
clangTidyGoogleModule
clangTidyMiscModule
clangTidyPerformanceModule
clangTidyUtils
)

View File

@@ -4,7 +4,6 @@ add_clang_library(clangTidyCppCoreGuidelinesModule
CppCoreGuidelinesTidyModule.cpp
InterfacesGlobalInitCheck.cpp
NoMallocCheck.cpp
OwningMemoryCheck.cpp
ProBoundsArrayToPointerDecayCheck.cpp
ProBoundsConstantArrayIndexCheck.cpp
ProBoundsPointerArithmeticCheck.cpp

View File

@@ -13,7 +13,6 @@
#include "../misc/UnconventionalAssignOperatorCheck.h"
#include "InterfacesGlobalInitCheck.h"
#include "NoMallocCheck.h"
#include "OwningMemoryCheck.h"
#include "ProBoundsArrayToPointerDecayCheck.h"
#include "ProBoundsConstantArrayIndexCheck.h"
#include "ProBoundsPointerArithmeticCheck.h"
@@ -38,8 +37,6 @@ public:
CheckFactories.registerCheck<InterfacesGlobalInitCheck>(
"cppcoreguidelines-interfaces-global-init");
CheckFactories.registerCheck<NoMallocCheck>("cppcoreguidelines-no-malloc");
CheckFactories.registerCheck<OwningMemoryCheck>(
"cppcoreguidelines-owning-memory");
CheckFactories.registerCheck<ProBoundsArrayToPointerDecayCheck>(
"cppcoreguidelines-pro-bounds-array-to-pointer-decay");
CheckFactories.registerCheck<ProBoundsConstantArrayIndexCheck>(

View File

@@ -29,7 +29,7 @@ Matcher<FunctionDecl> hasAnyListedName(const std::string &FunctionNames) {
utils::options::parseStringList(FunctionNames);
return hasAnyName(std::vector<StringRef>(NameList.begin(), NameList.end()));
}
} // namespace
}
void NoMallocCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
Options.store(Opts, "Allocations", AllocList);

View File

@@ -1,394 +0,0 @@
//===--- OwningMemoryCheck.cpp - clang-tidy--------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "OwningMemoryCheck.h"
#include "../utils/Matchers.h"
#include "../utils/OptionsUtils.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include <string>
#include <vector>
using namespace clang::ast_matchers;
using namespace clang::ast_matchers::internal;
namespace clang {
namespace tidy {
namespace cppcoreguidelines {
// FIXME: Copied from 'NoMallocCheck.cpp'. Has to be refactored into 'util' or
// something like that.
namespace {
Matcher<FunctionDecl> hasAnyListedName(const std::string &FunctionNames) {
const std::vector<std::string> NameList =
utils::options::parseStringList(FunctionNames);
return hasAnyName(std::vector<StringRef>(NameList.begin(), NameList.end()));
}
} // namespace
void OwningMemoryCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
Options.store(Opts, "LegacyResourceProducers", LegacyResourceProducers);
Options.store(Opts, "LegacyResourceConsumers", LegacyResourceConsumers);
}
/// Match common cases, where the owner semantic is relevant, like function
/// calls, delete expressions and others.
void OwningMemoryCheck::registerMatchers(MatchFinder *Finder) {
if (!getLangOpts().CPlusPlus11)
return;
const auto OwnerDecl = typeAliasTemplateDecl(hasName("::gsl::owner"));
const auto IsOwnerType = hasType(OwnerDecl);
const auto LegacyCreatorFunctions = hasAnyListedName(LegacyResourceProducers);
const auto LegacyConsumerFunctions =
hasAnyListedName(LegacyResourceConsumers);
// Legacy functions that are use for resource management but cannot be
// updated to use `gsl::owner<>`, like standard C memory management.
const auto CreatesLegacyOwner =
callExpr(callee(functionDecl(LegacyCreatorFunctions)));
// C-style functions like `::malloc()` sometimes create owners as void*
// which is expected to be cast to the correct type in C++. This case
// must be catched explicitly.
const auto LegacyOwnerCast =
castExpr(hasSourceExpression(CreatesLegacyOwner));
// Functions that do manual resource management but cannot be updated to use
// owner. Best example is `::free()`.
const auto LegacyOwnerConsumers = functionDecl(LegacyConsumerFunctions);
const auto CreatesOwner =
anyOf(cxxNewExpr(),
callExpr(callee(
functionDecl(returns(qualType(hasDeclaration(OwnerDecl)))))),
CreatesLegacyOwner, LegacyOwnerCast);
const auto ConsideredOwner = eachOf(IsOwnerType, CreatesOwner);
// Find delete expressions that delete non-owners.
Finder->addMatcher(
cxxDeleteExpr(
hasDescendant(
declRefExpr(unless(ConsideredOwner)).bind("deleted_variable")))
.bind("delete_expr"),
this);
// Ignoring the implicit casts is vital because the legacy owners do not work
// with the 'owner<>' annotation and therefore always implicitly cast to the
// legacy type (even 'void *').
//
// Furthermore, legacy owner functions are assumed to use raw pointers for
// resources. This check assumes that all pointer arguments of a legacy
// functions shall be 'gsl::owner<>'.
Finder->addMatcher(
callExpr(
allOf(callee(LegacyOwnerConsumers),
hasAnyArgument(allOf(unless(ignoringImpCasts(ConsideredOwner)),
hasType(pointerType())))))
.bind("legacy_consumer"),
this);
// Matching assignment to owners, with the rhs not being an owner nor creating
// one.
Finder->addMatcher(binaryOperator(allOf(matchers::isAssignmentOperator(),
hasLHS(IsOwnerType),
hasRHS(unless(ConsideredOwner))))
.bind("owner_assignment"),
this);
// Matching initialization of owners with non-owners, nor creating owners.
Finder->addMatcher(
namedDecl(
varDecl(allOf(hasInitializer(unless(ConsideredOwner)), IsOwnerType))
.bind("owner_initialization")),
this);
const auto HasConstructorInitializerForOwner =
has(cxxConstructorDecl(forEachConstructorInitializer(
cxxCtorInitializer(allOf(isMemberInitializer(), forField(IsOwnerType),
withInitializer(
// Avoid templatesdeclaration with
// excluding parenListExpr.
allOf(unless(ConsideredOwner),
unless(parenListExpr())))))
.bind("owner_member_initializer"))));
// Match class member initialization that expects owners, but does not get
// them.
Finder->addMatcher(cxxRecordDecl(HasConstructorInitializerForOwner), this);
// Matching on assignment operations where the RHS is a newly created owner,
// but the LHS is not an owner.
Finder->addMatcher(
binaryOperator(allOf(matchers::isAssignmentOperator(),
hasLHS(unless(IsOwnerType)), hasRHS(CreatesOwner)))
.bind("bad_owner_creation_assignment"),
this);
// Matching on initialization operations where the initial value is a newly
// created owner, but the LHS is not an owner.
Finder->addMatcher(
namedDecl(varDecl(eachOf(allOf(hasInitializer(CreatesOwner),
unless(IsOwnerType)),
allOf(hasInitializer(ConsideredOwner),
hasType(autoType().bind("deduced_type")))))
.bind("bad_owner_creation_variable")),
this);
// Match on all function calls that expect owners as arguments, but didn't
// get them.
Finder->addMatcher(
callExpr(forEachArgumentWithParam(
expr(unless(ConsideredOwner)).bind("expected_owner_argument"),
parmVarDecl(IsOwnerType))),
this);
// Matching for function calls where one argument is a created owner, but the
// parameter type is not an owner.
Finder->addMatcher(callExpr(forEachArgumentWithParam(
expr(CreatesOwner).bind("bad_owner_creation_argument"),
parmVarDecl(unless(IsOwnerType))
.bind("bad_owner_creation_parameter"))),
this);
// Matching on functions, that return an owner/resource, but don't declare
// their return type as owner.
Finder->addMatcher(
functionDecl(
allOf(hasDescendant(returnStmt(hasReturnValue(ConsideredOwner))
.bind("bad_owner_return")),
unless(returns(qualType(hasDeclaration(OwnerDecl))))))
.bind("function_decl"),
this);
// Match on classes that have an owner as member, but don't declare a
// destructor to properly release the owner.
Finder->addMatcher(
cxxRecordDecl(
allOf(
has(fieldDecl(IsOwnerType).bind("undestructed_owner_member")),
anyOf(unless(has(cxxDestructorDecl())),
has(cxxDestructorDecl(anyOf(isDefaulted(), isDeleted()))))))
.bind("non_destructor_class"),
this);
}
void OwningMemoryCheck::check(const MatchFinder::MatchResult &Result) {
const auto &Nodes = Result.Nodes;
bool CheckExecuted = false;
CheckExecuted |= handleDeletion(Nodes);
CheckExecuted |= handleLegacyConsumers(Nodes);
CheckExecuted |= handleExpectedOwner(Nodes);
CheckExecuted |= handleAssignmentAndInit(Nodes);
CheckExecuted |= handleAssignmentFromNewOwner(Nodes);
CheckExecuted |= handleReturnValues(Nodes);
CheckExecuted |= handleOwnerMembers(Nodes);
assert(CheckExecuted &&
"None of the subroutines executed, logic error in matcher!");
}
bool OwningMemoryCheck::handleDeletion(const BoundNodes &Nodes) {
// Result of delete matchers.
const auto *DeleteStmt = Nodes.getNodeAs<CXXDeleteExpr>("delete_expr");
const auto *DeletedVariable =
Nodes.getNodeAs<DeclRefExpr>("deleted_variable");
// Deletion of non-owners, with `delete variable;`
if (DeleteStmt) {
diag(DeleteStmt->getLocStart(),
"deleting a pointer through a type that is "
"not marked 'gsl::owner<>'; consider using a "
"smart pointer instead")
<< DeletedVariable->getSourceRange();
// FIXME: The declaration of the variable that was deleted can be
// rewritten.
const ValueDecl *Decl = DeletedVariable->getDecl();
diag(Decl->getLocStart(), "variable declared here", DiagnosticIDs::Note)
<< Decl->getSourceRange();
return true;
}
return false;
}
bool OwningMemoryCheck::handleLegacyConsumers(const BoundNodes &Nodes) {
// Result of matching for legacy consumer-functions like `::free()`.
const auto *LegacyConsumer = Nodes.getNodeAs<CallExpr>("legacy_consumer");
// FIXME: `freopen` should be handled seperately because it takes the filename
// as a pointer, which should not be an owner. The argument that is an owner
// is known and the false positive coming from the filename can be avoided.
if (LegacyConsumer) {
diag(LegacyConsumer->getLocStart(),
"calling legacy resource function without passing a 'gsl::owner<>'")
<< LegacyConsumer->getSourceRange();
return true;
}
return false;
}
bool OwningMemoryCheck::handleExpectedOwner(const BoundNodes &Nodes) {
// Result of function call matchers.
const auto *ExpectedOwner = Nodes.getNodeAs<Expr>("expected_owner_argument");
// Expected function argument to be owner.
if (ExpectedOwner) {
diag(ExpectedOwner->getLocStart(),
"expected argument of type 'gsl::owner<>'; got %0")
<< ExpectedOwner->getType() << ExpectedOwner->getSourceRange();
return true;
}
return false;
}
/// Assignment and initialization of owner variables.
bool OwningMemoryCheck::handleAssignmentAndInit(const BoundNodes &Nodes) {
const auto *OwnerAssignment =
Nodes.getNodeAs<BinaryOperator>("owner_assignment");
const auto *OwnerInitialization =
Nodes.getNodeAs<VarDecl>("owner_initialization");
const auto *OwnerInitializer =
Nodes.getNodeAs<CXXCtorInitializer>("owner_member_initializer");
// Assignments to owners.
if (OwnerAssignment) {
diag(OwnerAssignment->getLocStart(),
"expected assignment source to be of type 'gsl::owner<>'; got %0")
<< OwnerAssignment->getRHS()->getType()
<< OwnerAssignment->getSourceRange();
return true;
}
// Initialization of owners.
if (OwnerInitialization) {
diag(OwnerInitialization->getLocStart(),
"expected initialization with value of type 'gsl::owner<>'; got %0")
<< OwnerInitialization->getAnyInitializer()->getType()
<< OwnerInitialization->getSourceRange();
return true;
}
// Initializer of class constructors that initialize owners.
if (OwnerInitializer) {
diag(OwnerInitializer->getSourceLocation(),
"expected initialization of owner member variable with value of type "
"'gsl::owner<>'; got %0")
// FIXME: the expression from getInit has type 'void', but the type
// of the supplied argument would be of interest.
<< OwnerInitializer->getInit()->getType()
<< OwnerInitializer->getSourceRange();
return true;
}
return false;
}
/// Problematic assignment and initializations, since the assigned value is a
/// newly created owner.
bool OwningMemoryCheck::handleAssignmentFromNewOwner(const BoundNodes &Nodes) {
const auto *BadOwnerAssignment =
Nodes.getNodeAs<BinaryOperator>("bad_owner_creation_assignment");
const auto *BadOwnerInitialization =
Nodes.getNodeAs<VarDecl>("bad_owner_creation_variable");
const auto *BadOwnerArgument =
Nodes.getNodeAs<Expr>("bad_owner_creation_argument");
const auto *BadOwnerParameter =
Nodes.getNodeAs<ParmVarDecl>("bad_owner_creation_parameter");
// Bad assignments to non-owners, where the RHS is a newly created owner.
if (BadOwnerAssignment) {
diag(BadOwnerAssignment->getLocStart(),
"assigning newly created 'gsl::owner<>' to non-owner %0")
<< BadOwnerAssignment->getLHS()->getType()
<< BadOwnerAssignment->getSourceRange();
return true;
}
// Bad initialization of non-owners, where the RHS is a newly created owner.
if (BadOwnerInitialization) {
diag(BadOwnerInitialization->getLocStart(),
"initializing non-owner %0 with a newly created 'gsl::owner<>'")
<< BadOwnerInitialization->getType()
<< BadOwnerInitialization->getSourceRange();
// FIXME: FixitHint to rewrite the type of the initialized variable
// as 'gsl::owner<OriginalType>'
// If the type of the variable was deduced, the wrapping owner typedef is
// eliminated, therefore the check emits a special note for that case.
if (Nodes.getNodeAs<AutoType>("deduced_type")) {
diag(BadOwnerInitialization->getLocStart(),
"type deduction did not result in an owner", DiagnosticIDs::Note);
}
return true;
}
// Function call, where one arguments is a newly created owner, but the
// parameter type is not.
if (BadOwnerArgument) {
assert(BadOwnerParameter &&
"parameter for the problematic argument not found");
diag(BadOwnerArgument->getLocStart(), "initializing non-owner argument of "
"type %0 with a newly created "
"'gsl::owner<>'")
<< BadOwnerParameter->getType() << BadOwnerArgument->getSourceRange();
return true;
}
return false;
}
bool OwningMemoryCheck::handleReturnValues(const BoundNodes &Nodes) {
// Function return statements, that are owners/resources, but the function
// declaration does not declare its return value as owner.
const auto *BadReturnType = Nodes.getNodeAs<ReturnStmt>("bad_owner_return");
const auto *Function = Nodes.getNodeAs<FunctionDecl>("function_decl");
// Function return values, that should be owners but aren't.
if (BadReturnType) {
// The returned value is a resource or variable that was not annotated with
// owner<> and the function return type is not owner<>.
diag(BadReturnType->getLocStart(),
"returning a newly created resource of "
"type %0 or 'gsl::owner<>' from a "
"function whose return type is not 'gsl::owner<>'")
<< Function->getReturnType() << BadReturnType->getSourceRange();
// FIXME: Rewrite the return type as 'gsl::owner<OriginalType>'
return true;
}
return false;
}
bool OwningMemoryCheck::handleOwnerMembers(const BoundNodes &Nodes) {
// Classes, that have owners as member, but do not declare destructors
// accordingly.
const auto *BadClass = Nodes.getNodeAs<CXXRecordDecl>("non_destructor_class");
// Classes, that contains owners, but do not declare destructors.
if (BadClass) {
const auto *DeclaredOwnerMember =
Nodes.getNodeAs<FieldDecl>("undestructed_owner_member");
assert(DeclaredOwnerMember &&
"match on class with bad destructor but without a declared owner");
diag(DeclaredOwnerMember->getLocStart(),
"member variable of type 'gsl::owner<>' requires the class %0 to "
"implement a destructor to release the owned resource")
<< BadClass;
return true;
}
return false;
}
} // namespace cppcoreguidelines
} // namespace tidy
} // namespace clang

View File

@@ -1,63 +0,0 @@
//===--- OwningMemoryCheck.h - clang-tidy------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CPPCOREGUIDELINES_OWNING_MEMORY_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CPPCOREGUIDELINES_OWNING_MEMORY_H
#include "../ClangTidy.h"
namespace clang {
namespace tidy {
namespace cppcoreguidelines {
/// Checks for common use cases for gsl::owner and enforces the unique owner
/// nature of it whenever possible.
///
/// For the user-facing documentation see:
/// http://clang.llvm.org/extra/clang-tidy/checks/cppcoreguidelines-owning-memory.html
class OwningMemoryCheck : public ClangTidyCheck {
public:
OwningMemoryCheck(StringRef Name, ClangTidyContext *Context)
: ClangTidyCheck(Name, Context),
LegacyResourceProducers(Options.get(
"LegacyResourceProducers", "::malloc;::aligned_alloc;::realloc;"
"::calloc;::fopen;::freopen;::tmpfile")),
LegacyResourceConsumers(Options.get(
"LegacyResourceConsumers", "::free;::realloc;::freopen;::fclose")) {
}
/// Make configuration of checker discoverable.
void storeOptions(ClangTidyOptions::OptionMap &Opts) override;
void registerMatchers(ast_matchers::MatchFinder *Finder) override;
void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
private:
bool handleDeletion(const ast_matchers::BoundNodes &Nodes);
bool handleLegacyConsumers(const ast_matchers::BoundNodes &Nodes);
bool handleExpectedOwner(const ast_matchers::BoundNodes &Nodes);
bool handleAssignmentAndInit(const ast_matchers::BoundNodes &Nodes);
bool handleAssignmentFromNewOwner(const ast_matchers::BoundNodes &Nodes);
bool handleReturnValues(const ast_matchers::BoundNodes &Nodes);
bool handleOwnerMembers(const ast_matchers::BoundNodes &Nodes);
/// List of old C-style functions that create resources.
/// Defaults to
/// `::malloc;::aligned_alloc;::realloc;::calloc;::fopen;::freopen;::tmpfile`.
const std::string LegacyResourceProducers;
/// List of old C-style functions that consume or release resources.
/// Defaults to `::free;::realloc;::freopen;::fclose`.
const std::string LegacyResourceConsumers;
};
} // namespace cppcoreguidelines
} // namespace tidy
} // namespace clang
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CPPCOREGUIDELINES_OWNING_MEMORY_H

View File

@@ -23,7 +23,7 @@ ProBoundsConstantArrayIndexCheck::ProBoundsConstantArrayIndexCheck(
StringRef Name, ClangTidyContext *Context)
: ClangTidyCheck(Name, Context), GslHeader(Options.get("GslHeader", "")),
IncludeStyle(utils::IncludeSorter::parseIncludeStyle(
Options.getLocalOrGlobal("IncludeStyle", "llvm"))) {}
Options.get("IncludeStyle", "llvm"))) {}
void ProBoundsConstantArrayIndexCheck::storeOptions(
ClangTidyOptions::OptionMap &Opts) {

View File

@@ -32,16 +32,22 @@ AST_MATCHER(CXXRecordDecl, hasDefaultConstructor) {
}
// Iterate over all the fields in a record type, both direct and indirect (e.g.
// if the record contains an anonmyous struct).
// if the record contains an anonmyous struct). If OneFieldPerUnion is true and
// the record type (or indirect field) is a union, forEachField will stop after
// the first field.
template <typename T, typename Func>
void forEachField(const RecordDecl &Record, const T &Fields, Func &&Fn) {
void forEachField(const RecordDecl &Record, const T &Fields,
bool OneFieldPerUnion, Func &&Fn) {
for (const FieldDecl *F : Fields) {
if (F->isAnonymousStructOrUnion()) {
if (const CXXRecordDecl *R = F->getType()->getAsCXXRecordDecl())
forEachField(*R, R->fields(), Fn);
forEachField(*R, R->fields(), OneFieldPerUnion, Fn);
} else {
Fn(F);
}
if (OneFieldPerUnion && Record.isUnion())
break;
}
}
@@ -221,7 +227,7 @@ void getInitializationsInOrder(const CXXRecordDecl &ClassDecl,
Decls.emplace_back(Decl);
}
}
forEachField(ClassDecl, ClassDecl.fields(),
forEachField(ClassDecl, ClassDecl.fields(), false,
[&](const FieldDecl *F) { Decls.push_back(F); });
}
@@ -347,7 +353,7 @@ void ProTypeMemberInitCheck::checkMissingMemberInitializer(
// Gather all fields (direct and indirect) that need to be initialized.
SmallPtrSet<const FieldDecl *, 16> FieldsToInit;
forEachField(ClassDecl, ClassDecl.fields(), [&](const FieldDecl *F) {
forEachField(ClassDecl, ClassDecl.fields(), false, [&](const FieldDecl *F) {
if (!F->hasInClassInitializer() &&
utils::type_traits::isTriviallyDefaultConstructible(F->getType(),
Context) &&
@@ -373,12 +379,12 @@ void ProTypeMemberInitCheck::checkMissingMemberInitializer(
// Collect all fields in order, both direct fields and indirect fields from
// anonmyous record types.
SmallVector<const FieldDecl *, 16> OrderedFields;
forEachField(ClassDecl, ClassDecl.fields(),
forEachField(ClassDecl, ClassDecl.fields(), false,
[&](const FieldDecl *F) { OrderedFields.push_back(F); });
// Collect all the fields we need to initialize, including indirect fields.
SmallPtrSet<const FieldDecl *, 16> AllFieldsToInit;
forEachField(ClassDecl, FieldsToInit,
forEachField(ClassDecl, FieldsToInit, false,
[&](const FieldDecl *F) { AllFieldsToInit.insert(F); });
if (AllFieldsToInit.empty())
return;
@@ -398,16 +404,11 @@ void ProTypeMemberInitCheck::checkMissingMemberInitializer(
// Collect all fields but only suggest a fix for the first member of unions,
// as initializing more than one union member is an error.
SmallPtrSet<const FieldDecl *, 16> FieldsToFix;
SmallPtrSet<const RecordDecl *, 4> UnionsSeen;
forEachField(ClassDecl, OrderedFields, [&](const FieldDecl *F) {
if (!FieldsToInit.count(F))
return;
forEachField(ClassDecl, FieldsToInit, true, [&](const FieldDecl *F) {
// Don't suggest fixes for enums because we don't know a good default.
// Don't suggest fixes for bitfields because in-class initialization is not
// possible.
if (F->getType()->isEnumeralType() || F->isBitField())
return;
if (!F->getParent()->isUnion() || UnionsSeen.insert(F->getParent()).second)
if (!F->getType()->isEnumeralType() && !F->isBitField())
FieldsToFix.insert(F);
});
if (FieldsToFix.empty())

View File

@@ -1,16 +0,0 @@
set(LLVM_LINK_COMPONENTS support)
add_clang_library(clangTidyFuchsiaModule
DefaultArgumentsCheck.cpp
FuchsiaTidyModule.cpp
OverloadedOperatorCheck.cpp
VirtualInheritanceCheck.cpp
LINK_LIBS
clangAST
clangASTMatchers
clangBasic
clangLex
clangTidy
clangTidyUtils
)

View File

@@ -1,64 +0,0 @@
//===--- DefaultArgumentsCheck.cpp - clang-tidy----------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "DefaultArgumentsCheck.h"
using namespace clang::ast_matchers;
namespace clang {
namespace tidy {
namespace fuchsia {
void DefaultArgumentsCheck::registerMatchers(MatchFinder *Finder) {
// Calling a function which uses default arguments is disallowed.
Finder->addMatcher(cxxDefaultArgExpr().bind("stmt"), this);
// Declaring default parameters is disallowed.
Finder->addMatcher(parmVarDecl(hasDefaultArgument()).bind("decl"), this);
}
void DefaultArgumentsCheck::check(const MatchFinder::MatchResult &Result) {
if (const auto *S =
Result.Nodes.getNodeAs<CXXDefaultArgExpr>("stmt")) {
diag(S->getUsedLocation(),
"calling a function that uses a default argument is disallowed");
diag(S->getParam()->getLocStart(),
"default parameter was declared here",
DiagnosticIDs::Note);
} else if (const ParmVarDecl *D =
Result.Nodes.getNodeAs<ParmVarDecl>("decl")) {
SourceRange DefaultArgRange = D->getDefaultArgRange();
if (DefaultArgRange.getEnd() != D->getLocEnd()) {
return;
} else if (DefaultArgRange.getBegin().isMacroID()) {
diag(D->getLocStart(),
"declaring a parameter with a default argument is disallowed");
} else {
SourceLocation StartLocation = D->getName().empty() ?
D->getLocStart() : D->getLocation();
SourceRange RemovalRange(Lexer::getLocForEndOfToken(
StartLocation, 0,
*Result.SourceManager,
Result.Context->getLangOpts()
),
DefaultArgRange.getEnd()
);
diag(D->getLocStart(),
"declaring a parameter with a default argument is disallowed")
<< D
<< FixItHint::CreateRemoval(RemovalRange);
}
}
}
} // namespace fuchsia
} // namespace tidy
} // namespace clang

View File

@@ -1,35 +0,0 @@
//===--- DefaultArgumentsCheck.h - clang-tidy--------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_FUCHSIA_DEFAULT_ARGUMENTS_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_FUCHSIA_DEFAULT_ARGUMENTS_H
#include "../ClangTidy.h"
namespace clang {
namespace tidy {
namespace fuchsia {
/// Default arguments are not allowed in declared or called functions.
///
/// For the user-facing documentation see:
/// http://clang.llvm.org/extra/clang-tidy/checks/fuchsia-default-arguments.html
class DefaultArgumentsCheck : public ClangTidyCheck {
public:
DefaultArgumentsCheck(StringRef Name, ClangTidyContext *Context)
: ClangTidyCheck(Name, Context) {}
void registerMatchers(ast_matchers::MatchFinder *Finder) override;
void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
};
} // namespace fuchsia
} // namespace tidy
} // namespace clang
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_FUCHSIA_DEFAULT_ARGUMENTS_H

View File

@@ -1,45 +0,0 @@
//===--- FuchsiaTidyModule.cpp - clang-tidy--------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "../ClangTidy.h"
#include "../ClangTidyModule.h"
#include "../ClangTidyModuleRegistry.h"
#include "DefaultArgumentsCheck.h"
#include "OverloadedOperatorCheck.h"
#include "VirtualInheritanceCheck.h"
using namespace clang::ast_matchers;
namespace clang {
namespace tidy {
namespace fuchsia {
/// This module is for Fuchsia-specific checks.
class FuchsiaModule : public ClangTidyModule {
public:
void addCheckFactories(ClangTidyCheckFactories &CheckFactories) override {
CheckFactories.registerCheck<DefaultArgumentsCheck>(
"fuchsia-default-arguments");
CheckFactories.registerCheck<OverloadedOperatorCheck>(
"fuchsia-overloaded-operator");
CheckFactories.registerCheck<VirtualInheritanceCheck>(
"fuchsia-virtual-inheritance");
}
};
// Register the FuchsiaTidyModule using this statically initialized variable.
static ClangTidyModuleRegistry::Add<FuchsiaModule>
X("fuchsia-module", "Adds Fuchsia platform checks.");
} // namespace fuchsia
// This anchor is used to force the linker to link in the generated object file
// and thus register the FuchsiaModule.
volatile int FuchsiaModuleAnchorSource = 0;
} // namespace tidy
} // namespace clang

View File

@@ -1,43 +0,0 @@
//===--- OverloadedOperatorCheck.cpp - clang-tidy--------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "OverloadedOperatorCheck.h"
using namespace clang::ast_matchers;
namespace clang {
namespace tidy {
namespace fuchsia {
AST_MATCHER(FunctionDecl, isFuchsiaOverloadedOperator) {
if (const auto *CXXMethodNode = dyn_cast<CXXMethodDecl>(&Node)) {
if (CXXMethodNode->isCopyAssignmentOperator() ||
CXXMethodNode->isMoveAssignmentOperator())
return false;
}
return Node.isOverloadedOperator();
}
void OverloadedOperatorCheck::registerMatchers(MatchFinder *Finder) {
Finder->addMatcher(functionDecl(isFuchsiaOverloadedOperator()).bind("decl"),
this);
}
void OverloadedOperatorCheck::check(const MatchFinder::MatchResult &Result) {
const auto *D = Result.Nodes.getNodeAs<FunctionDecl>("decl");
assert(D && "No FunctionDecl captured!");
SourceLocation Loc = D->getLocStart();
if (Loc.isValid())
diag(Loc, "cannot overload %0") << D;
}
} // namespace fuchsia
} // namespace tidy
} // namespace clang

View File

@@ -1,35 +0,0 @@
//===--- OverloadedOperatorCheck.h - clang-tidy------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_FUCHSIA_OVERLOADED_OPERATOR_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_FUCHSIA_OVERLOADED_OPERATOR_H
#include "../ClangTidy.h"
namespace clang {
namespace tidy {
namespace fuchsia {
/// Overloading operators is disallowed by the Fuchsia coding standard.
///
/// For the user-facing documentation see:
/// http://clang.llvm.org/extra/clang-tidy/checks/fuchsia-overloaded-operator.html
class OverloadedOperatorCheck : public ClangTidyCheck {
public:
OverloadedOperatorCheck(StringRef Name, ClangTidyContext *Context)
: ClangTidyCheck(Name, Context) {}
void registerMatchers(ast_matchers::MatchFinder *Finder) override;
void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
};
} // namespace fuchsia
} // namespace tidy
} // namespace clang
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_FUCHSIA_OVERLOADED_OPERATOR_H

View File

@@ -1,41 +0,0 @@
//===--- VirtualInheritanceCheck.cpp - clang-tidy--------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "VirtualInheritanceCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
using namespace clang::ast_matchers;
namespace clang {
namespace tidy {
namespace fuchsia {
AST_MATCHER(CXXRecordDecl, hasDirectVirtualBaseClass) {
if (!Node.hasDefinition()) return false;
if (!Node.getNumVBases()) return false;
for (const CXXBaseSpecifier &Base : Node.bases())
if (Base.isVirtual()) return true;
return false;
}
void VirtualInheritanceCheck::registerMatchers(MatchFinder *Finder) {
// Defining classes using direct virtual inheritance is disallowed.
Finder->addMatcher(cxxRecordDecl(hasDirectVirtualBaseClass()).bind("decl"),
this);
}
void VirtualInheritanceCheck::check(const MatchFinder::MatchResult &Result) {
if (const auto *D = Result.Nodes.getNodeAs<CXXRecordDecl>("decl"))
diag(D->getLocStart(), "direct virtual inheritance is disallowed");
}
} // namespace fuchsia
} // namespace tidy
} // namespace clang

View File

@@ -1,35 +0,0 @@
//===--- VirtualInheritanceCheck.h - clang-tidy------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_FUCHSIA_VIRTUAL_INHERITANCE_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_FUCHSIA_VIRTUAL_INHERITANCE_H
#include "../ClangTidy.h"
namespace clang {
namespace tidy {
namespace fuchsia {
/// Defining classes with virtual inheritance is disallowed.
///
/// For the user-facing documentation see:
/// http://clang.llvm.org/extra/clang-tidy/checks/fuchsia-virtual-inheritance.html
class VirtualInheritanceCheck : public ClangTidyCheck {
public:
VirtualInheritanceCheck(StringRef Name, ClangTidyContext *Context)
: ClangTidyCheck(Name, Context) {}
void registerMatchers(ast_matchers::MatchFinder *Finder) override;
void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
};
} // namespace fuchsia
} // namespace tidy
} // namespace clang
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_FUCHSIA_VIRTUAL_INHERITANCE_H

View File

@@ -1,47 +0,0 @@
//===--- AvoidThrowingObjCExceptionCheck.cpp - clang-tidy------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "AvoidThrowingObjCExceptionCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
using namespace clang::ast_matchers;
namespace clang {
namespace tidy {
namespace google {
namespace objc {
void AvoidThrowingObjCExceptionCheck::registerMatchers(MatchFinder *Finder) {
Finder->addMatcher(objcThrowStmt().bind("throwStmt"), this);
Finder->addMatcher(
objcMessageExpr(anyOf(hasSelector("raise:format:"),
hasSelector("raise:format:arguments:")),
hasReceiverType(asString("NSException")))
.bind("raiseException"),
this);
}
void AvoidThrowingObjCExceptionCheck::check(
const MatchFinder::MatchResult &Result) {
const auto *MatchedStmt =
Result.Nodes.getNodeAs<ObjCAtThrowStmt>("throwStmt");
const auto *MatchedExpr =
Result.Nodes.getNodeAs<ObjCMessageExpr>("raiseException");
auto SourceLoc = MatchedStmt == nullptr ? MatchedExpr->getSelectorStartLoc()
: MatchedStmt->getThrowLoc();
diag(SourceLoc,
"pass in NSError ** instead of throwing exception to indicate "
"Objective-C errors");
}
} // namespace objc
} // namespace google
} // namespace tidy
} // namespace clang

View File

@@ -1,39 +0,0 @@
//===--- AvoidThrowingObjCExceptionCheck.h - clang-tidy----------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_GOOGLE_OBJC_AVOID_THROWING_EXCEPTION_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_GOOGLE_OBJC_AVOID_THROWING_EXCEPTION_H
#include "../ClangTidy.h"
namespace clang {
namespace tidy {
namespace google {
namespace objc {
/// The check is to find usage of @throw invocation in Objective-C code.
/// We should avoid using @throw for Objective-C exceptions according to
/// the Google Objective-C Style Guide.
///
/// For the user-facing documentation see:
/// http://clang.llvm.org/extra/clang-tidy/checks/google-objc-avoid-throwing-exception.html
class AvoidThrowingObjCExceptionCheck : public ClangTidyCheck {
public:
AvoidThrowingObjCExceptionCheck(StringRef Name, ClangTidyContext *Context)
: ClangTidyCheck(Name, Context) {}
void registerMatchers(ast_matchers::MatchFinder *Finder) override;
void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
};
} // namespace objc
} // namespace google
} // namespace tidy
} // namespace clang
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_GOOGLE_OBJC_AVOID_THROWING_EXCEPTION_H

View File

@@ -2,12 +2,10 @@ set(LLVM_LINK_COMPONENTS support)
add_clang_library(clangTidyGoogleModule
AvoidCStyleCastsCheck.cpp
AvoidThrowingObjCExceptionCheck.cpp
DefaultArgumentsCheck.cpp
ExplicitConstructorCheck.cpp
ExplicitMakePairCheck.cpp
GlobalNamesInHeadersCheck.cpp
GlobalVariableDeclarationCheck.cpp
GoogleTidyModule.cpp
IntegerTypesCheck.cpp
NonConstReferences.cpp

View File

@@ -23,8 +23,8 @@ namespace readability {
GlobalNamesInHeadersCheck::GlobalNamesInHeadersCheck(StringRef Name,
ClangTidyContext *Context)
: ClangTidyCheck(Name, Context),
RawStringHeaderFileExtensions(Options.getLocalOrGlobal(
"HeaderFileExtensions", utils::defaultHeaderFileExtensions())) {
RawStringHeaderFileExtensions(
Options.getLocalOrGlobal("HeaderFileExtensions", "h")) {
if (!utils::parseHeaderFileExtensions(RawStringHeaderFileExtensions,
HeaderFileExtensions, ',')) {
llvm::errs() << "Invalid header file extension: "

View File

@@ -1,90 +0,0 @@
//===--- GlobalVariableDeclarationCheck.cpp - clang-tidy-------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "GlobalVariableDeclarationCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringRef.h"
#include <string>
using namespace clang::ast_matchers;
namespace clang {
namespace tidy {
namespace google {
namespace objc {
namespace {
FixItHint generateFixItHint(const VarDecl *Decl, bool IsConst) {
char FC = Decl->getName()[0];
if (!llvm::isAlpha(FC) || Decl->getName().size() == 1) {
// No fix available if first character is not alphabetical character, or it
// is a single-character variable, since it is difficult to determine the
// proper fix in this case. Users should create a proper variable name by
// their own.
return FixItHint();
}
char SC = Decl->getName()[1];
if ((FC == 'k' || FC == 'g') && !llvm::isAlpha(SC)) {
// No fix available if the prefix is correct but the second character is not
// alphabetical, since it is difficult to determine the proper fix in this
// case.
return FixItHint();
}
auto NewName = (IsConst ? "k" : "g") +
llvm::StringRef(std::string(1, FC)).upper() +
Decl->getName().substr(1).str();
return FixItHint::CreateReplacement(
CharSourceRange::getTokenRange(SourceRange(Decl->getLocation())),
llvm::StringRef(NewName));
}
} // namespace
void GlobalVariableDeclarationCheck::registerMatchers(MatchFinder *Finder) {
// The relevant Style Guide rule only applies to Objective-C.
if (!getLangOpts().ObjC1 && !getLangOpts().ObjC2) {
return;
}
// need to add two matchers since we need to bind different ids to distinguish
// constants and variables. Since bind() can only be called on node matchers,
// we cannot make it in one matcher.
Finder->addMatcher(
varDecl(hasGlobalStorage(), unless(hasType(isConstQualified())),
unless(matchesName("::g[A-Z]")))
.bind("global_var"),
this);
Finder->addMatcher(varDecl(hasGlobalStorage(), hasType(isConstQualified()),
unless(matchesName("::k[A-Z]")))
.bind("global_const"),
this);
}
void GlobalVariableDeclarationCheck::check(
const MatchFinder::MatchResult &Result) {
if (const auto *Decl = Result.Nodes.getNodeAs<VarDecl>("global_var")) {
diag(Decl->getLocation(),
"non-const global variable '%0' must have a name which starts with "
"'g[A-Z]'")
<< Decl->getName() << generateFixItHint(Decl, false);
}
if (const auto *Decl = Result.Nodes.getNodeAs<VarDecl>("global_const")) {
diag(Decl->getLocation(),
"const global variable '%0' must have a name which starts with "
"'k[A-Z]'")
<< Decl->getName() << generateFixItHint(Decl, true);
}
}
} // namespace objc
} // namespace google
} // namespace tidy
} // namespace clang

View File

@@ -1,39 +0,0 @@
//===--- GlobalVariableDeclarationCheck.h - clang-tidy-----------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_GOOGLE_OBJC_GLOBAL_VARIABLE_DECLARATION_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_GOOGLE_OBJC_GLOBAL_VARIABLE_DECLARATION_H
#include "../ClangTidy.h"
namespace clang {
namespace tidy {
namespace google {
namespace objc {
/// The check for Objective-C global variables and constants naming convention.
/// The declaration should follow the patterns of 'k[A-Z].*' (constants) or
/// 'g[A-Z].*' (variables).
///
/// For the user-facing documentation see:
/// http://clang.llvm.org/extra/clang-tidy/checks/google-objc-global-variable-declaration.html
class GlobalVariableDeclarationCheck : public ClangTidyCheck {
public:
GlobalVariableDeclarationCheck(StringRef Name, ClangTidyContext *Context)
: ClangTidyCheck(Name, Context) {}
void registerMatchers(ast_matchers::MatchFinder *Finder) override;
void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
};
} // namespace objc
} // namespace google
} // namespace tidy
} // namespace clang
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_GOOGLE_OBJC_GLOBAL_VARIABLE_DECLARATION_H

View File

@@ -15,12 +15,10 @@
#include "../readability/NamespaceCommentCheck.h"
#include "../readability/RedundantSmartptrGetCheck.h"
#include "AvoidCStyleCastsCheck.h"
#include "AvoidThrowingObjCExceptionCheck.h"
#include "DefaultArgumentsCheck.h"
#include "ExplicitConstructorCheck.h"
#include "ExplicitMakePairCheck.h"
#include "GlobalNamesInHeadersCheck.h"
#include "GlobalVariableDeclarationCheck.h"
#include "IntegerTypesCheck.h"
#include "NonConstReferences.h"
#include "OverloadedUnaryAndCheck.h"
@@ -36,7 +34,7 @@ namespace tidy {
namespace google {
class GoogleModule : public ClangTidyModule {
public:
public:
void addCheckFactories(ClangTidyCheckFactories &CheckFactories) override {
CheckFactories.registerCheck<build::ExplicitMakePairCheck>(
"google-build-explicit-make-pair");
@@ -48,12 +46,6 @@ class GoogleModule : public ClangTidyModule {
"google-default-arguments");
CheckFactories.registerCheck<ExplicitConstructorCheck>(
"google-explicit-constructor");
CheckFactories.registerCheck<readability::GlobalNamesInHeadersCheck>(
"google-global-names-in-headers");
CheckFactories.registerCheck<objc::AvoidThrowingObjCExceptionCheck>(
"google-objc-avoid-throwing-exception");
CheckFactories.registerCheck<objc::GlobalVariableDeclarationCheck>(
"google-objc-global-variable-declaration");
CheckFactories.registerCheck<runtime::IntegerTypesCheck>(
"google-runtime-int");
CheckFactories.registerCheck<runtime::OverloadedUnaryAndCheck>(
@@ -69,6 +61,8 @@ class GoogleModule : public ClangTidyModule {
CheckFactories
.registerCheck<clang::tidy::readability::BracesAroundStatementsCheck>(
"google-readability-braces-around-statements");
CheckFactories.registerCheck<readability::GlobalNamesInHeadersCheck>(
"google-global-names-in-headers");
CheckFactories.registerCheck<clang::tidy::readability::FunctionSizeCheck>(
"google-readability-function-size");
CheckFactories
@@ -95,11 +89,11 @@ class GoogleModule : public ClangTidyModule {
static ClangTidyModuleRegistry::Add<GoogleModule> X("google-module",
"Adds Google lint checks.");
} // namespace google
} // namespace google
// This anchor is used to force the linker to link in the generated object file
// and thus register the GoogleModule.
volatile int GoogleModuleAnchorSource = 0;
} // namespace tidy
} // namespace clang
} // namespace tidy
} // namespace clang

View File

@@ -27,8 +27,8 @@ void StringReferenceMemberCheck::registerMatchers(
return;
// Look for const references to std::string or ::string.
auto String = anyOf(namedDecl(hasName("::std::string")),
namedDecl(hasName("::string")));
auto String = anyOf(recordDecl(hasName("::std::basic_string")),
recordDecl(hasName("::string")));
auto ConstString = qualType(isConstQualified(), hasDeclaration(String));
// Ignore members in template instantiations.

View File

@@ -22,8 +22,8 @@ namespace build {
UnnamedNamespaceInHeaderCheck::UnnamedNamespaceInHeaderCheck(
StringRef Name, ClangTidyContext *Context)
: ClangTidyCheck(Name, Context),
RawStringHeaderFileExtensions(Options.getLocalOrGlobal(
"HeaderFileExtensions", utils::defaultHeaderFileExtensions())) {
RawStringHeaderFileExtensions(
Options.getLocalOrGlobal("HeaderFileExtensions", "h,hh,hpp,hxx")) {
if (!utils::parseHeaderFileExtensions(RawStringHeaderFileExtensions,
HeaderFileExtensions, ',')) {
llvm::errs() << "Invalid header file extension: "

View File

@@ -1,10 +1,8 @@
set(LLVM_LINK_COMPONENTS support)
add_clang_library(clangTidyHICPPModule
ExceptionBaseclassCheck.cpp
NoAssemblerCheck.cpp
HICPPTidyModule.cpp
SignedBitwiseCheck.cpp
LINK_LIBS
clangAST
@@ -12,12 +10,10 @@ add_clang_library(clangTidyHICPPModule
clangBasic
clangLex
clangTidy
clangTidyBugproneModule
clangTidyCppCoreGuidelinesModule
clangTidyGoogleModule
clangTidyMiscModule
clangTidyModernizeModule
clangTidyPerformanceModule
clangTidyReadabilityModule
clangTidyUtils
)

View File

@@ -1,50 +0,0 @@
//===--- ExceptionBaseclassCheck.cpp - clang-tidy--------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "ExceptionBaseclassCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
using namespace clang::ast_matchers;
namespace clang {
namespace tidy {
namespace hicpp {
void ExceptionBaseclassCheck::registerMatchers(MatchFinder *Finder) {
if (!getLangOpts().CPlusPlus)
return;
Finder->addMatcher(
cxxThrowExpr(allOf(has(expr(unless(hasType(qualType(hasCanonicalType(
hasDeclaration(cxxRecordDecl(isSameOrDerivedFrom(
hasName("std::exception")))))))))),
has(expr(unless(cxxUnresolvedConstructExpr()))),
eachOf(has(expr(hasType(namedDecl().bind("decl")))),
anything())))
.bind("bad_throw"),
this);
}
void ExceptionBaseclassCheck::check(const MatchFinder::MatchResult &Result) {
const auto *BadThrow = Result.Nodes.getNodeAs<CXXThrowExpr>("bad_throw");
diag(BadThrow->getSubExpr()->getLocStart(), "throwing an exception whose "
"type %0 is not derived from "
"'std::exception'")
<< BadThrow->getSubExpr()->getType() << BadThrow->getSourceRange();
const auto *TypeDecl = Result.Nodes.getNodeAs<NamedDecl>("decl");
if (TypeDecl != nullptr)
diag(TypeDecl->getLocStart(), "type defined here", DiagnosticIDs::Note);
}
} // namespace hicpp
} // namespace tidy
} // namespace clang

View File

@@ -1,35 +0,0 @@
//===--- ExceptionBaseclassCheck.h - clang-tidy------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_HICPP_EXCEPTION_BASECLASS_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_HICPP_EXCEPTION_BASECLASS_H
#include "../ClangTidy.h"
namespace clang {
namespace tidy {
namespace hicpp {
/// Check for thrown exceptions and enforce they are all derived from std::exception.
///
/// For the user-facing documentation see:
/// http://clang.llvm.org/extra/clang-tidy/checks/hicpp-exception-baseclass.html
class ExceptionBaseclassCheck : public ClangTidyCheck {
public:
ExceptionBaseclassCheck(StringRef Name, ClangTidyContext *Context)
: ClangTidyCheck(Name, Context) {}
void registerMatchers(ast_matchers::MatchFinder *Finder) override;
void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
};
} // namespace hicpp
} // namespace tidy
} // namespace clang
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_HICPP_EXCEPTION_BASECLASS_H

View File

@@ -10,33 +10,20 @@
#include "../ClangTidy.h"
#include "../ClangTidyModule.h"
#include "../ClangTidyModuleRegistry.h"
#include "../bugprone/UseAfterMoveCheck.h"
#include "../cppcoreguidelines/NoMallocCheck.h"
#include "../cppcoreguidelines/ProBoundsArrayToPointerDecayCheck.h"
#include "../cppcoreguidelines/ProTypeMemberInitCheck.h"
#include "../cppcoreguidelines/ProTypeVarargCheck.h"
#include "../cppcoreguidelines/SpecialMemberFunctionsCheck.h"
#include "../google/DefaultArgumentsCheck.h"
#include "../google/ExplicitConstructorCheck.h"
#include "../misc/NewDeleteOverloadsCheck.h"
#include "../misc/StaticAssertCheck.h"
#include "../misc/NoexceptMoveConstructorCheck.h"
#include "../misc/UndelegatedConstructor.h"
#include "../modernize/DeprecatedHeadersCheck.h"
#include "../modernize/UseAutoCheck.h"
#include "../modernize/UseEmplaceCheck.h"
#include "../misc/UseAfterMoveCheck.h"
#include "../modernize/UseEqualsDefaultCheck.h"
#include "../modernize/UseEqualsDeleteCheck.h"
#include "../modernize/UseNoexceptCheck.h"
#include "../modernize/UseNullptrCheck.h"
#include "../modernize/UseOverrideCheck.h"
#include "../performance/MoveConstArgCheck.h"
#include "../performance/NoexceptMoveConstructorCheck.h"
#include "../readability/BracesAroundStatementsCheck.h"
#include "../readability/FunctionSizeCheck.h"
#include "../readability/IdentifierNamingCheck.h"
#include "ExceptionBaseclassCheck.h"
#include "NoAssemblerCheck.h"
#include "SignedBitwiseCheck.h"
namespace clang {
namespace tidy {
@@ -45,58 +32,32 @@ namespace hicpp {
class HICPPModule : public ClangTidyModule {
public:
void addCheckFactories(ClangTidyCheckFactories &CheckFactories) override {
CheckFactories.registerCheck<readability::BracesAroundStatementsCheck>(
"hicpp-braces-around-statements");
CheckFactories.registerCheck<modernize::DeprecatedHeadersCheck>(
"hicpp-deprecated-headers");
CheckFactories.registerCheck<ExceptionBaseclassCheck>(
"hicpp-exception-baseclass");
CheckFactories.registerCheck<SignedBitwiseCheck>(
"hicpp-signed-bitwise");
CheckFactories.registerCheck<google::ExplicitConstructorCheck>(
"hicpp-explicit-conversions");
CheckFactories.registerCheck<readability::FunctionSizeCheck>(
"hicpp-function-size");
CheckFactories.registerCheck<readability::IdentifierNamingCheck>(
"hicpp-named-parameter");
CheckFactories.registerCheck<bugprone::UseAfterMoveCheck>(
CheckFactories.registerCheck<misc::UseAfterMoveCheck>(
"hicpp-invalid-access-moved");
CheckFactories.registerCheck<cppcoreguidelines::ProTypeMemberInitCheck>(
"hicpp-member-init");
CheckFactories.registerCheck<performance::MoveConstArgCheck>(
"hicpp-move-const-arg");
CheckFactories.registerCheck<misc::NewDeleteOverloadsCheck>(
"hicpp-new-delete-operators");
CheckFactories.registerCheck<performance::NoexceptMoveConstructorCheck>(
CheckFactories.registerCheck<misc::NoexceptMoveConstructorCheck>(
"hicpp-noexcept-move");
CheckFactories
.registerCheck<cppcoreguidelines::ProBoundsArrayToPointerDecayCheck>(
"hicpp-no-array-decay");
CheckFactories.registerCheck<NoAssemblerCheck>("hicpp-no-assembler");
CheckFactories.registerCheck<cppcoreguidelines::NoMallocCheck>(
"hicpp-no-malloc");
CheckFactories
.registerCheck<cppcoreguidelines::SpecialMemberFunctionsCheck>(
"hicpp-special-member-functions");
CheckFactories.registerCheck<misc::StaticAssertCheck>(
"hicpp-static-assert");
CheckFactories.registerCheck<modernize::UseAutoCheck>("hicpp-use-auto");
CheckFactories.registerCheck<misc::UndelegatedConstructorCheck>(
"hicpp-undelegated-constructor");
CheckFactories.registerCheck<modernize::UseEmplaceCheck>(
"hicpp-use-emplace");
CheckFactories.registerCheck<modernize::UseEqualsDefaultCheck>(
"hicpp-use-equals-default");
CheckFactories.registerCheck<modernize::UseEqualsDeleteCheck>(
"hicpp-use-equals-delete");
CheckFactories.registerCheck<modernize::UseNoexceptCheck>(
"hicpp-use-noexcept");
CheckFactories.registerCheck<modernize::UseNullptrCheck>(
"hicpp-use-nullptr");
CheckFactories.registerCheck<modernize::UseOverrideCheck>(
"hicpp-use-override");
CheckFactories.registerCheck<cppcoreguidelines::ProTypeVarargCheck>(
"hicpp-vararg");
}
};

View File

@@ -1,96 +0,0 @@
//===--- SignedBitwiseCheck.cpp - clang-tidy-------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "SignedBitwiseCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
using namespace clang::ast_matchers;
using namespace clang::ast_matchers::internal;
namespace clang {
namespace tidy {
namespace hicpp {
void SignedBitwiseCheck::registerMatchers(MatchFinder *Finder) {
const auto SignedIntegerOperand =
expr(ignoringImpCasts(hasType(isSignedInteger()))).bind("signed-operand");
// The standard [bitmask.types] allows some integral types to be implemented
// as signed types. Exclude these types from diagnosing for bitwise or(|) and
// bitwise and(&). Shifting and complementing such values is still not
// allowed.
const auto BitmaskType = namedDecl(anyOf(
hasName("::std::locale::category"), hasName("::std::ctype_base::mask"),
hasName("::std::ios_base::fmtflags"), hasName("::std::ios_base::iostate"),
hasName("::std::ios_base::openmode")));
const auto IsStdBitmask = ignoringImpCasts(declRefExpr(hasType(BitmaskType)));
// Match binary bitwise operations on signed integer arguments.
Finder->addMatcher(
binaryOperator(
allOf(anyOf(hasOperatorName("^"), hasOperatorName("|"),
hasOperatorName("&")),
unless(allOf(hasLHS(IsStdBitmask), hasRHS(IsStdBitmask))),
hasEitherOperand(SignedIntegerOperand),
hasLHS(hasType(isInteger())), hasRHS(hasType(isInteger()))))
.bind("binary-no-sign-interference"),
this);
// Shifting and complement is not allowed for any signed integer type because
// the sign bit may corrupt the result.
Finder->addMatcher(
binaryOperator(allOf(anyOf(hasOperatorName("<<"), hasOperatorName(">>")),
hasEitherOperand(SignedIntegerOperand),
hasLHS(hasType(isInteger())),
hasRHS(hasType(isInteger()))))
.bind("binary-sign-interference"),
this);
// Match unary operations on signed integer types.
Finder->addMatcher(unaryOperator(allOf(hasOperatorName("~"),
hasUnaryOperand(SignedIntegerOperand)))
.bind("unary-signed"),
this);
}
void SignedBitwiseCheck::check(const MatchFinder::MatchResult &Result) {
const ast_matchers::BoundNodes &N = Result.Nodes;
const auto *SignedOperand = N.getNodeAs<Expr>("signed-operand");
assert(SignedOperand &&
"No signed operand found in problematic bitwise operations");
bool IsUnary = false;
SourceLocation Location;
if (const auto *UnaryOp = N.getNodeAs<UnaryOperator>("unary-signed")) {
IsUnary = true;
Location = UnaryOp->getLocStart();
} else {
if (const auto *BinaryOp =
N.getNodeAs<BinaryOperator>("binary-no-sign-interference"))
Location = BinaryOp->getLocStart();
else if (const auto *BinaryOp =
N.getNodeAs<BinaryOperator>("binary-sign-interference"))
Location = BinaryOp->getLocStart();
else
llvm_unreachable("unexpected matcher result");
}
diag(Location,
"use of a signed integer operand with a %select{binary|unary}0 bitwise "
"operator")
<< IsUnary << SignedOperand->getSourceRange();
}
} // namespace hicpp
} // namespace tidy
} // namespace clang

View File

@@ -1,36 +0,0 @@
//===--- SignedBitwiseCheck.h - clang-tidy-----------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_HICPP_SIGNED_BITWISE_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_HICPP_SIGNED_BITWISE_H
#include "../ClangTidy.h"
namespace clang {
namespace tidy {
namespace hicpp {
/// This check implements the rule 5.6.1 of the HICPP Standard, which disallows
/// bitwise operations on signed integer types.
///
/// For the user-facing documentation see:
/// http://clang.llvm.org/extra/clang-tidy/checks/hicpp-signed-bitwise.html
class SignedBitwiseCheck : public ClangTidyCheck {
public:
SignedBitwiseCheck(StringRef Name, ClangTidyContext *Context)
: ClangTidyCheck(Name, Context) {}
void registerMatchers(ast_matchers::MatchFinder *Finder) override;
void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
};
} // namespace hicpp
} // namespace tidy
} // namespace clang
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_HICPP_SIGNED_BITWISE_H

View File

@@ -15,7 +15,20 @@ namespace llvm {
LLVMHeaderGuardCheck::LLVMHeaderGuardCheck(StringRef Name,
ClangTidyContext *Context)
: HeaderGuardCheck(Name, Context) {}
: HeaderGuardCheck(Name, Context),
RawStringHeaderFileExtensions(
Options.getLocalOrGlobal("HeaderFileExtensions", ",h,hh,hpp,hxx")) {
utils::parseHeaderFileExtensions(RawStringHeaderFileExtensions,
HeaderFileExtensions, ',');
}
void LLVMHeaderGuardCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
Options.store(Opts, "HeaderFileExtensions", RawStringHeaderFileExtensions);
}
bool LLVMHeaderGuardCheck::shouldFixHeaderGuard(StringRef FileName) {
return utils::isHeaderFileExtension(FileName, HeaderFileExtensions);
}
std::string LLVMHeaderGuardCheck::getHeaderGuard(StringRef Filename,
StringRef OldGuard) {

View File

@@ -29,8 +29,14 @@ class LLVMHeaderGuardCheck : public utils::HeaderGuardCheck {
public:
LLVMHeaderGuardCheck(StringRef Name, ClangTidyContext *Context);
void storeOptions(ClangTidyOptions::OptionMap &Opts) override;
bool shouldSuggestEndifComment(StringRef Filename) override { return false; }
bool shouldFixHeaderGuard(StringRef Filename) override;
std::string getHeaderGuard(StringRef Filename, StringRef OldGuard) override;
private:
std::string RawStringHeaderFileExtensions;
utils::HeaderFileExtensionsSet HeaderFileExtensions;
};
} // namespace llvm

View File

@@ -18,7 +18,7 @@ using namespace clang::ast_matchers;
namespace clang {
namespace tidy {
namespace bugprone {
namespace misc {
ArgumentCommentCheck::ArgumentCommentCheck(StringRef Name,
ClangTidyContext *Context)
@@ -303,6 +303,6 @@ void ArgumentCommentCheck::check(const MatchFinder::MatchResult &Result) {
}
}
} // namespace bugprone
} // namespace misc
} // namespace tidy
} // namespace clang

View File

@@ -7,15 +7,15 @@
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_ARGUMENTCOMMENTCHECK_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_ARGUMENTCOMMENTCHECK_H
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_ARGUMENTCOMMENTCHECK_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_ARGUMENTCOMMENTCHECK_H
#include "../ClangTidy.h"
#include "llvm/Support/Regex.h"
namespace clang {
namespace tidy {
namespace bugprone {
namespace misc {
/// Checks that argument comments match parameter names.
///
@@ -48,8 +48,8 @@ private:
llvm::ArrayRef<const Expr *> Args);
};
} // namespace bugprone
} // namespace misc
} // namespace tidy
} // namespace clang
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_ARGUMENTCOMMENTCHECK_H
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_ARGUMENTCOMMENTCHECK_H

View File

@@ -22,7 +22,7 @@ using namespace clang::ast_matchers;
namespace clang {
namespace tidy {
namespace bugprone {
namespace misc {
namespace {
@@ -122,6 +122,6 @@ void AssertSideEffectCheck::check(const MatchFinder::MatchResult &Result) {
diag(Loc, "found %0() with side effect") << AssertMacroName;
}
} // namespace bugprone
} // namespace misc
} // namespace tidy
} // namespace clang

View File

@@ -7,8 +7,8 @@
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_ASSERTSIDEEFFECTCHECK_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_ASSERTSIDEEFFECTCHECK_H
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_ASSERTSIDEEFFECTCHECK_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_ASSERTSIDEEFFECTCHECK_H
#include "../ClangTidy.h"
#include "llvm/ADT/SmallVector.h"
@@ -17,7 +17,7 @@
namespace clang {
namespace tidy {
namespace bugprone {
namespace misc {
/// Finds `assert()` with side effect.
///
@@ -45,8 +45,8 @@ private:
SmallVector<StringRef, 5> AssertMacros;
};
} // namespace bugprone
} // namespace misc
} // namespace tidy
} // namespace clang
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_ASSERTSIDEEFFECTCHECK_H
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_ASSERTSIDEEFFECTCHECK_H

View File

@@ -13,7 +13,7 @@ using namespace clang::ast_matchers;
namespace clang {
namespace tidy {
namespace bugprone {
namespace misc {
void BoolPointerImplicitConversionCheck::registerMatchers(MatchFinder *Finder) {
// Look for ifs that have an implicit bool* to bool conversion in the
@@ -68,6 +68,6 @@ void BoolPointerImplicitConversionCheck::check(
<< FixItHint::CreateInsertion(Var->getLocStart(), "*");
}
} // namespace bugprone
} // namespace misc
} // namespace tidy
} // namespace clang

View File

@@ -7,14 +7,14 @@
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_BOOLPOINTERIMPLICITCONVERSIONCHECK_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_BOOLPOINTERIMPLICITCONVERSIONCHECK_H
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_BOOLPOINTERIMPLICITCONVERSIONCHECK_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_BOOLPOINTERIMPLICITCONVERSIONCHECK_H
#include "../ClangTidy.h"
namespace clang {
namespace tidy {
namespace bugprone {
namespace misc {
/// Checks for conditions based on implicit conversion from a bool pointer to
/// bool.
@@ -35,8 +35,8 @@ public:
void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
};
} // namespace bugprone
} // namespace misc
} // namespace tidy
} // namespace clang
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_BOOLPOINTERIMPLICITCONVERSIONCHECK_H
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_BOOLPOINTERIMPLICITCONVERSIONCHECK_H

View File

@@ -1,23 +1,37 @@
set(LLVM_LINK_COMPONENTS support)
add_clang_library(clangTidyMiscModule
ArgumentCommentCheck.cpp
AssertSideEffectCheck.cpp
ForwardingReferenceOverloadCheck.cpp
LambdaFunctionNameCheck.cpp
MisplacedConstCheck.cpp
UnconventionalAssignOperatorCheck.cpp
BoolPointerImplicitConversionCheck.cpp
DanglingHandleCheck.cpp
DefinitionsInHeadersCheck.cpp
FoldInitTypeCheck.cpp
ForwardDeclarationNamespaceCheck.cpp
InaccurateEraseCheck.cpp
IncorrectRoundings.cpp
InefficientAlgorithmCheck.cpp
MacroParenthesesCheck.cpp
MacroRepeatedSideEffectsCheck.cpp
MiscTidyModule.cpp
MisplacedWideningCastCheck.cpp
MoveConstantArgumentCheck.cpp
MoveConstructorInitCheck.cpp
MoveForwardingReferenceCheck.cpp
MultipleStatementMacroCheck.cpp
NewDeleteOverloadsCheck.cpp
NoexceptMoveConstructorCheck.cpp
NonCopyableObjects.cpp
RedundantExpressionCheck.cpp
SizeofContainerCheck.cpp
SizeofExpressionCheck.cpp
StaticAssertCheck.cpp
StringCompareCheck.cpp
StringConstructorCheck.cpp
StringIntegerAssignmentCheck.cpp
StringLiteralWithEmbeddedNulCheck.cpp
SuspiciousEnumUsageCheck.cpp
@@ -32,6 +46,8 @@ add_clang_library(clangTidyMiscModule
UnusedParametersCheck.cpp
UnusedRAIICheck.cpp
UnusedUsingDeclsCheck.cpp
UseAfterMoveCheck.cpp
VirtualNearMissCheck.cpp
LINK_LIBS
clangAnalysis

View File

@@ -18,7 +18,7 @@ using namespace clang::tidy::matchers;
namespace clang {
namespace tidy {
namespace bugprone {
namespace misc {
namespace {
@@ -71,13 +71,11 @@ ast_matchers::internal::BindableMatcher<Stmt> makeContainerMatcher(
// For sequences: assign, push_back, resize.
cxxMemberCallExpr(
callee(functionDecl(hasAnyName("assign", "push_back", "resize"))),
on(expr(hasType(hasUnqualifiedDesugaredType(
recordType(hasDeclaration(recordDecl(isASequence())))))))),
on(expr(hasType(recordDecl(isASequence()))))),
// For sequences and sets: insert.
cxxMemberCallExpr(callee(functionDecl(hasName("insert"))),
on(expr(hasType(hasUnqualifiedDesugaredType(
recordType(hasDeclaration(recordDecl(
anyOf(isASequence(), isASet()))))))))),
cxxMemberCallExpr(
callee(functionDecl(hasName("insert"))),
on(expr(hasType(recordDecl(anyOf(isASequence(), isASet())))))),
// For maps: operator[].
cxxOperatorCallExpr(callee(cxxMethodDecl(ofClass(isAMap()))),
hasOverloadedOperatorName("[]"))));
@@ -105,8 +103,7 @@ void DanglingHandleCheck::registerMatchersForVariables(MatchFinder *Finder) {
// Find 'Handle foo(ReturnsAValue());'
Finder->addMatcher(
varDecl(hasType(hasUnqualifiedDesugaredType(
recordType(hasDeclaration(cxxRecordDecl(IsAHandle))))),
varDecl(hasType(cxxRecordDecl(IsAHandle)),
hasInitializer(
exprWithCleanups(has(ignoringParenImpCasts(ConvertedHandle)))
.bind("bad_stmt"))),
@@ -115,9 +112,7 @@ void DanglingHandleCheck::registerMatchersForVariables(MatchFinder *Finder) {
// Find 'Handle foo = ReturnsAValue();'
Finder->addMatcher(
varDecl(
hasType(hasUnqualifiedDesugaredType(
recordType(hasDeclaration(cxxRecordDecl(IsAHandle))))),
unless(parmVarDecl()),
hasType(cxxRecordDecl(IsAHandle)), unless(parmVarDecl()),
hasInitializer(exprWithCleanups(has(ignoringParenImpCasts(handleFrom(
IsAHandle, ConvertedHandle))))
.bind("bad_stmt"))),
@@ -144,15 +139,13 @@ void DanglingHandleCheck::registerMatchersForReturn(MatchFinder *Finder) {
// We have to match both.
has(ignoringImplicit(handleFrom(
IsAHandle,
handleFrom(IsAHandle,
declRefExpr(to(varDecl(
// Is function scope ...
hasAutomaticStorageDuration(),
// ... and it is a local array or Value.
anyOf(hasType(arrayType()),
hasType(hasUnqualifiedDesugaredType(
recordType(hasDeclaration(recordDecl(
unless(IsAHandle)))))))))))))),
handleFrom(IsAHandle, declRefExpr(to(varDecl(
// Is function scope ...
hasAutomaticStorageDuration(),
// ... and it is a local array or Value.
anyOf(hasType(arrayType()),
hasType(recordDecl(
unless(IsAHandle))))))))))),
// Temporary fix for false positives inside lambdas.
unless(hasAncestor(lambdaExpr())))
.bind("bad_stmt"),
@@ -179,6 +172,6 @@ void DanglingHandleCheck::check(const MatchFinder::MatchResult &Result) {
<< Handle->getQualifiedNameAsString();
}
} // namespace bugprone
} // namespace misc
} // namespace tidy
} // namespace clang

View File

@@ -7,20 +7,20 @@
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_DANGLING_HANDLE_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_DANGLING_HANDLE_H
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_DANGLING_HANDLE_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_DANGLING_HANDLE_H
#include "../ClangTidy.h"
namespace clang {
namespace tidy {
namespace bugprone {
namespace misc {
/// Detect dangling references in value handlers like
/// std::experimental::string_view.
///
/// For the user-facing documentation see:
/// http://clang.llvm.org/extra/clang-tidy/checks/bugprone-dangling-handle.html
/// http://clang.llvm.org/extra/clang-tidy/checks/misc-dangling-handle.html
class DanglingHandleCheck : public ClangTidyCheck {
public:
DanglingHandleCheck(StringRef Name, ClangTidyContext *Context);
@@ -36,8 +36,8 @@ private:
const ast_matchers::internal::Matcher<RecordDecl> IsAHandle;
};
} // namespace bugprone
} // namespace misc
} // namespace tidy
} // namespace clang
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_DANGLING_HANDLE_H
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_DANGLING_HANDLE_H

View File

@@ -32,8 +32,8 @@ DefinitionsInHeadersCheck::DefinitionsInHeadersCheck(StringRef Name,
ClangTidyContext *Context)
: ClangTidyCheck(Name, Context),
UseHeaderFileExtension(Options.get("UseHeaderFileExtension", true)),
RawStringHeaderFileExtensions(Options.getLocalOrGlobal(
"HeaderFileExtensions", utils::defaultHeaderFileExtensions())) {
RawStringHeaderFileExtensions(
Options.getLocalOrGlobal("HeaderFileExtensions", ",h,hh,hpp,hxx")) {
if (!utils::parseHeaderFileExtensions(RawStringHeaderFileExtensions,
HeaderFileExtensions, ',')) {
// FIXME: Find a more suitable way to handle invalid configuration
@@ -94,10 +94,7 @@ void DefinitionsInHeadersCheck::check(const MatchFinder::MatchResult &Result) {
//
// Although these might also cause ODR violations, we can be less certain and
// should try to keep the false-positive rate down.
//
// FIXME: Should declarations in anonymous namespaces get the same treatment
// as static / const declarations?
if (!ND->hasExternalFormalLinkage() && !ND->isInAnonymousNamespace())
if (ND->getLinkageInternal() == InternalLinkage)
return;
if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {

View File

@@ -15,7 +15,7 @@ using namespace clang::ast_matchers;
namespace clang {
namespace tidy {
namespace bugprone {
namespace misc {
void FoldInitTypeCheck::registerMatchers(MatchFinder *Finder) {
// We match functions of interest and bind the iterator and init value types.
@@ -135,6 +135,6 @@ void FoldInitTypeCheck::check(const MatchFinder::MatchResult &Result) {
doCheck(*Iter2ValueType, *InitType, *Result.Context, *CallNode);
}
} // namespace bugprone
} // namespace misc
} // namespace tidy
} // namespace clang

View File

@@ -7,14 +7,14 @@
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_FOLD_INIT_TYPE_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_FOLD_INIT_TYPE_H
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_FOLD_INIT_TYPE_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_FOLD_INIT_TYPE_H
#include "../ClangTidy.h"
namespace clang {
namespace tidy {
namespace bugprone {
namespace misc {
/// Find and flag invalid initializer values in folds, e.g. std::accumulate.
/// Example:
@@ -24,7 +24,7 @@ namespace bugprone {
/// \endcode
///
/// For the user-facing documentation see:
/// http://clang.llvm.org/extra/clang-tidy/checks/bugprone-fold-init-type.html
/// http://clang.llvm.org/extra/clang-tidy/checks/misc-fold-init-type.html
class FoldInitTypeCheck : public ClangTidyCheck {
public:
FoldInitTypeCheck(StringRef Name, ClangTidyContext *Context)
@@ -37,8 +37,8 @@ private:
const ASTContext &Context, const CallExpr &CallNode);
};
} // namespace bugprone
} // namespace misc
} // namespace tidy
} // namespace clang
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_FOLD_INIT_TYPE_H
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_FOLD_INIT_TYPE_H

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