[PATCH] D97577: [clang-tidy] performance-for-range-copy: Don't trigger on implicit type conversions.

2021-02-26 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

It is best not to change existing tests, but add new ones.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97577/new/

https://reviews.llvm.org/D97577

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D96803: EntryExitInstrumenter: Enable at all optimization levels (PR49143)

2021-02-26 Thread Arthur Eubanks via Phabricator via cfe-commits
aeubanks added a comment.

Alternatively: https://reviews.llvm.org/D97608


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D96803/new/

https://reviews.llvm.org/D96803

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D97608: Move EntryExitInstrumentation pass location

2021-02-26 Thread Arthur Eubanks via Phabricator via cfe-commits
aeubanks created this revision.
Herald added subscribers: nikic, pengfei, hiraditya.
aeubanks requested review of this revision.
Herald added projects: clang, LLVM.
Herald added subscribers: llvm-commits, cfe-commits.

This seems to be more of a Clang thing rather than a generic LLVM thing,
so this moves it out of LLVM pipelines and as Clang extension hooks into
LLVM pipelines.

Move the post-inline EEInstrumentation out of the backend pipeline and
into a late pass, similar to other sanitizer passes. It doesn't fit
into the codegen pipeline.

Also fix up EntryExitInstrumentation not running at -O0 under the new
PM. PR49143


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D97608

Files:
  clang/lib/CodeGen/BackendUtil.cpp
  clang/test/CodeGen/X86/x86_64-instrument-functions.c
  clang/test/CodeGen/mcount.c
  llvm/include/llvm/Transforms/Utils/EntryExitInstrumenter.h
  llvm/lib/CodeGen/TargetPassConfig.cpp
  llvm/lib/Transforms/IPO/PassManagerBuilder.cpp
  llvm/test/CodeGen/X86/O0-pipeline.ll
  llvm/test/CodeGen/X86/musttail-inalloca.ll
  llvm/test/CodeGen/X86/opt-pipeline.ll
  llvm/test/Other/opt-O0-pipeline-enable-matrix.ll
  llvm/test/Other/opt-O0-pipeline.ll
  llvm/test/Other/opt-O2-pipeline.ll
  llvm/test/Other/opt-O3-pipeline-enable-matrix.ll
  llvm/test/Other/opt-O3-pipeline.ll
  llvm/test/Other/opt-Os-pipeline.ll

Index: llvm/test/Other/opt-Os-pipeline.ll
===
--- llvm/test/Other/opt-Os-pipeline.ll
+++ llvm/test/Other/opt-Os-pipeline.ll
@@ -12,7 +12,6 @@
 ; CHECK-NEXT: Module Verifier
 ; CHECK-EXT:  Good Bye World Pass
 ; CHECK-NOEXT-NOT:  Good Bye World Pass
-; CHECK-NEXT: Instrument function entry/exit with calls to e.g. mcount() (pre inlining)
 ; CHECK-NEXT: Simplify the CFG
 ; CHECK-NEXT: Dominator Tree Construction
 ; CHECK-NEXT: SROA
Index: llvm/test/Other/opt-O3-pipeline.ll
===
--- llvm/test/Other/opt-O3-pipeline.ll
+++ llvm/test/Other/opt-O3-pipeline.ll
@@ -12,7 +12,6 @@
 ; CHECK-NEXT: Module Verifier
 ; CHECK-EXT:  Good Bye World Pass
 ; CHECK-NOEXT-NOT:  Good Bye World Pass
-; CHECK-NEXT: Instrument function entry/exit with calls to e.g. mcount() (pre inlining)
 ; CHECK-NEXT: Simplify the CFG
 ; CHECK-NEXT: Dominator Tree Construction
 ; CHECK-NEXT: SROA
Index: llvm/test/Other/opt-O3-pipeline-enable-matrix.ll
===
--- llvm/test/Other/opt-O3-pipeline-enable-matrix.ll
+++ llvm/test/Other/opt-O3-pipeline-enable-matrix.ll
@@ -12,7 +12,6 @@
 ; CHECK-NEXT: Module Verifier
 ; CHECK-EXT:  Good Bye World Pass
 ; CHECK-NOEXT-NOT:  Good Bye World Pass
-; CHECK-NEXT: Instrument function entry/exit with calls to e.g. mcount() (pre inlining)
 ; CHECK-NEXT: Simplify the CFG
 ; CHECK-NEXT: Dominator Tree Construction
 ; CHECK-NEXT: SROA
Index: llvm/test/Other/opt-O2-pipeline.ll
===
--- llvm/test/Other/opt-O2-pipeline.ll
+++ llvm/test/Other/opt-O2-pipeline.ll
@@ -12,7 +12,6 @@
 ; CHECK-NEXT: Module Verifier
 ; CHECK-EXT:  Good Bye World Pass
 ; CHECK-NOEXT-NOT:  Good Bye World Pass
-; CHECK-NEXT: Instrument function entry/exit with calls to e.g. mcount() (pre inlining)
 ; CHECK-NEXT: Simplify the CFG
 ; CHECK-NEXT: Dominator Tree Construction
 ; CHECK-NEXT: SROA
Index: llvm/test/Other/opt-O0-pipeline.ll
===
--- llvm/test/Other/opt-O0-pipeline.ll
+++ llvm/test/Other/opt-O0-pipeline.ll
@@ -10,7 +10,6 @@
 ; CHECK-NEXT:   FunctionPass Manager
 ; CHECK-NEXT: Module Verifier
 ; CHECK-EXT: Good Bye World Pass
-; CHECK-NEXT: Instrument function entry/exit with calls to e.g. mcount() (pre inlining)
 ; CHECK-NEXT: Pass Arguments:
 ; CHECK-NEXT: Target Library Information
 ; CHECK-NEXT: Target Transform Information
Index: llvm/test/Other/opt-O0-pipeline-enable-matrix.ll
===
--- llvm/test/Other/opt-O0-pipeline-enable-matrix.ll
+++ llvm/test/Other/opt-O0-pipeline-enable-matrix.ll
@@ -6,7 +6,6 @@
 ; CHECK-NEXT: Target Transform Information
 ; CHECK-NEXT:   FunctionPass Manager
 ; CHECK-NEXT: Module Verifier
-; CHECK-NEXT: Instrument function entry/exit with calls to e.g. mcount() (pre inlining)
 ; CHECK-NEXT: Lower the matrix intrinsics (minimal)
 
 
Index: llvm/test/CodeGen/X86/opt-pipeline.ll
===
--- llvm/test/CodeGen/X86/opt-pipeline.ll
+++ llvm/test/CodeGen/X86/opt-pipeline.ll
@@ -53,7 +53,6 @@
 ; CHECK-NEXT:   Constant Hoisting
 ; CHECK-NEXT:   Replace intrinsics with calls to vector library
 ; CHECK-NEXT:   Partially inline calls to library functions
-; CHECK-NEXT:   Instrument function entry/exit with calls to 

[clang] 2e2ee43 - [test] Add -triple x86_64 to attr-retain.cpp

2021-02-26 Thread Fangrui Song via cfe-commits

Author: Fangrui Song
Date: 2021-02-26T19:35:53-08:00
New Revision: 2e2ee4300d1f9766209d435c0d8c44c72092b974

URL: 
https://github.com/llvm/llvm-project/commit/2e2ee4300d1f9766209d435c0d8c44c72092b974
DIFF: 
https://github.com/llvm/llvm-project/commit/2e2ee4300d1f9766209d435c0d8c44c72092b974.diff

LOG: [test] Add -triple x86_64 to attr-retain.cpp

Added: 


Modified: 
clang/test/CodeGenCXX/attr-retain.cpp

Removed: 




diff  --git a/clang/test/CodeGenCXX/attr-retain.cpp 
b/clang/test/CodeGenCXX/attr-retain.cpp
index 0bc1a4c95abb..9f7000b6fbf4 100644
--- a/clang/test/CodeGenCXX/attr-retain.cpp
+++ b/clang/test/CodeGenCXX/attr-retain.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -emit-llvm -triple %itanium_abi_triple -Werror %s -o - | 
FileCheck %s
+// RUN: %clang_cc1 -emit-llvm -triple x86_64 -Werror %s -o - | FileCheck %s
 
 // CHECK:  @llvm.used = appending global [7 x i8*]
 // CHECK-SAME:   @_ZN2X0C2Ev



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D97606: [Clang interpreter] Avoid storing pointers at unaligned locations

2021-02-26 Thread Jessica Clarke via Phabricator via cfe-commits
jrtc27 added a comment.

Is there any way I can usefully test this? As far as I can tell there's only a 
single constexpr test in the tree that uses the new interpreter, and it's 
pretty trivial?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97606/new/

https://reviews.llvm.org/D97606

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D64146: [Clang Interpreter] Initial patch for the constexpr interpreter

2021-02-26 Thread Jessica Clarke via Phabricator via cfe-commits
jrtc27 added a comment.

In D64146#2591830 , @jrtc27 wrote:

> In D64146#2591732 , @jrtc27 wrote:
>
>> In D64146#2567710 , @nand wrote:
>>
>>> CodePtr points into the bytecode emitted by the byte code compiler. In some 
>>> instances, pointers to auxiliary data structures are embedded into the byte 
>>> code, such as functions or AST nodes which contain information relevant to 
>>> the execution of the instruction.
>>>
>>> Would it help if instead of encoding pointers, the byte code encoded some 
>>> integers mapped to the original objects?
>>
>> I've read through the code and have slightly more understanding now. It 
>> seems there are several options:
>>
>> 1. Keep the pointers somewhere on the side and put an integer in the byte 
>> code, like you suggest
>>
>> 2. Pad values in the byte code to their natural alignment in general (and 
>> ensure the underlying std::vector gets its storage allocated at an 
>> aligned boundary / use a different container), though this can get a little 
>> weird as the amount of padding between consecutive arguments varies 
>> depending on where you are (unless you force realignment to the max 
>> alignment at the start of a new opcode)
>>
>> 3. Make the byte code be an array of uintptr_t instead of packing it like is 
>> done currently, with care needed on ILP32; that can either just use uint64_t 
>> instead and we declare CHERI unsupported for 32-bit architectures (which is 
>> unlikely to be a problem as you probably want a 64-bit virtual address space 
>> if the doubling pointer size, with 64-bit CHERI capabilities on 32-bit VA 
>> systems being only for embedded use) or you can split 64-bit integers into 
>> two 32-bit integers and treat them as two arguments
>>
>> 1 works but feels ugly. 2 or 3 would be my preference, and mirror how 
>> "normal" interpreters work, though those might split the code and data so 
>> they can keep the opcodes as, say, 32-bit integers, but the stack full of 
>> native word/pointer slots; my inclination is that 3 is the best option as it 
>> looks like the simplest. How do you feel about each of those? Is memory 
>> overhead from not packing values a concern?
>
> Hm, though I see the "store an ID" pattern is common for dynamic things and 
> this should be quite rare, so maybe that is indeed the right approach, 
> mirroring something like getOrCreateGlobal?

https://reviews.llvm.org/D97606 implements this.


Repository:
  rL LLVM

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D64146/new/

https://reviews.llvm.org/D64146

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D97606: [Clang interpreter] Avoid storing pointers at unaligned locations

2021-02-26 Thread Jessica Clarke via Phabricator via cfe-commits
jrtc27 updated this revision to Diff 326872.
jrtc27 added a comment.

Reworked code slightly to make it look nicer after clang-format uglified it


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97606/new/

https://reviews.llvm.org/D97606

Files:
  clang/lib/AST/Interp/ByteCodeEmitter.cpp
  clang/lib/AST/Interp/Disasm.cpp
  clang/lib/AST/Interp/Interp.h
  clang/lib/AST/Interp/Program.cpp
  clang/lib/AST/Interp/Program.h
  clang/lib/AST/Interp/Source.h
  clang/utils/TableGen/ClangOpcodesEmitter.cpp

Index: clang/utils/TableGen/ClangOpcodesEmitter.cpp
===
--- clang/utils/TableGen/ClangOpcodesEmitter.cpp
+++ clang/utils/TableGen/ClangOpcodesEmitter.cpp
@@ -124,7 +124,7 @@
 for (size_t I = 0, N = Args.size(); I < N; ++I) {
   OS << "  auto V" << I;
   OS << " = ";
-  OS << "PC.read<" << Args[I]->getValueAsString("Name") << ">();\n";
+  OS << "ReadArg<" << Args[I]->getValueAsString("Name") << ">(S, PC);\n";
 }
 
 // Emit a call to the template method and pass arguments.
@@ -161,8 +161,10 @@
 OS << "  PrintName(\"" << ID << "\");\n";
 OS << "  OS << \"\\t\"";
 
-for (auto *Arg : R->getValueAsListOfDefs("Args"))
-  OS << " << PC.read<" << Arg->getValueAsString("Name") << ">() << \" \"";
+for (auto *Arg : R->getValueAsListOfDefs("Args")) {
+  OS << " << ReadArg<" << Arg->getValueAsString("Name") << ">(P, PC)";
+  OS << " << \" \"";
+}
 
 OS << " << \"\\n\";\n";
 OS << "  continue;\n";
Index: clang/lib/AST/Interp/Source.h
===
--- clang/lib/AST/Interp/Source.h
+++ clang/lib/AST/Interp/Source.h
@@ -44,8 +44,9 @@
   bool operator!=(const CodePtr ) const { return Ptr != RHS.Ptr; }
 
   /// Reads data and advances the pointer.
-  template  T read() {
-T Value = ReadHelper(Ptr);
+  template  std::enable_if_t::value, T> read() {
+using namespace llvm::support;
+T Value = endian::read(Ptr);
 Ptr += sizeof(T);
 return Value;
   }
@@ -54,22 +55,6 @@
   /// Constructor used by Function to generate pointers.
   CodePtr(const char *Ptr) : Ptr(Ptr) {}
 
-  /// Helper to decode a value or a pointer.
-  template 
-  static std::enable_if_t::value, T>
-  ReadHelper(const char *Ptr) {
-using namespace llvm::support;
-return endian::read(Ptr);
-  }
-
-  template 
-  static std::enable_if_t::value, T>
-  ReadHelper(const char *Ptr) {
-using namespace llvm::support;
-auto Punned = endian::read(Ptr);
-return reinterpret_cast(Punned);
-  }
-
 private:
   friend class Function;
 
Index: clang/lib/AST/Interp/Program.h
===
--- clang/lib/AST/Interp/Program.h
+++ clang/lib/AST/Interp/Program.h
@@ -44,6 +44,12 @@
 public:
   Program(Context ) : Ctx(Ctx) {}
 
+  /// Marshals a native pointer to an ID for embedding in bytecode.
+  unsigned getOrCreateNativePointer(const void *Ptr);
+
+  /// Returns the value of a marshalled native pointer.
+  const void *getNativePointer(unsigned Idx);
+
   /// Emits a string literal among global data.
   unsigned createGlobalString(const StringLiteral *S);
 
@@ -143,6 +149,11 @@
   /// Function relocation locations.
   llvm::DenseMap> Relocs;
 
+  /// Native pointers referenced by bytecode.
+  std::vector NativePointers;
+  /// Cached native pointer indices.
+  llvm::DenseMap NativePointerIndices;
+
   /// Custom allocator for global storage.
   using PoolAllocTy = llvm::BumpPtrAllocatorImpl;
 
Index: clang/lib/AST/Interp/Program.cpp
===
--- clang/lib/AST/Interp/Program.cpp
+++ clang/lib/AST/Interp/Program.cpp
@@ -18,6 +18,21 @@
 using namespace clang;
 using namespace clang::interp;
 
+unsigned Program::getOrCreateNativePointer(const void *Ptr) {
+  auto It = NativePointerIndices.find(Ptr);
+  if (It != NativePointerIndices.end())
+return It->second;
+
+  unsigned Idx = NativePointers.size();
+  NativePointers.push_back(Ptr);
+  NativePointerIndices[Ptr] = Idx;
+  return Idx;
+}
+
+const void *Program::getNativePointer(unsigned Idx) {
+  return NativePointers[Idx];
+}
+
 unsigned Program::createGlobalString(const StringLiteral *S) {
   const size_t CharWidth = S->getCharByteWidth();
   const size_t BitWidth = CharWidth * Ctx.getCharBit();
Index: clang/lib/AST/Interp/Interp.h
===
--- clang/lib/AST/Interp/Interp.h
+++ clang/lib/AST/Interp/Interp.h
@@ -13,8 +13,6 @@
 #ifndef LLVM_CLANG_AST_INTERP_INTERP_H
 #define LLVM_CLANG_AST_INTERP_INTERP_H
 
-#include 
-#include 
 #include "Function.h"
 #include "InterpFrame.h"
 #include "InterpStack.h"
@@ -30,6 +28,9 @@
 #include "llvm/ADT/APFloat.h"
 #include "llvm/ADT/APSInt.h"
 #include "llvm/Support/Endian.h"
+#include 
+#include 
+#include 
 
 namespace clang {
 namespace interp {
@@ -948,6 +949,23 

[PATCH] D97449: [Diagnose] Unify MCContext and LLVMContext diagnosing

2021-02-26 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added inline comments.



Comment at: clang/lib/CodeGen/CodeGenAction.cpp:477
+  StringRef Message = D.getMessage();
+  if (Message.startswith("error: "))
+Message = Message.substr(7);

`StringRef::consume_front`

I know you are moving code, but do you know why it needs to chop off the 
`error: ` prefix (why does the message get a prefix here?)


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97449/new/

https://reviews.llvm.org/D97449

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D97606: [Clang interpreter] Avoid storing pointers at unaligned locations

2021-02-26 Thread Jessica Clarke via Phabricator via cfe-commits
jrtc27 created this revision.
jrtc27 added reviewers: nand, jfb, Bigcheese, rsmith, dexonsmith.
Herald added subscribers: kristof.beyls, arichardson.
jrtc27 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

The Clang interpreter's bytecode uses a packed stream of bytes
representation, but also wants to have some opcodes take pointers as
arguments, which are currently embedded in the bytecode directly.

However, CHERI, and thus Arm's upcoming experimental Morello prototype,
provide spatial memory safety for C/C++ by implementing language-level
(and sub-language-level) pointers as capabilities, which track bounds,
permissions and validity in hardware. This uses tagged memory with a
single tag bit at every capability-aligned address, and so storing
pointers to unaligned addresses results in the tag being stripped,
leading to a tag fault when the pointer is ultimately dereferenced at a
later point.

In order to support a stricter C/C++ implementation like CHERI, we no
longer store pointers directly in the bytecode, instead storing them in
a table and embedding the index in the bytecode.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D97606

Files:
  clang/lib/AST/Interp/ByteCodeEmitter.cpp
  clang/lib/AST/Interp/Disasm.cpp
  clang/lib/AST/Interp/Interp.h
  clang/lib/AST/Interp/Program.cpp
  clang/lib/AST/Interp/Program.h
  clang/lib/AST/Interp/Source.h
  clang/utils/TableGen/ClangOpcodesEmitter.cpp

Index: clang/utils/TableGen/ClangOpcodesEmitter.cpp
===
--- clang/utils/TableGen/ClangOpcodesEmitter.cpp
+++ clang/utils/TableGen/ClangOpcodesEmitter.cpp
@@ -124,7 +124,7 @@
 for (size_t I = 0, N = Args.size(); I < N; ++I) {
   OS << "  auto V" << I;
   OS << " = ";
-  OS << "PC.read<" << Args[I]->getValueAsString("Name") << ">();\n";
+  OS << "ReadArg<" << Args[I]->getValueAsString("Name") << ">(S, PC);\n";
 }
 
 // Emit a call to the template method and pass arguments.
@@ -162,7 +162,8 @@
 OS << "  OS << \"\\t\"";
 
 for (auto *Arg : R->getValueAsListOfDefs("Args"))
-  OS << " << PC.read<" << Arg->getValueAsString("Name") << ">() << \" \"";
+  OS << " << ReadArg<" << Arg->getValueAsString("Name")
+ << ">(P, PC) << \" \"";
 
 OS << " << \"\\n\";\n";
 OS << "  continue;\n";
Index: clang/lib/AST/Interp/Source.h
===
--- clang/lib/AST/Interp/Source.h
+++ clang/lib/AST/Interp/Source.h
@@ -44,8 +44,9 @@
   bool operator!=(const CodePtr ) const { return Ptr != RHS.Ptr; }
 
   /// Reads data and advances the pointer.
-  template  T read() {
-T Value = ReadHelper(Ptr);
+  template  std::enable_if_t::value, T> read() {
+using namespace llvm::support;
+T Value = endian::read(Ptr);
 Ptr += sizeof(T);
 return Value;
   }
@@ -54,22 +55,6 @@
   /// Constructor used by Function to generate pointers.
   CodePtr(const char *Ptr) : Ptr(Ptr) {}
 
-  /// Helper to decode a value or a pointer.
-  template 
-  static std::enable_if_t::value, T>
-  ReadHelper(const char *Ptr) {
-using namespace llvm::support;
-return endian::read(Ptr);
-  }
-
-  template 
-  static std::enable_if_t::value, T>
-  ReadHelper(const char *Ptr) {
-using namespace llvm::support;
-auto Punned = endian::read(Ptr);
-return reinterpret_cast(Punned);
-  }
-
 private:
   friend class Function;
 
Index: clang/lib/AST/Interp/Program.h
===
--- clang/lib/AST/Interp/Program.h
+++ clang/lib/AST/Interp/Program.h
@@ -44,6 +44,12 @@
 public:
   Program(Context ) : Ctx(Ctx) {}
 
+  /// Marshals a native pointer to an ID for embedding in bytecode.
+  unsigned getOrCreateNativePointer(const void *Ptr);
+
+  /// Returns the value of a marshalled native pointer.
+  const void *getNativePointer(unsigned Idx);
+
   /// Emits a string literal among global data.
   unsigned createGlobalString(const StringLiteral *S);
 
@@ -143,6 +149,11 @@
   /// Function relocation locations.
   llvm::DenseMap> Relocs;
 
+  /// Native pointers referenced by bytecode.
+  std::vector NativePointers;
+  /// Cached native pointer indices.
+  llvm::DenseMap NativePointerIndices;
+
   /// Custom allocator for global storage.
   using PoolAllocTy = llvm::BumpPtrAllocatorImpl;
 
Index: clang/lib/AST/Interp/Program.cpp
===
--- clang/lib/AST/Interp/Program.cpp
+++ clang/lib/AST/Interp/Program.cpp
@@ -18,6 +18,21 @@
 using namespace clang;
 using namespace clang::interp;
 
+unsigned Program::getOrCreateNativePointer(const void *Ptr) {
+  auto It = NativePointerIndices.find(Ptr);
+  if (It != NativePointerIndices.end())
+return It->second;
+
+  unsigned Idx = NativePointers.size();
+  NativePointers.push_back(Ptr);
+  NativePointerIndices[Ptr] = Idx;
+  return Idx;
+}
+
+const void 

[PATCH] D97449: [Diagnose] Unify MCContext and LLVMContext diagnosing

2021-02-26 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added a comment.

I am supportive of getting rid of InlineAsmDiagnosticHandler, too.

The updated AMDGPU tests suggeste that previously `MCContext::reportError` may 
be called with no `SrcMgr` or `InlineSrcMgr`, so the error is propagated to the 
temporary `SourceMgr()`. The `LLCDiagnosticHandler` does not receive anything 
so the exit code is incorrect 0.

The new behavior moves the `SrcMgr` or `InlineSrcMgr` check under `if 
(Loc.isValid()) {` (in `MCContext::reportCommon`). There is still a temporary 
`SrcMgr`. I wonder whether this can be improved.




Comment at: llvm/include/llvm/IR/DiagnosticInfo.h:1036
+  void print(DiagnosticPrinter ) const override {
+llvm_unreachable("unimplemented");
+  }

@nickdesaulniers's diagnostic means this is reachable.

Perhaps `Diagnostic.print` needs to be called with appropriate arguments.



Comment at: llvm/lib/MC/MCContext.cpp:869
+SMLoc Loc,
+std::function GetMessage) {
+  SourceMgr SM;

Use lightweight function_ref since you don't need to store the callback.



Comment at: llvm/lib/MC/MCContext.cpp:870
+std::function GetMessage) {
+  SourceMgr SM;
+  const SourceMgr *SMP = 

This looks a bit strange: we need to construct a fresh SourceMgr to print a 
diagnostic.



Comment at: llvm/test/CodeGen/AMDGPU/lds-initializer.ll:1-2
-; RUN: llc -march=amdgcn -mcpu=tahiti < %s -o /dev/null 2>&1 | FileCheck %s
-; RUN: llc -march=amdgcn -mcpu=tonga < %s -o /dev/null 2>&1 | FileCheck %s
+; RUN: not llc -march=amdgcn -mcpu=tahiti < %s -o /dev/null 2>&1 | FileCheck %s
+; RUN: not llc -march=amdgcn -mcpu=tonga < %s -o /dev/null 2>&1 | FileCheck %s
 

nickdesaulniers wrote:
> Does the addition of `not` mean that this test would have failed due to these 
> changes? How come?
This is an improvement. Errors should return non-zero. It might be clear to 
change the CHECK below to have `error:`.

In the new code, `LLCDiagnosticHandler` sets `HasError` to true.



Comment at: llvm/test/CodeGen/AMDGPU/lds-zero-initializer.ll:1
-; RUN: llc -march=amdgcn -mcpu=tahiti < %s -o /dev/null 2>&1 | FileCheck %s
-; RUN: llc -march=amdgcn -mcpu=tonga < %s -o /dev/null 2>&1 | FileCheck %s
+; RUN: not llc -march=amdgcn -mcpu=tahiti < %s -o /dev/null 2>&1 | FileCheck %s
+; RUN: not llc -march=amdgcn -mcpu=tonga < %s -o /dev/null 2>&1 | FileCheck %s

While here, `-o /dev/null` -> `-filetype=null`



Comment at: llvm/test/CodeGen/AMDGPU/lds-zero-initializer.ll:4
 
 ; CHECK: lds: unsupported initializer for address space
 

Add `error:` to make it clear this is an error.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97449/new/

https://reviews.llvm.org/D97449

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D97605: [Lifetimes] Fix false positive warning from BUG 49342

2021-02-26 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun created this revision.
xazax.hun added reviewers: rsmith, mgehre.
xazax.hun added a project: clang.
Herald added subscribers: Charusso, gamesh411, Szelethus, dkrupp, rnkovacs.
xazax.hun requested review of this revision.
Herald added a subscriber: cfe-commits.

After some interaction between the statement local lifetime analysis and some 
newly introduced warnings 
(https://github.com/llvm/llvm-project/commit/2177e4555ab84771c611a3295ab1149af7f79c29),
 a new false positive pattern appeared.  This patch updates the logic that is 
responsible to make sure we only warn for a returned `GslPointer` when it was 
initialized from a value with a local owner.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D97605

Files:
  clang/lib/Sema/SemaInit.cpp
  clang/test/Sema/warn-lifetime-analysis-nocfg.cpp


Index: clang/test/Sema/warn-lifetime-analysis-nocfg.cpp
===
--- clang/test/Sema/warn-lifetime-analysis-nocfg.cpp
+++ clang/test/Sema/warn-lifetime-analysis-nocfg.cpp
@@ -171,12 +171,22 @@
   const T *begin() const;
 };
 
+template struct iter {
+iter& operator-=(int);
+
+iter operator-(int _Off) const {
+iter _Tmp = *this;
+return _Tmp -= _Off;
+}
+};
+
 template
 struct basic_string {
   basic_string();
   basic_string(const T *);
   const T *c_str() const;
   operator basic_string_view () const;
+  using const_iterator = iter;
 };
 
 
@@ -455,3 +465,8 @@
   std::vector::iterator> iters;
   return iters.at(0);
 }
+
+void testForBug49342()
+{
+  auto it = std::iter{} - 2; // Used to be false positive.
+}
Index: clang/lib/Sema/SemaInit.cpp
===
--- clang/lib/Sema/SemaInit.cpp
+++ clang/lib/Sema/SemaInit.cpp
@@ -7521,6 +7521,8 @@
   continue;
 if (It->Kind == IndirectLocalPathEntry::AddressOf)
   continue;
+if (It->Kind == IndirectLocalPathEntry::LifetimeBoundCall)
+  continue;
 return It->Kind == IndirectLocalPathEntry::GslPointerInit ||
It->Kind == IndirectLocalPathEntry::GslReferenceInit;
   }


Index: clang/test/Sema/warn-lifetime-analysis-nocfg.cpp
===
--- clang/test/Sema/warn-lifetime-analysis-nocfg.cpp
+++ clang/test/Sema/warn-lifetime-analysis-nocfg.cpp
@@ -171,12 +171,22 @@
   const T *begin() const;
 };
 
+template struct iter {
+iter& operator-=(int);
+
+iter operator-(int _Off) const {
+iter _Tmp = *this;
+return _Tmp -= _Off;
+}
+};
+
 template
 struct basic_string {
   basic_string();
   basic_string(const T *);
   const T *c_str() const;
   operator basic_string_view () const;
+  using const_iterator = iter;
 };
 
 
@@ -455,3 +465,8 @@
   std::vector::iterator> iters;
   return iters.at(0);
 }
+
+void testForBug49342()
+{
+  auto it = std::iter{} - 2; // Used to be false positive.
+}
Index: clang/lib/Sema/SemaInit.cpp
===
--- clang/lib/Sema/SemaInit.cpp
+++ clang/lib/Sema/SemaInit.cpp
@@ -7521,6 +7521,8 @@
   continue;
 if (It->Kind == IndirectLocalPathEntry::AddressOf)
   continue;
+if (It->Kind == IndirectLocalPathEntry::LifetimeBoundCall)
+  continue;
 return It->Kind == IndirectLocalPathEntry::GslPointerInit ||
It->Kind == IndirectLocalPathEntry::GslReferenceInit;
   }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D97449: [Diagnose] Unify MCContext and LLVMContext diagnosing

2021-02-26 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers added a comment.

I tested this on some wacko LTO kernel build failure 
(https://github.com/ClangBuiltLinux/linux/issues/1269).  The error message went 
from:

> :0: error: __ia32_compat_sys_sysctl changed binding to STB_GLOBAL

To:

  unimplemented
  UNREACHABLE executed at ../include/llvm/IR/DiagnosticInfo.h:1036!
  PLEASE submit a bug report to https://bugs.llvm.org/ and include the crash 
backtrace.
  Stack dump:
  0.  Program arguments: ld.lld -m elf_x86_64 -z max-page-size=0x20 
-plugin-opt=-code-model=kernel -plugin-opt=-stack-alignment=8 -mllvm 
-import-instr-limit=5 -r -o vmlinux.o -T .tmp_lto.lds --whole-archive 
built-in.a --no-whole-archive --start-group lib/lib.a arch/x86/lib/lib.a 
--end-group
  1.  Running pass 'Function Pass Manager' on module 'ld-temp.o'.
  2.  Running pass 'X86 Assembly Printer' on function 
'@__ia32_compat_sys_sysctl'
   #0 0x01bb2d13 llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) 
(/android0/llvm-project/llvm/build/bin/lld+0x1bb2d13)
   #1 0x01bb0a5e llvm::sys::RunSignalHandlers() 
(/android0/llvm-project/llvm/build/bin/lld+0x1bb0a5e)
   #2 0x01bb330f SignalHandler(int) Signals.cpp:0:0
   #3 0x7f5d1768b140 __restore_rt 
(/lib/x86_64-linux-gnu/libpthread.so.0+0x14140)
   #4 0x7f5d16fb5ce1 raise ./signal/../sysdeps/unix/sysv/linux/raise.c:51:1
   #5 0x7f5d16f9f537 abort ./stdlib/abort.c:81:7
   #6 0x01b2a261 (/android0/llvm-project/llvm/build/bin/lld+0x1b2a261)
   #7 0x02cd3199 (/android0/llvm-project/llvm/build/bin/lld+0x2cd3199)
   #8 0x01bb4479 lld::diagnosticHandler(llvm::DiagnosticInfo const&) 
(/android0/llvm-project/llvm/build/bin/lld+0x1bb4479)
   #9 0x02bb03bf 
llvm::lto::LTOLLVMDiagnosticHandler::handleDiagnostics(llvm::DiagnosticInfo 
const&) LTO.cpp:0:0
  #10 0x0407f96c llvm::LLVMContext::diagnose(llvm::DiagnosticInfo 
const&) (/android0/llvm-project/llvm/build/bin/lld+0x407f96c)
  #11 0x02cd30b4 std::_Function_handler >&), 
llvm::MachineModuleInfoWrapperPass::doInitialization(llvm::Module&)::$_1>::_M_invoke(std::_Any_data
 const&, llvm::SMDiagnostic const&, bool&&, llvm::SourceMgr const&, 
std::vector >&) 
MachineModuleInfo.cpp:0:0
  #12 0x03e5e87a llvm::MCContext::reportCommon(llvm::SMLoc, 
std::function) 
(/android0/llvm-project/llvm/build/bin/lld+0x3e5e87a)
  #13 0x03e5aeee llvm::MCContext::reportError(llvm::SMLoc, llvm::Twine 
const&) (/android0/llvm-project/llvm/build/bin/lld+0x3e5aeee)
  #14 0x03e6c7de 
llvm::MCELFStreamer::emitSymbolAttribute(llvm::MCSymbol*, llvm::MCSymbolAttr) 
(/android0/llvm-project/llvm/build/bin/lld+0x3e6c7de)
  #15 0x0271b6f2 llvm::AsmPrinter::emitFunctionHeader() 
(/android0/llvm-project/llvm/build/bin/lld+0x271b6f2)
  #16 0x0271cb3d llvm::AsmPrinter::emitFunctionBody() 
(/android0/llvm-project/llvm/build/bin/lld+0x271cb3d)
  #17 0x02482556 
llvm::X86AsmPrinter::runOnMachineFunction(llvm::MachineFunction&) 
X86AsmPrinter.cpp:0:0
  #18 0x02cb37fe 
llvm::MachineFunctionPass::runOnFunction(llvm::Function&) 
(/android0/llvm-project/llvm/build/bin/lld+0x2cb37fe)
  #19 0x040912a8 llvm::FPPassManager::runOnFunction(llvm::Function&) 
(/android0/llvm-project/llvm/build/bin/lld+0x40912a8)
  #20 0x040979a8 llvm::FPPassManager::runOnModule(llvm::Module&) 
(/android0/llvm-project/llvm/build/bin/lld+0x40979a8)
  #21 0x04091957 llvm::legacy::PassManagerImpl::run(llvm::Module&) 
(/android0/llvm-project/llvm/build/bin/lld+0x4091957)




Comment at: llvm/test/CodeGen/AMDGPU/lds-initializer.ll:1-2
-; RUN: llc -march=amdgcn -mcpu=tahiti < %s -o /dev/null 2>&1 | FileCheck %s
-; RUN: llc -march=amdgcn -mcpu=tonga < %s -o /dev/null 2>&1 | FileCheck %s
+; RUN: not llc -march=amdgcn -mcpu=tahiti < %s -o /dev/null 2>&1 | FileCheck %s
+; RUN: not llc -march=amdgcn -mcpu=tonga < %s -o /dev/null 2>&1 | FileCheck %s
 

Does the addition of `not` mean that this test would have failed due to these 
changes? How come?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97449/new/

https://reviews.llvm.org/D97449

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D64146: [Clang Interpreter] Initial patch for the constexpr interpreter

2021-02-26 Thread Jessica Clarke via Phabricator via cfe-commits
jrtc27 added a comment.

In D64146#2591732 , @jrtc27 wrote:

> In D64146#2567710 , @nand wrote:
>
>> CodePtr points into the bytecode emitted by the byte code compiler. In some 
>> instances, pointers to auxiliary data structures are embedded into the byte 
>> code, such as functions or AST nodes which contain information relevant to 
>> the execution of the instruction.
>>
>> Would it help if instead of encoding pointers, the byte code encoded some 
>> integers mapped to the original objects?
>
> I've read through the code and have slightly more understanding now. It seems 
> there are several options:
>
> 1. Keep the pointers somewhere on the side and put an integer in the byte 
> code, like you suggest
>
> 2. Pad values in the byte code to their natural alignment in general (and 
> ensure the underlying std::vector gets its storage allocated at an 
> aligned boundary / use a different container), though this can get a little 
> weird as the amount of padding between consecutive arguments varies depending 
> on where you are (unless you force realignment to the max alignment at the 
> start of a new opcode)
>
> 3. Make the byte code be an array of uintptr_t instead of packing it like is 
> done currently, with care needed on ILP32; that can either just use uint64_t 
> instead and we declare CHERI unsupported for 32-bit architectures (which is 
> unlikely to be a problem as you probably want a 64-bit virtual address space 
> if the doubling pointer size, with 64-bit CHERI capabilities on 32-bit VA 
> systems being only for embedded use) or you can split 64-bit integers into 
> two 32-bit integers and treat them as two arguments
>
> 1 works but feels ugly. 2 or 3 would be my preference, and mirror how 
> "normal" interpreters work, though those might split the code and data so 
> they can keep the opcodes as, say, 32-bit integers, but the stack full of 
> native word/pointer slots; my inclination is that 3 is the best option as it 
> looks like the simplest. How do you feel about each of those? Is memory 
> overhead from not packing values a concern?

Hm, though I see the "store an ID" pattern is common for dynamic things and 
this should be quite rare, so maybe that is indeed the right approach, 
mirroring something like getOrCreateGlobal?


Repository:
  rL LLVM

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D64146/new/

https://reviews.llvm.org/D64146

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 9e0d550 - [clang][NFC] Clean up whitespace in ClangOpcodesEmitter output

2021-02-26 Thread Jessica Clarke via cfe-commits

Author: Jessica Clarke
Date: 2021-02-27T01:28:56Z
New Revision: 9e0d55024d4ed776f209ee04e260bdd314854993

URL: 
https://github.com/llvm/llvm-project/commit/9e0d55024d4ed776f209ee04e260bdd314854993
DIFF: 
https://github.com/llvm/llvm-project/commit/9e0d55024d4ed776f209ee04e260bdd314854993.diff

LOG: [clang][NFC] Clean up whitespace in ClangOpcodesEmitter output

This should now be about as style-conforming as TableGen'ed code ever
can reasonably be.

Added: 


Modified: 
clang/utils/TableGen/ClangOpcodesEmitter.cpp

Removed: 




diff  --git a/clang/utils/TableGen/ClangOpcodesEmitter.cpp 
b/clang/utils/TableGen/ClangOpcodesEmitter.cpp
index e5bfac5ba1b6f..ffeedcdf0ee27 100644
--- a/clang/utils/TableGen/ClangOpcodesEmitter.cpp
+++ b/clang/utils/TableGen/ClangOpcodesEmitter.cpp
@@ -122,13 +122,13 @@ void ClangOpcodesEmitter::EmitInterp(raw_ostream , 
StringRef N, Record *R) {
 
 // Emit calls to read arguments.
 for (size_t I = 0, N = Args.size(); I < N; ++I) {
-  OS << "\tauto V" << I;
+  OS << "  auto V" << I;
   OS << " = ";
   OS << "PC.read<" << Args[I]->getValueAsString("Name") << ">();\n";
 }
 
 // Emit a call to the template method and pass arguments.
-OS << "\tif (!" << N;
+OS << "  if (!" << N;
 PrintTypes(OS, TS);
 OS << "(S";
 if (ChangesPC)
@@ -140,15 +140,15 @@ void ClangOpcodesEmitter::EmitInterp(raw_ostream , 
StringRef N, Record *R) {
 for (size_t I = 0, N = Args.size(); I < N; ++I)
   OS << ", V" << I;
 OS << "))\n";
-OS << "\t\treturn false;\n";
+OS << "return false;\n";
 
 // Bail out if interpreter returned.
 if (CanReturn) {
-  OS << "\tif (!S.Current || S.Current->isRoot())\n";
-  OS << "\t\treturn true;\n";
+  OS << "  if (!S.Current || S.Current->isRoot())\n";
+  OS << "return true;\n";
 }
 
-OS << "\tcontinue;\n";
+OS << "  continue;\n";
 OS << "}\n";
   });
   OS << "#endif\n";
@@ -158,14 +158,14 @@ void ClangOpcodesEmitter::EmitDisasm(raw_ostream , 
StringRef N, Record *R) {
   OS << "#ifdef GET_DISASM\n";
   Enumerate(R, N, [R, ](ArrayRef, const Twine ) {
 OS << "case OP_" << ID << ":\n";
-OS << "\tPrintName(\"" << ID << "\");\n";
-OS << "\tOS << \"\\t\"";
+OS << "  PrintName(\"" << ID << "\");\n";
+OS << "  OS << \"\\t\"";
 
 for (auto *Arg : R->getValueAsListOfDefs("Args"))
   OS << " << PC.read<" << Arg->getValueAsString("Name") << ">() << \" \"";
 
-OS << "<< \"\\n\";\n";
-OS << "\tcontinue;\n";
+OS << " << \"\\n\";\n";
+OS << "  continue;\n";
   });
   OS << "#endif\n";
 }
@@ -181,11 +181,11 @@ void ClangOpcodesEmitter::EmitEmitter(raw_ostream , 
StringRef N, Record *R) {
 // Emit the list of arguments.
 OS << "bool ByteCodeEmitter::emit" << ID << "(";
 for (size_t I = 0, N = Args.size(); I < N; ++I)
-  OS << Args[I]->getValueAsString("Name") << " A" << I << ",";
+  OS << Args[I]->getValueAsString("Name") << " A" << I << ", ";
 OS << "const SourceInfo ) {\n";
 
 // Emit a call to write the opcodes.
-OS << "\treturn emitOp<";
+OS << "  return emitOp<";
 for (size_t I = 0, N = Args.size(); I < N; ++I) {
   if (I != 0)
 OS << ", ";
@@ -250,7 +250,7 @@ void ClangOpcodesEmitter::EmitGroup(raw_ostream , 
StringRef N, Record *R) {
 
   // Emit the dispatch implementation in the source.
   OS << "#if defined(GET_EVAL_IMPL) || defined(GET_LINK_IMPL)\n";
-  OS << "bool \n";
+  OS << "bool\n";
   OS << "#if defined(GET_EVAL_IMPL)\n";
   OS << "EvalEmitter\n";
   OS << "#else\n";
@@ -271,13 +271,14 @@ void ClangOpcodesEmitter::EmitGroup(raw_ostream , 
StringRef N, Record *R) {
   // Custom evaluator methods dispatch to template methods.
   if (R->getValueAsBit("HasCustomEval")) {
 OS << "#ifdef GET_LINK_IMPL\n";
-OS << "return emit" << ID << "\n";
+OS << "return emit" << ID << "\n";
 OS << "#else\n";
-OS << "return emit" << N;
+OS << "return emit" << N;
 PrintTypes(OS, TS);
 OS << "\n#endif\n";
+OS << "  ";
   } else {
-OS << "return emit" << ID;
+OS << "return emit" << ID;
   }
 
   OS << "(";
@@ -290,19 +291,19 @@ void ClangOpcodesEmitter::EmitGroup(raw_ostream , 
StringRef N, Record *R) {
 
 // Print a switch statement selecting T.
 if (auto *TypeClass = dyn_cast(Types->getElement(I))) {
-  OS << "switch (T" << I << "){\n";
+  OS << "  switch (T" << I << ") {\n";
   auto Cases = TypeClass->getDef()->getValueAsListOfDefs("Types");
   for (auto *Case : Cases) {
-OS << "case PT_" << Case->getName() << ":\n";
+OS << "  case PT_" << Case->getName() << ":\n";
 TS.push_back(Case);
 Rec(I + 1, ID + Case->getName());
 TS.pop_back();
   }
   // Emit a default case if not all types are present.
 

[clang] a0c1cd6 - [test] Add -triple x86_64 to attr-retain.c

2021-02-26 Thread Fangrui Song via cfe-commits

Author: Fangrui Song
Date: 2021-02-26T17:26:26-08:00
New Revision: a0c1cd642da51ab8f471d2dd5ba905cf81760187

URL: 
https://github.com/llvm/llvm-project/commit/a0c1cd642da51ab8f471d2dd5ba905cf81760187
DIFF: 
https://github.com/llvm/llvm-project/commit/a0c1cd642da51ab8f471d2dd5ba905cf81760187.diff

LOG: [test] Add -triple x86_64 to attr-retain.c

Added: 


Modified: 
clang/test/CodeGen/attr-retain.c

Removed: 




diff  --git a/clang/test/CodeGen/attr-retain.c 
b/clang/test/CodeGen/attr-retain.c
index 871065d4fe75..8ac9fefb3c20 100644
--- a/clang/test/CodeGen/attr-retain.c
+++ b/clang/test/CodeGen/attr-retain.c
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -emit-llvm %s -o - | FileCheck %s
+// RUN: %clang_cc1 -emit-llvm -triple x86_64 %s -o - | FileCheck %s
 
 /// Set !retain regardless of the target. The backend will lower !retain to
 /// SHF_GNU_RETAIN on ELF and ignore the metadata for other binary formats.



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D64146: [Clang Interpreter] Initial patch for the constexpr interpreter

2021-02-26 Thread Jessica Clarke via Phabricator via cfe-commits
jrtc27 added a comment.

In D64146#2567710 , @nand wrote:

> CodePtr points into the bytecode emitted by the byte code compiler. In some 
> instances, pointers to auxiliary data structures are embedded into the byte 
> code, such as functions or AST nodes which contain information relevant to 
> the execution of the instruction.
>
> Would it help if instead of encoding pointers, the byte code encoded some 
> integers mapped to the original objects?

I've read through the code and have slightly more understanding now. It seems 
there are several options:

1. Keep the pointers somewhere on the side and put an integer in the byte code, 
like you suggest

2. Pad values in the byte code to their natural alignment in general (and 
ensure the underlying std::vector gets its storage allocated at an 
aligned boundary / use a different container), though this can get a little 
weird as the amount of padding between consecutive arguments varies depending 
on where you are (unless you force realignment to the max alignment at the 
start of a new opcode)

3. Make the byte code be an array of uintptr_t instead of packing it like is 
done currently, with care needed on ILP32; that can either just use uint64_t 
instead and we declare CHERI unsupported for 32-bit architectures (which is 
unlikely to be a problem as you probably want a 64-bit virtual address space if 
the doubling pointer size, with 64-bit CHERI capabilities on 32-bit VA systems 
being only for embedded use) or you can split 64-bit integers into two 32-bit 
integers and treat them as two arguments

1 works but feels ugly. 2 or 3 would be my preference, and mirror how "normal" 
interpreters work, though those might split the code and data so they can keep 
the opcodes as, say, 32-bit integers, but the stack full of native word/pointer 
slots; my inclination is that 3 is the best option as it looks like the 
simplest. How do you feel about each of those? Is memory overhead from not 
packing values a concern?


Repository:
  rL LLVM

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D64146/new/

https://reviews.llvm.org/D64146

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D97447: Add GNU attribute 'retain'

2021-02-26 Thread Fangrui Song via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG8afdacba9dcd: Add GNU attribute retain (authored 
by MaskRay).

Changed prior to commit:
  https://reviews.llvm.org/D97447?vs=326766=326839#toc

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97447/new/

https://reviews.llvm.org/D97447

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/lib/CodeGen/CGDecl.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/test/CodeGen/attr-retain.c
  clang/test/CodeGenCXX/attr-retain.cpp
  clang/test/Sema/attr-retain.c

Index: clang/test/Sema/attr-retain.c
===
--- /dev/null
+++ clang/test/Sema/attr-retain.c
@@ -0,0 +1,29 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s -Wunused-function
+
+/// We allow 'retain' on non-ELF targets because 'retain' is often used together
+/// with 'used'. 'used' has GC root semantics on macOS and Windows. We want
+/// users to just write retain,used and don't need to dispatch on binary formats.
+
+extern char test1[] __attribute__((retain));   // expected-warning {{'retain' attribute ignored on a non-definition declaration}}
+extern const char test2[] __attribute__((retain)); // expected-warning {{'retain' attribute ignored on a non-definition declaration}}
+const char test3[] __attribute__((retain)) = "";
+
+struct __attribute__((retain)) s { // expected-warning {{'retain' attribute only applies to variables with non-local storage, functions, and Objective-C methods}}
+};
+
+void foo() {
+  static int a __attribute__((retain));
+  int b __attribute__((retain)); // expected-warning {{'retain' attribute only applies to variables with non-local storage, functions, and Objective-C methods}}
+  (void)a;
+  (void)b;
+}
+
+__attribute__((retain,used)) static void f0() {}
+__attribute__((retain)) static void f1() {} // expected-warning {{unused function 'f1'}}
+__attribute__((retain)) void f2() {}
+
+/// Test attribute merging.
+int tentative;
+int tentative __attribute__((retain));
+extern int tentative;
+int tentative = 0;
Index: clang/test/CodeGenCXX/attr-retain.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/attr-retain.cpp
@@ -0,0 +1,45 @@
+// RUN: %clang_cc1 -emit-llvm -triple %itanium_abi_triple -Werror %s -o - | FileCheck %s
+
+// CHECK:  @llvm.used = appending global [7 x i8*]
+// CHECK-SAME:   @_ZN2X0C2Ev
+// CHECK-SAME:   @_ZN2X0C1Ev
+// CHECK-SAME:   @_ZN2X0D2Ev
+// CHECK-SAME:   @_ZN2X0D1Ev
+// CHECK-SAME:   @_ZN2X16Nested2f1Ev
+// CHECK-SAME:   @_ZN10merge_declL4funcEv
+// CHECK-SAME:   @_ZN18instantiate_member1SIiE1fEv
+
+struct X0 {
+  // CHECK: define linkonce_odr{{.*}} @_ZN2X0C1Ev({{.*}}
+  __attribute__((used, retain)) X0() {}
+  // CHECK: define linkonce_odr{{.*}} @_ZN2X0D1Ev({{.*}}
+  __attribute__((used, retain)) ~X0() {}
+};
+
+struct X1 {
+  struct Nested {
+// CHECK-NOT: 2f0Ev
+// CHECK: define linkonce_odr{{.*}} @_ZN2X16Nested2f1Ev({{.*}}
+void __attribute__((retain)) f0() {}
+void __attribute__((used, retain)) f1() {}
+  };
+};
+
+// CHECK: define internal void @_ZN10merge_declL4funcEv(){{.*}}
+namespace merge_decl {
+static void func();
+void bar() { void func() __attribute__((used, retain)); }
+static void func() {}
+} // namespace merge_decl
+
+namespace instantiate_member {
+template 
+struct S {
+  void __attribute__((used, retain)) f() {}
+};
+
+void test() {
+  // CHECK: define linkonce_odr{{.*}} void @_ZN18instantiate_member1SIiE1fEv({{.*}}
+  S a;
+}
+} // namespace instantiate_member
Index: clang/test/CodeGen/attr-retain.c
===
--- /dev/null
+++ clang/test/CodeGen/attr-retain.c
@@ -0,0 +1,29 @@
+// RUN: %clang_cc1 -emit-llvm %s -o - | FileCheck %s
+
+/// Set !retain regardless of the target. The backend will lower !retain to
+/// SHF_GNU_RETAIN on ELF and ignore the metadata for other binary formats.
+// CHECK:  @c0 ={{.*}} constant i32 {{.*}}
+// CHECK:  @foo.l0 = internal global i32 {{.*}}
+// CHECK:  @g0 ={{.*}} global i32 {{.*}}
+// CHECK-NEXT: @g1 ={{.*}} global i32 {{.*}}
+// CHECK-NEXT: @g3 = internal global i32 {{.*}}
+// CHECK-NEXT: @g4 = internal global i32 0, section ".data.g"{{.*}}
+
+// CHECK:  @llvm.used = appending global [8 x i8*] [i8* bitcast (i32* @c0 to i8*), i8* bitcast (i32* @foo.l0 to i8*), i8* bitcast (void ()* @f0 to i8*), i8* bitcast (void ()* @f2 to i8*), i8* bitcast (i32* @g0 to i8*), i8* bitcast (i32* @g1 to i8*), i8* bitcast (i32* @g3 to i8*), i8* bitcast (i32* @g4 to i8*)], section "llvm.metadata"
+// CHECK:  @llvm.compiler.used = appending global [3 x i8*] [i8* bitcast (void ()* @f2 to i8*), i8* bitcast (i32* @g3 to i8*), i8* bitcast (i32* @g4 to i8*)], section "llvm.metadata"
+
+const int c0 

[clang] 8afdacb - Add GNU attribute 'retain'

2021-02-26 Thread Fangrui Song via cfe-commits

Author: Fangrui Song
Date: 2021-02-26T16:37:50-08:00
New Revision: 8afdacba9dcd36fc838eb86fca86f7f903040030

URL: 
https://github.com/llvm/llvm-project/commit/8afdacba9dcd36fc838eb86fca86f7f903040030
DIFF: 
https://github.com/llvm/llvm-project/commit/8afdacba9dcd36fc838eb86fca86f7f903040030.diff

LOG: Add GNU attribute 'retain'

For ELF targets, GCC 11 will set SHF_GNU_RETAIN on the section of a
`__attribute__((retain))` function/variable to prevent linker garbage
collection. (See AttrDocs.td for the linker support).

This patch adds `retain` functions/variables to the `llvm.used` list, which has
the desired linker GC semantics. Note: `retain` does not imply `used`,
so an unused function/variable can be dropped by Sema.

Before 'retain' was introduced, previous ELF solutions require inline asm or
linker tricks, e.g.  `asm volatile(".reloc 0, R_X86_64_NONE, target");`
(architecture dependent) or define a non-local symbol in the section and use
`ld -u`. There was no elegant source-level solution.

With D97448, `__attribute__((retain))` will set `SHF_GNU_RETAIN` on ELF targets.

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

Added: 
clang/test/CodeGen/attr-retain.c
clang/test/CodeGenCXX/attr-retain.cpp
clang/test/Sema/attr-retain.c

Modified: 
clang/include/clang/Basic/Attr.td
clang/include/clang/Basic/AttrDocs.td
clang/lib/CodeGen/CGDecl.cpp
clang/lib/CodeGen/CodeGenModule.cpp
clang/lib/Sema/SemaDecl.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index bc2d8ceeeb6c..8afa676c133f 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -2648,7 +2648,14 @@ def Unused : InheritableAttr {
 def Used : InheritableAttr {
   let Spellings = [GCC<"used">];
   let Subjects = SubjectList<[NonLocalVar, Function, ObjCMethod]>;
-  let Documentation = [Undocumented];
+  let Documentation = [UsedDocs];
+  let SimpleHandler = 1;
+}
+
+def Retain : InheritableAttr {
+  let Spellings = [GCC<"retain">];
+  let Subjects = SubjectList<[NonLocalVar, Function, ObjCMethod]>;
+  let Documentation = [RetainDocs];
   let SimpleHandler = 1;
 }
 

diff  --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index b88b18d37477..deda68b64f90 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -57,6 +57,55 @@ global variable or function should be in after translation.
   let Heading = "section, __declspec(allocate)";
 }
 
+def UsedDocs : Documentation {
+  let Category = DocCatFunction;
+  let Content = [{
+This attribute, when attached to a function or variable definition, indicates
+that there may be references to the entity which are not apparent in the source
+code.  For example, it may be referenced from inline ``asm``, or it may be
+found through a dynamic symbol or section lookup.
+
+The compiler must emit the definition even if it appears to be unused, and it
+must not apply optimizations which depend on fully understanding how the entity
+is used.
+
+Whether this attribute has any effect on the linker depends on the target and
+the linker. Most linkers support the feature of section garbage collection
+(``--gc-sections``), also known as "dead stripping" (``ld64 -dead_strip``) or
+discarding unreferenced sections (``link.exe /OPT:REF``). On COFF and Mach-O
+targets (Windows and Apple platforms), the `used` attribute prevents symbols
+from being removed by linker section GC. On ELF targets, it has no effect on 
its
+own, and the linker may remove the definition if it is not otherwise 
referenced.
+This linker GC can be avoided by also adding the ``retain`` attribute.  Note
+that ``retain`` requires special support from the linker; see that attribute's
+documentation for further information.
+  }];
+}
+
+def RetainDocs : Documentation {
+  let Category = DocCatFunction;
+  let Content = [{
+This attribute, when attached to a function or variable definition, prevents
+section garbage collection in the linker. It does not prevent other discard
+mechanisms, such as archive member selection, and COMDAT group resolution.
+
+If the compiler does not emit the definition, e.g. because it was not used in
+the translation unit or the compiler was able to eliminate all of the uses,
+this attribute has no effect.  This attribute is typically combined with the
+``used`` attribute to force the definition to be emitted and preserved into the
+final linked image.
+
+This attribute is only necessary on ELF targets; other targets prevent section
+garbage collection by the linker when using the ``used`` attribute alone.
+Using the attributes together should result in consistent behavior across
+targets.
+
+This attribute requires the linker to support the ``SHF_GNU_RETAIN`` extension.
+This support is available in GNU ``ld`` and ``gold`` as of binutils 2.36, as

[clang] 233ba27 - [Driver] Fix a warning about the the initialization order

2021-02-26 Thread Kazu Hirata via cfe-commits

Author: Kazu Hirata
Date: 2021-02-26T16:32:30-08:00
New Revision: 233ba2709bde54ea820cdaba0405d46b2c197e01

URL: 
https://github.com/llvm/llvm-project/commit/233ba2709bde54ea820cdaba0405d46b2c197e01
DIFF: 
https://github.com/llvm/llvm-project/commit/233ba2709bde54ea820cdaba0405d46b2c197e01.diff

LOG: [Driver] Fix a warning about the the initialization order

Added: 


Modified: 
clang/lib/Driver/Driver.cpp

Removed: 




diff  --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index acea40f05182..ceaeb16df6f1 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -135,9 +135,9 @@ Driver::Driver(StringRef ClangExecutable, StringRef 
TargetTriple,
 : Diags(Diags), VFS(std::move(VFS)), Mode(GCCMode),
   SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone), LTOMode(LTOK_None),
   ClangExecutable(ClangExecutable), SysRoot(DEFAULT_SYSROOT),
-  DriverTitle(Title), CCPrintOptionsFilename(nullptr),
-  CCPrintHeadersFilename(nullptr), CCLogDiagnosticsFilename(nullptr),
-  CCPrintStatReportFilename(nullptr), CCCPrintBindings(false),
+  DriverTitle(Title), CCPrintStatReportFilename(nullptr),
+  CCPrintOptionsFilename(nullptr), CCPrintHeadersFilename(nullptr),
+  CCLogDiagnosticsFilename(nullptr), CCCPrintBindings(false),
   CCPrintOptions(false), CCPrintHeaders(false), CCLogDiagnostics(false),
   CCGenDiagnostics(false), CCPrintProcessStats(false),
   TargetTriple(TargetTriple), CCCGenericGCCName(""), Saver(Alloc),



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D97094: [Driver] Print process statistics report on CC_PRINT_PROC_STAT env variable.

2021-02-26 Thread Vlad Vereschaka via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG155c49e0878d: [Driver] Print process statistics report on 
CC_PRINT_PROC_STAT env variable. (authored by vvereschaka).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97094/new/

https://reviews.llvm.org/D97094

Files:
  clang/docs/UsersManual.rst
  clang/include/clang/Driver/Driver.h
  clang/lib/Driver/Driver.cpp
  clang/test/Driver/cc-print-proc-stat.c
  clang/test/Driver/lit.local.cfg
  clang/tools/driver/driver.cpp

Index: clang/tools/driver/driver.cpp
===
--- clang/tools/driver/driver.cpp
+++ clang/tools/driver/driver.cpp
@@ -258,6 +258,11 @@
   TheDriver.CCLogDiagnostics = !!::getenv("CC_LOG_DIAGNOSTICS");
   if (TheDriver.CCLogDiagnostics)
 TheDriver.CCLogDiagnosticsFilename = ::getenv("CC_LOG_DIAGNOSTICS_FILE");
+
+  // Handle CC_PRINT_PROC_STAT and CC_PRINT_PROC_STAT_FILE.
+  TheDriver.CCPrintProcessStats = !!::getenv("CC_PRINT_PROC_STAT");
+  if (TheDriver.CCPrintProcessStats)
+TheDriver.CCPrintStatReportFilename = ::getenv("CC_PRINT_PROC_STAT_FILE");
 }
 
 static void FixupDiagPrefixExeName(TextDiagnosticPrinter *DiagClient,
Index: clang/test/Driver/lit.local.cfg
===
--- clang/test/Driver/lit.local.cfg
+++ clang/test/Driver/lit.local.cfg
@@ -11,7 +11,7 @@
  'IPHONEOS_DEPLOYMENT_TARGET',
  'SDKROOT', 'CCC_OVERRIDE_OPTIONS',
  'CC_PRINT_OPTIONS', 'CC_PRINT_HEADERS',
- 'CC_LOG_DIAGNOSTICS']
+ 'CC_LOG_DIAGNOSTICS', 'CC_PRINT_PROC_STAT']
 
 for name in driver_overwrite_env_vars:
   if name in config.environment:
Index: clang/test/Driver/cc-print-proc-stat.c
===
--- /dev/null
+++ clang/test/Driver/cc-print-proc-stat.c
@@ -0,0 +1,9 @@
+// RUN: env CC_PRINT_PROC_STAT=1 \
+// RUN: CC_PRINT_PROC_STAT_FILE=%t.csv \
+// RUN: %clang -no-canonical-prefixes -S -o %t.s %s
+// RUN: FileCheck --check-prefix=CHECK-CSV %s < %t.csv
+// CHECK-CSV: clang{{.*}},"{{.*}}.s",{{[0-9]+}},{{[0-9]+}},{{[0-9]+}}
+
+// RUN: env CC_PRINT_PROC_STAT=1 \
+// RUN: %clang -c -fintegrated-as %s | FileCheck %s
+// CHECK: clang{{.*}}: output={{.*}}.o, total={{[0-9.]+}} ms, user={{[0-9.]+}} ms, mem={{[0-9]+}} Kb
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -137,8 +137,9 @@
   ClangExecutable(ClangExecutable), SysRoot(DEFAULT_SYSROOT),
   DriverTitle(Title), CCPrintOptionsFilename(nullptr),
   CCPrintHeadersFilename(nullptr), CCLogDiagnosticsFilename(nullptr),
-  CCCPrintBindings(false), CCPrintOptions(false), CCPrintHeaders(false),
-  CCLogDiagnostics(false), CCGenDiagnostics(false),
+  CCPrintStatReportFilename(nullptr), CCCPrintBindings(false),
+  CCPrintOptions(false), CCPrintHeaders(false), CCLogDiagnostics(false),
+  CCGenDiagnostics(false), CCPrintProcessStats(false),
   TargetTriple(TargetTriple), CCCGenericGCCName(""), Saver(Alloc),
   CheckInputsExist(true), GenReproducer(false),
   SuppressMissingInputWarning(false) {
@@ -1096,6 +1097,15 @@
   GenReproducer = Args.hasFlag(options::OPT_gen_reproducer,
options::OPT_fno_crash_diagnostics,
!!::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH"));
+
+  // Process -fproc-stat-report options.
+  if (const Arg *A = Args.getLastArg(options::OPT_fproc_stat_report_EQ)) {
+CCPrintProcessStats = true;
+CCPrintStatReportFilename = A->getValue();
+  }
+  if (Args.hasArg(options::OPT_fproc_stat_report))
+CCPrintProcessStats = true;
+
   // FIXME: TargetTriple is used by the target-prefixed calls to as/ld
   // and getToolChain is const.
   if (IsCLMode()) {
@@ -4009,62 +4019,58 @@
/*TargetDeviceOffloadKind*/ Action::OFK_None);
   }
 
-  StringRef StatReportFile;
-  bool PrintProcessStat = false;
-  if (const Arg *A = C.getArgs().getLastArg(options::OPT_fproc_stat_report_EQ))
-StatReportFile = A->getValue();
-  if (C.getArgs().hasArg(options::OPT_fproc_stat_report))
-PrintProcessStat = true;
-
   // If we have more than one job, then disable integrated-cc1 for now. Do this
   // also when we need to report process execution statistics.
-  if (C.getJobs().size() > 1 || !StatReportFile.empty() || PrintProcessStat)
+  if (C.getJobs().size() > 1 || CCPrintProcessStats)
 for (auto  : C.getJobs())
   J.InProcess = false;
 
-  if (!StatReportFile.empty() || PrintProcessStat) {
+  if (CCPrintProcessStats) {
 C.setPostCallback([=](const Command , int Res) {
   Optional ProcStat =
   Cmd.getProcessStatistics();
   if (!ProcStat)
 

[clang] 155c49e - [Driver] Print process statistics report on CC_PRINT_PROC_STAT env variable.

2021-02-26 Thread Vladimir Vereschaka via cfe-commits

Author: Vladimir Vereschaka
Date: 2021-02-26T16:16:00-08:00
New Revision: 155c49e0878de667b8021b9ba685390151dee11e

URL: 
https://github.com/llvm/llvm-project/commit/155c49e0878de667b8021b9ba685390151dee11e
DIFF: 
https://github.com/llvm/llvm-project/commit/155c49e0878de667b8021b9ba685390151dee11e.diff

LOG: [Driver] Print process statistics report on CC_PRINT_PROC_STAT env 
variable.

Added supporting CC_PRINT_PROC_STAT and CC_PRINT_PROC_STAT_FILE
environment variables to trigger clang driver reporting the process
statistics into specified file (alternate for -fproc-stat-report
option).

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

Added: 
clang/test/Driver/cc-print-proc-stat.c

Modified: 
clang/docs/UsersManual.rst
clang/include/clang/Driver/Driver.h
clang/lib/Driver/Driver.cpp
clang/test/Driver/lit.local.cfg
clang/tools/driver/driver.cpp

Removed: 




diff  --git a/clang/docs/UsersManual.rst b/clang/docs/UsersManual.rst
index 6f593cab8f1a..b762bf9a542b 100644
--- a/clang/docs/UsersManual.rst
+++ b/clang/docs/UsersManual.rst
@@ -764,12 +764,12 @@ compilations steps.
   is sent to. If it specifies a regular file, the data are saved to this file 
in
   CSV format:
 
-.. code-block:: console
+  .. code-block:: console
 
-   $ clang -fproc-stat-report=abc foo.c
-   $ cat abc
-   clang-11,"/tmp/foo-123456.o",92000,84000,87536
-   ld,"a.out",900,8000,53568
+$ clang -fproc-stat-report=abc foo.c
+$ cat abc
+clang-11,"/tmp/foo-123456.o",92000,84000,87536
+ld,"a.out",900,8000,53568
 
   The data on each row represent:
   
@@ -780,19 +780,38 @@ compilations steps.
   * peak memory usage in Kb.
   
   It is possible to specify this option without any value. In this case 
statistics
-  is printed on standard output in human readable format:
+  are printed on standard output in human readable format:
   
-.. code-block:: console
+  .. code-block:: console
 
-  $ clang -fproc-stat-report foo.c
-  clang-11: output=/tmp/foo-855a8e.o, total=68.000 ms, user=60.000 ms, 
mem=86920 Kb
-  ld: output=a.out, total=8.000 ms, user=4.000 ms, mem=52320 Kb
+$ clang -fproc-stat-report foo.c
+clang-11: output=/tmp/foo-855a8e.o, total=68.000 ms, user=60.000 ms, 
mem=86920 Kb
+ld: output=a.out, total=8.000 ms, user=4.000 ms, mem=52320 Kb
   
   The report file specified in the option is locked for write, so this option
   can be used to collect statistics in parallel builds. The report file is not
   cleared, new data is appended to it, thus making posible to accumulate build
   statistics.
 
+  You can also use environment variables to control the process statistics 
reporting.
+  Setting ``CC_PRINT_PROC_STAT`` to ``1`` enables the feature, the report goes 
to
+  stdout in human readable format.
+  Setting ``CC_PRINT_PROC_STAT_FILE`` to a fully qualified file path makes it 
report
+  process statistics to the given file in the CSV format. Specifying a relative
+  path will likely lead to multiple files with the same name created in 
diff erent
+  directories, since the path is relative to a changing working directory.
+
+  These environment variables are handy when you need to request the statistics
+  report without changing your build scripts or alter the existing set of 
compiler
+  options. Note that ``-fproc-stat-report`` take precedence over 
``CC_PRINT_PROC_STAT``
+  and ``CC_PRINT_PROC_STAT_FILE``.
+
+  .. code-block:: console
+
+$ export CC_PRINT_PROC_STAT=1
+$ export CC_PRINT_PROC_STAT_FILE=~/project-build-proc-stat.csv
+$ make
+
 Other Options
 -
 Clang options that don't fit neatly into other categories.

diff  --git a/clang/include/clang/Driver/Driver.h 
b/clang/include/clang/Driver/Driver.h
index 74a9cf3dab81..54c20620910b 100644
--- a/clang/include/clang/Driver/Driver.h
+++ b/clang/include/clang/Driver/Driver.h
@@ -156,6 +156,9 @@ class Driver {
   /// Information about the host which can be overridden by the user.
   std::string HostBits, HostMachine, HostSystem, HostRelease;
 
+  /// The file to log CC_PRINT_PROC_STAT_FILE output to, if enabled.
+  const char *CCPrintStatReportFilename;
+
   /// The file to log CC_PRINT_OPTIONS output to, if enabled.
   const char *CCPrintOptionsFilename;
 
@@ -204,6 +207,10 @@ class Driver {
   /// Whether the driver is generating diagnostics for debugging purposes.
   unsigned CCGenDiagnostics : 1;
 
+  /// Set CC_PRINT_PROC_STAT mode, which causes the driver to dump
+  /// performance report to CC_PRINT_PROC_STAT_FILE or to stdout.
+  unsigned CCPrintProcessStats : 1;
+
   /// Pointer to the ExecuteCC1Tool function, if available.
   /// When the clangDriver lib is used through clang.exe, this provides a
   /// shortcut for executing the -cc1 command-line directly, in the same

diff  --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 84bee2ae9d07..acea40f05182 100644
--- 

[PATCH] D95409: [clang] implicitly delete space ship operator with function pointers

2021-02-26 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG4a8530fc3039: [clang] implicitly delete space ship operator 
with function pointers (authored by mizvekov, committed by rsmith).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D95409/new/

https://reviews.llvm.org/D95409

Files:
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/test/CXX/class/class.compare/class.compare.default/p2.cpp
  clang/test/CXX/class/class.compare/class.eq/p2.cpp
  clang/test/CXX/class/class.compare/class.spaceship/p2.cpp


Index: clang/test/CXX/class/class.compare/class.spaceship/p2.cpp
===
--- clang/test/CXX/class/class.compare/class.spaceship/p2.cpp
+++ clang/test/CXX/class/class.compare/class.spaceship/p2.cpp
@@ -155,3 +155,20 @@
 friend CmpCat auto operator<=>(const D&, const D&) = default;
   };
 }
+
+namespace PR48856 {
+  struct A {
+auto operator<=>(const A &) const = default; // expected-warning 
{{implicitly deleted}}
+void (*x)(); // expected-note {{because 
there is no viable comparison function for member 'x'}}
+  };
+
+  struct B {
+auto operator<=>(const B &) const = default; // expected-warning 
{{implicitly deleted}}
+void (B::*x)();  // expected-note {{because 
there is no viable comparison function for member 'x'}}
+  };
+
+  struct C {
+auto operator<=>(const C &) const = default; // expected-warning 
{{implicitly deleted}}
+int C::*x;   // expected-note {{because 
there is no viable comparison function for member 'x'}}
+  };
+}
Index: clang/test/CXX/class/class.compare/class.eq/p2.cpp
===
--- clang/test/CXX/class/class.compare/class.eq/p2.cpp
+++ clang/test/CXX/class/class.compare/class.eq/p2.cpp
@@ -15,6 +15,25 @@
 struct F { void operator==(F) const; };
 struct G { bool operator==(G) const = delete; }; // expected-note {{deleted 
here}}
 
+struct H1 {
+  bool operator==(const H1 &) const = default;
+  bool operator<(const H1 &) const = default; // expected-warning {{implicitly 
deleted}}
+  // expected-note@-1 {{because there is no viable comparison function}}
+  void (*x)();
+};
+struct H2 {
+  bool operator==(const H2 &) const = default;
+  bool operator<(const H2 &) const = default; // expected-warning {{implicitly 
deleted}}
+  // expected-note@-1 {{because there is no viable comparison function}}
+  void (H2::*x)();
+};
+struct H3 {
+  bool operator==(const H3 &) const = default;
+  bool operator<(const H3 &) const = default; // expected-warning {{implicitly 
deleted}}
+  // expected-note@-1 {{because there is no viable comparison function}}
+  int H3::*x;
+};
+
 template struct X {
   X();
   bool operator==(const X&) const = default; // #x expected-note 4{{deleted 
here}}
Index: clang/test/CXX/class/class.compare/class.compare.default/p2.cpp
===
--- clang/test/CXX/class/class.compare/class.compare.default/p2.cpp
+++ clang/test/CXX/class/class.compare/class.compare.default/p2.cpp
@@ -39,6 +39,14 @@
   void(a >= a);
 }
 
+struct A3 {
+  int  // expected-note {{because class 'A3' has a reference member}}
+
+  bool operator==(const A3 &) const = default; // expected-warning 
{{implicitly deleted}}
+  bool operator<(const A3 &) const = default;  // expected-warning 
{{implicitly deleted}}
+  // expected-note@-1 {{because there is no viable comparison function}}
+};
+
 struct B1 {
   struct {
 int x;
Index: clang/lib/Sema/SemaDeclCXX.cpp
===
--- clang/lib/Sema/SemaDeclCXX.cpp
+++ clang/lib/Sema/SemaDeclCXX.cpp
@@ -7685,10 +7685,14 @@
 
 if (Args[0]->getType()->isOverloadableType())
   S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
-else {
+else if (OO == OO_EqualEqual ||
+ !Args[0]->getType()->isFunctionPointerType()) {
   // FIXME: We determine whether this is a valid expression by checking to
   // see if there's a viable builtin operator candidate for it. That isn't
   // really what the rules ask us to do, but should give the right results.
+  //
+  // Note that the builtin operator for relational comparisons on function
+  // pointers is the only known case which cannot be used.
   S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, 
CandidateSet);
 }
 


Index: clang/test/CXX/class/class.compare/class.spaceship/p2.cpp
===
--- clang/test/CXX/class/class.compare/class.spaceship/p2.cpp
+++ clang/test/CXX/class/class.compare/class.spaceship/p2.cpp
@@ -155,3 +155,20 @@
 friend CmpCat auto operator<=>(const D&, const D&) = default;
   };
 }
+
+namespace PR48856 {
+  struct A {
+auto operator<=>(const A &) const = 

[clang] 4a8530f - [clang] implicitly delete space ship operator with function pointers

2021-02-26 Thread Richard Smith via cfe-commits

Author: Matheus Izvekov
Date: 2021-02-26T16:03:01-08:00
New Revision: 4a8530fc3039f128eddc38737f0172bb3d489bcf

URL: 
https://github.com/llvm/llvm-project/commit/4a8530fc3039f128eddc38737f0172bb3d489bcf
DIFF: 
https://github.com/llvm/llvm-project/commit/4a8530fc3039f128eddc38737f0172bb3d489bcf.diff

LOG: [clang] implicitly delete space ship operator with function pointers

See bug #48856

Definitions of classes with member function pointers and default
spaceship operator were getting accepted with no diagnostic on
release build, and triggering assert on builds with runtime checks
enabled. Diagnostics were only produced when actually comparing
instances of such classes.

This patch makes it so Spaceship and Less operators are not considered
as builtin operator candidates for function pointers, producing
equivalent diagnostics for the cases where pointers to member function
and pointers to data members are used instead.

Reviewed By: rsmith

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

Added: 


Modified: 
clang/lib/Sema/SemaDeclCXX.cpp
clang/test/CXX/class/class.compare/class.compare.default/p2.cpp
clang/test/CXX/class/class.compare/class.eq/p2.cpp
clang/test/CXX/class/class.compare/class.spaceship/p2.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index cb35f0fb848f3..a150bc9fd766a 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -7685,10 +7685,14 @@ class DefaultedComparisonAnalyzer
 
 if (Args[0]->getType()->isOverloadableType())
   S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
-else {
+else if (OO == OO_EqualEqual ||
+ !Args[0]->getType()->isFunctionPointerType()) {
   // FIXME: We determine whether this is a valid expression by checking to
   // see if there's a viable builtin operator candidate for it. That isn't
   // really what the rules ask us to do, but should give the right results.
+  //
+  // Note that the builtin operator for relational comparisons on function
+  // pointers is the only known case which cannot be used.
   S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, 
CandidateSet);
 }
 

diff  --git a/clang/test/CXX/class/class.compare/class.compare.default/p2.cpp 
b/clang/test/CXX/class/class.compare/class.compare.default/p2.cpp
index cdffd445f7cea..226245ce8a440 100644
--- a/clang/test/CXX/class/class.compare/class.compare.default/p2.cpp
+++ b/clang/test/CXX/class/class.compare/class.compare.default/p2.cpp
@@ -39,6 +39,14 @@ void f(A2 a) {
   void(a >= a);
 }
 
+struct A3 {
+  int  // expected-note {{because class 'A3' has a reference member}}
+
+  bool operator==(const A3 &) const = default; // expected-warning 
{{implicitly deleted}}
+  bool operator<(const A3 &) const = default;  // expected-warning 
{{implicitly deleted}}
+  // expected-note@-1 {{because there is no viable comparison function}}
+};
+
 struct B1 {
   struct {
 int x;

diff  --git a/clang/test/CXX/class/class.compare/class.eq/p2.cpp 
b/clang/test/CXX/class/class.compare/class.eq/p2.cpp
index e5f4a020d5c83..7e9416574eeea 100644
--- a/clang/test/CXX/class/class.compare/class.eq/p2.cpp
+++ b/clang/test/CXX/class/class.compare/class.eq/p2.cpp
@@ -15,6 +15,25 @@ struct E {
 struct F { void operator==(F) const; };
 struct G { bool operator==(G) const = delete; }; // expected-note {{deleted 
here}}
 
+struct H1 {
+  bool operator==(const H1 &) const = default;
+  bool operator<(const H1 &) const = default; // expected-warning {{implicitly 
deleted}}
+  // expected-note@-1 {{because there is no viable comparison function}}
+  void (*x)();
+};
+struct H2 {
+  bool operator==(const H2 &) const = default;
+  bool operator<(const H2 &) const = default; // expected-warning {{implicitly 
deleted}}
+  // expected-note@-1 {{because there is no viable comparison function}}
+  void (H2::*x)();
+};
+struct H3 {
+  bool operator==(const H3 &) const = default;
+  bool operator<(const H3 &) const = default; // expected-warning {{implicitly 
deleted}}
+  // expected-note@-1 {{because there is no viable comparison function}}
+  int H3::*x;
+};
+
 template struct X {
   X();
   bool operator==(const X&) const = default; // #x expected-note 4{{deleted 
here}}

diff  --git a/clang/test/CXX/class/class.compare/class.spaceship/p2.cpp 
b/clang/test/CXX/class/class.compare/class.spaceship/p2.cpp
index dae31e925ba1e..d7f95ee4a6fde 100644
--- a/clang/test/CXX/class/class.compare/class.spaceship/p2.cpp
+++ b/clang/test/CXX/class/class.compare/class.spaceship/p2.cpp
@@ -155,3 +155,20 @@ namespace BadDeducedType {
 friend CmpCat auto operator<=>(const D&, const D&) = default;
   };
 }
+
+namespace PR48856 {
+  struct A {
+auto operator<=>(const A &) const = default; // expected-warning 
{{implicitly deleted}}
+void (*x)(); // 

[PATCH] D94973: [clang][OpenMP] Use OpenMPIRBuilder for workshare loops.

2021-02-26 Thread Joel E. Denny via Phabricator via cfe-commits
jdenny added a comment.

In D94973#2591210 , @Meinersbur wrote:

> In D94973#2590867 , @jdenny wrote:
>
>> One property of this patch that has bothered me is that OMPCanonicalLoop is 
>> not a loop.  Instead, it's an AST node that is sandwiched between a 
>> directive and a loop to contain extra information about the loop.  The 
>> TreeTransform issues we've been discussing highlight how that extra node can 
>> be confusing.
>
> There are many other AST nodes that are sandwiched carrying semantic 
> information. Examples: AttributedStmt, ImplicitCast, CapturedStmt of any 
> OMPExecutableStmt, ExprWithCleanups, CXXRewrittenBinaryOperator, 
> CXXBindTemporaryExpr.

Thanks for the examples.  I never thought of those cases in that way probably 
because they're easier to imagine as distinct constructs or operations.  But 
I'm probably splitting hairs.

> I even think that representing semantic information alongside of syntax is 
> one of the principles of Clang's AST.

Interesting.  Is that documented somewhere?

>> Now I remember that there's D95496 , which 
>> seems not to have that property.  I haven't reviewed that patch in any 
>> detail, and I haven't tried to locate any prior discussions.  Can you please 
>> summarize why you prefer the current patch over that one?
>
> D95496  is a lot more invasive to code that 
> does not even use OpenMP.

Fair enough.




Comment at: clang/lib/Sema/TreeTransform.h:8321
+TreeTransform::TransformOMPCanonicalLoop(OMPCanonicalLoop *L) {
+  // The OMPCanonicalLoop will be recreated when transforming the 
loop-associted
+  // directive.

Meinersbur wrote:
> jdenny wrote:
> > Meinersbur wrote:
> > > jdenny wrote:
> > > > Meinersbur wrote:
> > > > > jdenny wrote:
> > > > > > Meinersbur wrote:
> > > > > > > jdenny wrote:
> > > > > > > > Meinersbur wrote:
> > > > > > > > > jdenny wrote:
> > > > > > > > > > I'm used to seeing `TransformX` call `RebuildX` call 
> > > > > > > > > > `ActOnX`.  Why not do that for `X=OMPCanonicalLoop`?  Does 
> > > > > > > > > > `TransformOMPExecutableDirective` really need a special 
> > > > > > > > > > case for `OMPCanonicalLoop`?
> > > > > > > > > The intended behaviour is: 
> > > > > > > > > 
> > > > > > > > > 1. Transform the child loop
> > > > > > > > > 2. Return the child loop as representing the OMPCanonicalLoop 
> > > > > > > > > (i.e. OMPCanonicalLoop wrapper is removed).
> > > > > > > > > 3. Parent loop-associated directive (e.g. workshare) is 
> > > > > > > > > processed.
> > > > > > > > > 4. `ActOnOpenMPCanonicalLoop` adds new OMPCanonicalLoop 
> > > > > > > > > wrapper for loop nest.
> > > > > > > > > 
> > > > > > > > > This guarantees maximum flexibility on what of the loop can 
> > > > > > > > > be changed, such as
> > > > > > > > > * Change lower bound, upper bound, step
> > > > > > > > > * Convert between CXXForRangeStmt and ForStmt
> > > > > > > > > * Change the associated depth (e.g. different value for 
> > > > > > > > > `collapse` clause)
> > > > > > > > > * Remove the directive and no OMPCanonicalLoop remain
> > > > > > > > > 
> > > > > > > > > This also saves adding many lines of code handling 
> > > > > > > > > transforming each member of OMPCanonicalLoop separately.
> > > > > > > > > The intended behaviour is: 
> > > > > > > > > 
> > > > > > > > > 1. Transform the child loop
> > > > > > > > 
> > > > > > > > For  my suggestion, that call would remain within 
> > > > > > > > `TransformOMPCanonicalLoop` where it is now.
> > > > > > > > 
> > > > > > > > > 2. Return the child loop as representing the OMPCanonicalLoop 
> > > > > > > > > (i.e. OMPCanonicalLoop wrapper is removed).
> > > > > > > > 
> > > > > > > > For my suggestion, this would not happen.  I think it's normal 
> > > > > > > > for a `TransformX` to return the transformed `X` not the 
> > > > > > > > transformed child of `X`.  If a caller wants to transform the 
> > > > > > > > child, then it should transform the child directly instead.
> > > > > > > > 
> > > > > > > > > 3. Parent loop-associated directive (e.g. workshare) is 
> > > > > > > > > processed.
> > > > > > > > 
> > > > > > > > It looks to me like step 3 is currently within 
> > > > > > > > `TransformOMPExecutableDirective` and starts before the call to 
> > > > > > > > `TranformOMPCanonicalLoop` and thus before step 1.  It 
> > > > > > > > completes after step 4.  Or am I misunderstanding what you're 
> > > > > > > > describing as step 3?
> > > > > > > > 
> > > > > > > > > 4. `ActOnOpenMPCanonicalLoop` adds new OMPCanonicalLoop 
> > > > > > > > > wrapper for loop nest.
> > > > > > > > 
> > > > > > > > For my suggestion, this would still happen.  However, instead 
> > > > > > > > of step 2: within `TransformOMPCanonicalLoop`, you would call 
> > > > > > > > `RebuildOMPCanonicalLoop`, which would call 
> > > > > > > > 

[PATCH] D97417: [clangd] use a compatible preamble for the first AST built

2021-02-26 Thread Quentin Chateau via Phabricator via cfe-commits
qchateau updated this revision to Diff 326816.
qchateau added a comment.

- [clangd] make more compile commands compatible
- [clangd] ignore incompatible preamble

  I improved command line compatibility detection (faster & matches more files) 
and I had to blacklist some preambles. Namely, when the file we're building the 
AST for appears in the include tree of a preamble, we can't use it, otherwise 
symbols are missing from the AST. I feel like I understand why, but I have no 
idea how to fix it ...


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97417/new/

https://reviews.llvm.org/D97417

Files:
  clang-tools-extra/clangd/ParsedAST.cpp
  clang-tools-extra/clangd/TUScheduler.cpp
  clang-tools-extra/clangd/TUScheduler.h

Index: clang-tools-extra/clangd/TUScheduler.h
===
--- clang-tools-extra/clangd/TUScheduler.h
+++ clang-tools-extra/clangd/TUScheduler.h
@@ -310,6 +310,8 @@
   /// Responsible for retaining and rebuilding idle ASTs. An implementation is
   /// an LRU cache.
   class ASTCache;
+  /// Store all known preambles
+  class PreambleStore;
 
   // The file being built/processed in the current thread. This is a hack in
   // order to get the file name into the index implementations. Do not depend on
@@ -332,6 +334,7 @@
   Semaphore QuickRunBarrier;
   llvm::StringMap> Files;
   std::unique_ptr IdleASTs;
+  std::unique_ptr Preambles;
   // None when running tasks synchronously and non-None when running tasks
   // asynchronously.
   llvm::Optional PreambleTasks;
Index: clang-tools-extra/clangd/TUScheduler.cpp
===
--- clang-tools-extra/clangd/TUScheduler.cpp
+++ clang-tools-extra/clangd/TUScheduler.cpp
@@ -94,6 +94,62 @@
 
 namespace {
 class ASTWorker;
+
+bool compileCommandsAreSimilar(const tooling::CompileCommand ,
+   const tooling::CompileCommand ) {
+  auto LIt = LHS.CommandLine.begin();
+  auto RIt = RHS.CommandLine.begin();
+
+  auto SkipSpecificArg = [](auto It, auto End, const std::string ) {
+while (It != End) {
+  if (*It == "-o" || *It == "-x") {
+// Erase -o and its argument
+// Erase -x and its argument: it would prevent using header file
+// preamble for a source file
+It = std::min(It + 2, End);
+  } else if (*It == "-c" || It->find("-W") == 0 || *It == "-pedantic") {
+// We don't care about those flags
+It++;
+  } else if (It->find(Filename) != std::string::npos) {
+// The file we're compiling appears in this argument, drop it to make it
+// generic
+It++;
+  } else {
+break;
+  }
+}
+return It;
+  };
+
+  // Iterate the command line, skipping arguments that are specific to the
+  // file being compiled and that would not influence the premable
+  // compatiblity. Stop when one iterate reach the or when an argument differs
+  auto LEnd = LHS.CommandLine.end();
+  auto REnd = RHS.CommandLine.end();
+  while (true) {
+LIt = SkipSpecificArg(LIt, LEnd, LHS.Filename);
+RIt = SkipSpecificArg(RIt, REnd, RHS.Filename);
+
+if (LIt == LEnd || RIt == REnd) {
+  break;
+}
+
+if (*LIt != *RIt) {
+  break;
+}
+
+LIt++;
+RIt++;
+  }
+
+  // If both iterator get to the end at the same time, the CL are compatible
+  bool Compatible = LIt == LEnd && RIt == REnd;
+  if (Compatible) {
+vlog("{0} and {1} are compatible", LHS.Filename, RHS.Filename);
+  }
+  return Compatible;
+}
+
 } // namespace
 
 static clang::clangd::Key kFileBeingProcessed;
@@ -179,6 +235,59 @@
   std::vector LRU; /* GUARDED_BY(Mut) */
 };
 
+class TUScheduler::PreambleStore {
+public:
+  struct Entry {
+std::shared_ptr Preamble;
+size_t Score;
+Path FileName;
+
+bool operator>(const Entry ) const { return Score > Other.Score; }
+  };
+
+  auto getAll() {
+std::unique_lock Lock(Mut);
+return Store;
+  }
+
+  void push(PathRef FileName, std::shared_ptr Preamble) {
+std::unique_lock Lock(Mut);
+auto It = llvm::find_if(
+Store, [&](const auto ) { return Item.FileName == FileName; });
+if (It == Store.end()) {
+  Store.push_back(Entry{std::move(Preamble), 0, FileName.str()});
+  popWorstPreambles();
+}
+vlog("Store contains {0} preambles", Store.size());
+  }
+
+  void hit(PathRef FileName) {
+std::unique_lock Lock(Mut);
+auto It = llvm::find_if(
+Store, [&](const auto ) { return Item.FileName == FileName; });
+if (It == Store.end()) {
+  return;
+}
+It->Score++;
+  }
+
+private:
+  void popWorstPreambles() {
+constexpr int ClosedPreamblesToKeep = 5;
+auto Begin = llvm::partition(
+Store, [](const auto ) { return Item.Preamble.use_count() > 1; });
+if (std::distance(Begin, Store.end()) <= ClosedPreamblesToKeep) {
+  return;
+}
+auto Nth = Begin + 

[PATCH] D96120: [scudo] Port scudo sanitizer to Windows

2021-02-26 Thread Vitaly Buka via Phabricator via cfe-commits
vitalybuka added a comment.

>> This is intended as a step to porting scudo standalone.

Why this is needed for scudo stadalone?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D96120/new/

https://reviews.llvm.org/D96120

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D96120: [scudo] Port scudo sanitizer to Windows

2021-02-26 Thread Martin Storsjö via Phabricator via cfe-commits
mstorsjo added a comment.

In D96120#2590587 , @russell.gallop 
wrote:

> Hi @mstorsjo. Thanks for the suggestions. I tried running up an mingw 
> environment with msys but had trouble getting it working (running into cmake 
> issues). Would you be able to help?

Yeah, building things in that environment is a bit challenging.

> Yes, building and linking a program with -fsanitize=scudo is the simple way 
> to build a simple program. The support for this is in 
> clang/lib/Driver/ToolChains/MSVC.cpp. Would this require support in 
> clang/lib/Driver/ToolChains/MinGW.cpp?

Yes, it would need something similar - I tried whipping something together, 
which after some tweaks seems to work:

  diff --git a/clang/lib/Driver/ToolChains/MinGW.cpp 
b/clang/lib/Driver/ToolChains/MinGW.cpp
  index f6cead412236..aab141377204 100644
  --- a/clang/lib/Driver/ToolChains/MinGW.cpp
  +++ b/clang/lib/Driver/ToolChains/MinGW.cpp
  @@ -260,6 +260,14 @@ void tools::MinGW::Linker::ConstructJob(Compilation , 
const JobAction ,
   }
 }
   
  +  if (Sanitize.needsScudoRt()) {
  +for (const auto  : {"scudo", "scudo_cxx"}) {
  +  CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
  +}
  +CmdArgs.push_back("--require-defined");
  +CmdArgs.push_back(Args.MakeArgString("malloc"));
  +  }
  +
 AddLibGCC(Args, CmdArgs);
   
 if (Args.hasArg(options::OPT_pg))
  @@ -492,6 +500,7 @@ SanitizerMask toolchains::MinGW::getSupportedSanitizers() 
const {
 Res |= SanitizerKind::PointerCompare;
 Res |= SanitizerKind::PointerSubtract;
 Res |= SanitizerKind::Vptr;
  +  Res |= SanitizerKind::Scudo;
 return Res;
   }

Feel free to squash that into your patch (which saves me a bit of effort) :-)

(First I had placed this later in the function, after the asan bits, but in 
that case, it ended up linking against the normal malloc function instead of 
the one from scudo - the libraries that provide malloc end up added via the 
`AddLibGCC()` call.

> I think the best way to test is to run the scudo LIT tests with (e.g.) "ninja 
> check-scudo". These build and run some simple test programs and check that 
> problems are detected.

I didn't try this right now (I primarily cross compile so running tests for the 
runtimes is a bit challenging), but I did test building the double-free.cpp 
test with `-fsanitize=scudo`, and it seems to work as it should for all three 
cases it tests, so with that it seems to be at least roughly working, so I 
think that's good enough to include the clang driver bits in 
ToolChains/MinGW.cpp.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D96120/new/

https://reviews.llvm.org/D96120

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D97567: [clang-tidy] performance-* checks: Also allow allow member expressions to be used in a const manner.

2021-02-26 Thread Felix Berger via Phabricator via cfe-commits
flx updated this revision to Diff 326798.
flx added a comment.

Add tests for PerformanceUnnecssaryCopyInitialization check which actually uses
decl_ref_expr::isOnlyUsedAsConst().


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97567/new/

https://reviews.llvm.org/D97567

Files:
  clang-tools-extra/clang-tidy/utils/DeclRefExprUtils.cpp
  clang-tools-extra/test/clang-tidy/checkers/performance-for-range-copy.cpp
  
clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-copy-initialization.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-copy-initialization.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-copy-initialization.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-copy-initialization.cpp
@@ -508,3 +508,36 @@
   // CHECK-FIXES: const auto& UnnecessaryCopy = Ref.reference();
   Orig.constMethod();
 }
+
+struct Struct {
+  ExpensiveToCopyType Member;
+};
+
+void positiveConstMemberExpr() {
+  Struct Orig;
+  auto UC = Orig;
+  // CHECK-MESSAGES: [[@LINE-1]]:8: warning: local copy 'UC'
+  // CHECK-FIXES: const auto& UC = Orig;
+  const auto  = UC.Member;
+  auto MemberCopy = UC.Member;
+  bool b = UC.Member.constMethod();
+  useByValue(UC.Member);
+  useAsConstReference(UC.Member);
+  useByValue(UC.Member);
+}
+
+void negativeNonConstMemberExpr() {
+  Struct Orig;
+  {
+auto Copy = Orig;
+Copy.Member.nonConstMethod();
+  }
+  {
+auto Copy = Orig;
+mutate(Copy.Member);
+  }
+  {
+auto Copy = Orig;
+mutate();
+  }
+}
Index: clang-tools-extra/test/clang-tidy/checkers/performance-for-range-copy.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/performance-for-range-copy.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/performance-for-range-copy.cpp
@@ -296,3 +296,37 @@
 // SS : createView(*ValueReturningIterator())) {
   }
 }
+
+void positiveConstMemberExpr() {
+  struct Struct {
+Mutable Member;
+  };
+  for (Struct SS : View>()) {
+// CHECK-MESSAGES: [[@LINE-1]]:15: warning: loop variable is copied
+// CHECK-FIXES: for (const Struct& SS : View>()) {
+auto MemberCopy = SS.Member;
+const auto  = SS.Member;
+bool b = SS.Member.constMethod();
+use(SS.Member);
+useByConstValue(SS.Member);
+useByValue(SS.Member);
+  }
+}
+
+void negativeNonConstMemberExpr() {
+  struct Struct {
+Mutable Member;
+  };
+  for (Struct SS : View>()) {
+SS.Member.setBool(true);
+  }
+  for (Struct SS : View>()) {
+SS.Member[1];
+  }
+  for (Struct SS : View>()) {
+mutate(SS.Member);
+  }
+  for (Struct SS : View>()) {
+mutate();
+  }
+}
Index: clang-tools-extra/clang-tidy/utils/DeclRefExprUtils.cpp
===
--- clang-tools-extra/clang-tidy/utils/DeclRefExprUtils.cpp
+++ clang-tools-extra/clang-tidy/utils/DeclRefExprUtils.cpp
@@ -46,14 +46,19 @@
ASTContext ) {
   auto DeclRefToVar =
   declRefExpr(to(varDecl(equalsNode(.bind("declRef");
+  auto MemberExprOfVar = memberExpr(has(DeclRefToVar));
+  auto DeclRefToVarOrMemberExprOfVar =
+  stmt(anyOf(DeclRefToVar, MemberExprOfVar));
   auto ConstMethodCallee = callee(cxxMethodDecl(isConst()));
   // Match method call expressions where the variable is referenced as the this
   // implicit object argument and opertor call expression for member operators
   // where the variable is the 0-th argument.
   auto Matches = match(
-  findAll(expr(anyOf(cxxMemberCallExpr(ConstMethodCallee, on(DeclRefToVar)),
- cxxOperatorCallExpr(ConstMethodCallee,
- hasArgument(0, DeclRefToVar),
+  findAll(expr(anyOf(
+  cxxMemberCallExpr(ConstMethodCallee,
+on(DeclRefToVarOrMemberExprOfVar)),
+  cxxOperatorCallExpr(ConstMethodCallee,
+  hasArgument(0, DeclRefToVarOrMemberExprOfVar),
   Stmt, Context);
   SmallPtrSet DeclRefs;
   extractNodesByIdTo(Matches, "declRef", DeclRefs);
@@ -65,22 +70,23 @@
   ConstReferenceOrValue,
   substTemplateTypeParmType(hasReplacementType(ConstReferenceOrValue;
   auto UsedAsConstRefOrValueArg = forEachArgumentWithParam(
-  DeclRefToVar, parmVarDecl(hasType(ConstReferenceOrValueOrReplaced)));
+  DeclRefToVarOrMemberExprOfVar,
+  parmVarDecl(hasType(ConstReferenceOrValueOrReplaced)));
   Matches = match(findAll(invocation(UsedAsConstRefOrValueArg)), Stmt, Context);
   extractNodesByIdTo(Matches, "declRef", DeclRefs);
   // References and pointers to const assignments.
-  Matches =
-  match(findAll(declStmt(
-has(varDecl(hasType(qualType(matchers::isReferenceToConst())),
-

[PATCH] D97449: [Diagnose] Unify MCContext and LLVMContext diagnosing

2021-02-26 Thread Yuanfang Chen via Phabricator via cfe-commits
ychen updated this revision to Diff 326797.
ychen added a comment.

- Simplify MCContext changes.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97449/new/

https://reviews.llvm.org/D97449

Files:
  clang/lib/CodeGen/CodeGenAction.cpp
  lldb/source/Expression/IRExecutionUnit.cpp
  llvm/include/llvm/CodeGen/AsmPrinter.h
  llvm/include/llvm/IR/DiagnosticInfo.h
  llvm/include/llvm/IR/LLVMContext.h
  llvm/include/llvm/MC/MCContext.h
  llvm/lib/CodeGen/AsmPrinter/AsmPrinterInlineAsm.cpp
  llvm/lib/CodeGen/MachineModuleInfo.cpp
  llvm/lib/IR/LLVMContext.cpp
  llvm/lib/IR/LLVMContextImpl.h
  llvm/lib/MC/MCContext.cpp
  llvm/lib/MC/MCParser/AsmParser.cpp
  llvm/test/CodeGen/AMDGPU/lds-initializer.ll
  llvm/test/CodeGen/AMDGPU/lds-zero-initializer.ll
  llvm/test/CodeGen/XCore/section-name.ll
  llvm/tools/llc/llc.cpp

Index: llvm/tools/llc/llc.cpp
===
--- llvm/tools/llc/llc.cpp
+++ llvm/tools/llc/llc.cpp
@@ -290,6 +290,22 @@
   bool *HasError;
   LLCDiagnosticHandler(bool *HasErrorPtr) : HasError(HasErrorPtr) {}
   bool handleDiagnostics(const DiagnosticInfo ) override {
+if (DI.getKind() == llvm::DK_SrcMgr) {
+  const auto  = cast(DI);
+  const SMDiagnostic  = DISM.getSMDiag();
+
+  if (SMD.getKind() == SourceMgr::DK_Error)
+*HasError = true;
+
+  SMD.print(nullptr, errs());
+
+  // For testing purposes, we print the LocCookie here.
+  if (DISM.isInlineAsmDiag() && DISM.getLocCookie())
+WithColor::note() << "!srcloc = " << DISM.getLocCookie() << "\n";
+
+  return true;
+}
+
 if (DI.getSeverity() == DS_Error)
   *HasError = true;
 
@@ -305,19 +321,6 @@
   }
 };
 
-static void InlineAsmDiagHandler(const SMDiagnostic , void *Context,
- unsigned LocCookie) {
-  bool *HasError = static_cast(Context);
-  if (SMD.getKind() == SourceMgr::DK_Error)
-*HasError = true;
-
-  SMD.print(nullptr, errs());
-
-  // For testing purposes, we print the LocCookie here.
-  if (LocCookie)
-WithColor::note() << "!srcloc = " << LocCookie << "\n";
-}
-
 // main - Entry point for the llc compiler.
 //
 int main(int argc, char **argv) {
@@ -367,7 +370,6 @@
   bool HasError = false;
   Context.setDiagnosticHandler(
   std::make_unique());
-  Context.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, );
 
   Expected> RemarksFileOrErr =
   setupLLVMOptimizationRemarks(Context, RemarksFilename, RemarksPasses,
Index: llvm/test/CodeGen/XCore/section-name.ll
===
--- llvm/test/CodeGen/XCore/section-name.ll
+++ llvm/test/CodeGen/XCore/section-name.ll
@@ -1,4 +1,4 @@
-; RUN: llc < %s -march=xcore -o /dev/null 2>&1 | FileCheck %s
+; RUN: not llc < %s -march=xcore -o /dev/null 2>&1 | FileCheck %s
 
 @bar = internal global i32 zeroinitializer
 
Index: llvm/test/CodeGen/AMDGPU/lds-zero-initializer.ll
===
--- llvm/test/CodeGen/AMDGPU/lds-zero-initializer.ll
+++ llvm/test/CodeGen/AMDGPU/lds-zero-initializer.ll
@@ -1,5 +1,5 @@
-; RUN: llc -march=amdgcn -mcpu=tahiti < %s -o /dev/null 2>&1 | FileCheck %s
-; RUN: llc -march=amdgcn -mcpu=tonga < %s -o /dev/null 2>&1 | FileCheck %s
+; RUN: not llc -march=amdgcn -mcpu=tahiti < %s -o /dev/null 2>&1 | FileCheck %s
+; RUN: not llc -march=amdgcn -mcpu=tonga < %s -o /dev/null 2>&1 | FileCheck %s
 
 ; CHECK: lds: unsupported initializer for address space
 
Index: llvm/test/CodeGen/AMDGPU/lds-initializer.ll
===
--- llvm/test/CodeGen/AMDGPU/lds-initializer.ll
+++ llvm/test/CodeGen/AMDGPU/lds-initializer.ll
@@ -1,5 +1,5 @@
-; RUN: llc -march=amdgcn -mcpu=tahiti < %s -o /dev/null 2>&1 | FileCheck %s
-; RUN: llc -march=amdgcn -mcpu=tonga < %s -o /dev/null 2>&1 | FileCheck %s
+; RUN: not llc -march=amdgcn -mcpu=tahiti < %s -o /dev/null 2>&1 | FileCheck %s
+; RUN: not llc -march=amdgcn -mcpu=tonga < %s -o /dev/null 2>&1 | FileCheck %s
 
 ; CHECK: lds: unsupported initializer for address space
 
Index: llvm/lib/MC/MCParser/AsmParser.cpp
===
--- llvm/lib/MC/MCParser/AsmParser.cpp
+++ llvm/lib/MC/MCParser/AsmParser.cpp
@@ -2348,7 +2348,7 @@
 /// will use the last parsed cpp hash line filename comment
 /// for the Filename and LineNo if any in the diagnostic.
 void AsmParser::DiagHandler(const SMDiagnostic , void *Context) {
-  const AsmParser *Parser = static_cast(Context);
+  auto *Parser = static_cast(Context);
   raw_ostream  = errs();
 
   const SourceMgr  = *Diag.getSourceMgr();
@@ -2369,12 +2369,8 @@
   // If we have not parsed a cpp hash line filename comment or the source
   // manager changed or buffer changed (like in a nested include) then just
   // print the normal diagnostic using its Filename and LineNo.
-  if (!Parser->CppHashInfo.LineNumber ||  

[PATCH] D94973: [clang][OpenMP] Use OpenMPIRBuilder for workshare loops.

2021-02-26 Thread Michael Kruse via Phabricator via cfe-commits
Meinersbur added a comment.

In D94973#2590867 , @jdenny wrote:

> One property of this patch that has bothered me is that OMPCanonicalLoop is 
> not a loop.  Instead, it's an AST node that is sandwiched between a directive 
> and a loop to contain extra information about the loop.  The TreeTransform 
> issues we've been discussing highlight how that extra node can be confusing.

There are many other AST nodes that are sandwiched carrying semantic 
information. Examples: AttributedStmt, ImplicitCast, CapturedStmt of any 
OMPExecutableStmt, ExprWithCleanups, CXXRewrittenBinaryOperator, 
CXXBindTemporaryExpr. I even think that representing semantic information 
alongside of syntax is one of the principles of Clang's AST.

> Now I remember that there's D95496 , which 
> seems not to have that property.  I haven't reviewed that patch in any 
> detail, and I haven't tried to locate any prior discussions.  Can you please 
> summarize why you prefer the current patch over that one?

D95496  is a lot more invasive to code that 
does not even use OpenMP. E.g. 
it increases the object size of any ForStmt or CXXForRangeStmt even if not used 
as an OpenMP loop-associated construct.
ForStmt and CXXForRangeStmt have a new base class called 
`MaybeCanonicalLoopStmt` fow which I could not find a better name. Because I 
cannot put the common new fields (DISTANCE_FUNC, LOOPVAR_FUNC, LOOPVAR_REF) at 
the beginning of the SubStmt list without big compatibility issues, they have 
to be put at the and and requires `getCanonicalChildren()` to access them 
without a switch for which of the derived classes it actually is.
It also introduces a variable number of children for those two statements.

On the other side, sandwiching implicit semantics is already pretty common in 
the AST.




Comment at: clang/lib/Sema/TreeTransform.h:8321
+TreeTransform::TransformOMPCanonicalLoop(OMPCanonicalLoop *L) {
+  // The OMPCanonicalLoop will be recreated when transforming the 
loop-associted
+  // directive.

jdenny wrote:
> Meinersbur wrote:
> > jdenny wrote:
> > > Meinersbur wrote:
> > > > jdenny wrote:
> > > > > Meinersbur wrote:
> > > > > > jdenny wrote:
> > > > > > > Meinersbur wrote:
> > > > > > > > jdenny wrote:
> > > > > > > > > I'm used to seeing `TransformX` call `RebuildX` call 
> > > > > > > > > `ActOnX`.  Why not do that for `X=OMPCanonicalLoop`?  Does 
> > > > > > > > > `TransformOMPExecutableDirective` really need a special case 
> > > > > > > > > for `OMPCanonicalLoop`?
> > > > > > > > The intended behaviour is: 
> > > > > > > > 
> > > > > > > > 1. Transform the child loop
> > > > > > > > 2. Return the child loop as representing the OMPCanonicalLoop 
> > > > > > > > (i.e. OMPCanonicalLoop wrapper is removed).
> > > > > > > > 3. Parent loop-associated directive (e.g. workshare) is 
> > > > > > > > processed.
> > > > > > > > 4. `ActOnOpenMPCanonicalLoop` adds new OMPCanonicalLoop wrapper 
> > > > > > > > for loop nest.
> > > > > > > > 
> > > > > > > > This guarantees maximum flexibility on what of the loop can be 
> > > > > > > > changed, such as
> > > > > > > > * Change lower bound, upper bound, step
> > > > > > > > * Convert between CXXForRangeStmt and ForStmt
> > > > > > > > * Change the associated depth (e.g. different value for 
> > > > > > > > `collapse` clause)
> > > > > > > > * Remove the directive and no OMPCanonicalLoop remain
> > > > > > > > 
> > > > > > > > This also saves adding many lines of code handling transforming 
> > > > > > > > each member of OMPCanonicalLoop separately.
> > > > > > > > The intended behaviour is: 
> > > > > > > > 
> > > > > > > > 1. Transform the child loop
> > > > > > > 
> > > > > > > For  my suggestion, that call would remain within 
> > > > > > > `TransformOMPCanonicalLoop` where it is now.
> > > > > > > 
> > > > > > > > 2. Return the child loop as representing the OMPCanonicalLoop 
> > > > > > > > (i.e. OMPCanonicalLoop wrapper is removed).
> > > > > > > 
> > > > > > > For my suggestion, this would not happen.  I think it's normal 
> > > > > > > for a `TransformX` to return the transformed `X` not the 
> > > > > > > transformed child of `X`.  If a caller wants to transform the 
> > > > > > > child, then it should transform the child directly instead.
> > > > > > > 
> > > > > > > > 3. Parent loop-associated directive (e.g. workshare) is 
> > > > > > > > processed.
> > > > > > > 
> > > > > > > It looks to me like step 3 is currently within 
> > > > > > > `TransformOMPExecutableDirective` and starts before the call to 
> > > > > > > `TranformOMPCanonicalLoop` and thus before step 1.  It completes 
> > > > > > > after step 4.  Or am I misunderstanding what you're describing as 
> > > > > > > step 3?
> > > > > > > 
> > > > > > > > 4. `ActOnOpenMPCanonicalLoop` adds new OMPCanonicalLoop wrapper 
> > > > > > > > for loop nest.
> > > > > > > 
> > > > > > > 

[PATCH] D97577: [clang-tidy] performance-for-range-copy: Don't trigger on implicit type conversions.

2021-02-26 Thread Felix Berger via Phabricator via cfe-commits
flx updated this revision to Diff 326793.
flx added a comment.

Remove include.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97577/new/

https://reviews.llvm.org/D97577

Files:
  clang-tools-extra/clang-tidy/performance/ForRangeCopyCheck.cpp
  clang-tools-extra/test/clang-tidy/checkers/performance-for-range-copy.cpp


Index: clang-tools-extra/test/clang-tidy/checkers/performance-for-range-copy.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/performance-for-range-copy.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/performance-for-range-copy.cpp
@@ -60,13 +60,13 @@
 
 void negativeUserDefinedConversion() {
   Convertible C[0];
-  for (const S  : C) {
+  for (const S S1 : C) {
   }
 }
 
 void negativeImplicitConstructorConversion() {
   ConstructorConvertible C[0];
-  for (const S  : C) {
+  for (const S S1 : C) {
   }
 }
 
Index: clang-tools-extra/clang-tidy/performance/ForRangeCopyCheck.cpp
===
--- clang-tools-extra/clang-tidy/performance/ForRangeCopyCheck.cpp
+++ clang-tools-extra/clang-tidy/performance/ForRangeCopyCheck.cpp
@@ -45,10 +45,14 @@
   hasOverloadedOperatorName("*"),
   callee(
   cxxMethodDecl(returns(unless(hasCanonicalType(referenceType()));
+  auto NotConstructedByCopy = cxxConstructExpr(
+  hasDeclaration(cxxConstructorDecl(unless(isCopyConstructor();
+  auto ConstructedByConversion = 
cxxMemberCallExpr(callee(cxxConversionDecl()));
   auto LoopVar =
   varDecl(HasReferenceOrPointerTypeOrIsAllowed,
-  unless(hasInitializer(expr(hasDescendant(expr(anyOf(
-  materializeTemporaryExpr(), IteratorReturnsValueType)));
+  unless(hasInitializer(expr(hasDescendant(expr(
+  anyOf(materializeTemporaryExpr(), IteratorReturnsValueType,
+NotConstructedByCopy, ConstructedByConversion)));
   Finder->addMatcher(
   traverse(TK_AsIs,
cxxForRangeStmt(hasLoopVariable(LoopVar.bind("loopVar")))


Index: clang-tools-extra/test/clang-tidy/checkers/performance-for-range-copy.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/performance-for-range-copy.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/performance-for-range-copy.cpp
@@ -60,13 +60,13 @@
 
 void negativeUserDefinedConversion() {
   Convertible C[0];
-  for (const S  : C) {
+  for (const S S1 : C) {
   }
 }
 
 void negativeImplicitConstructorConversion() {
   ConstructorConvertible C[0];
-  for (const S  : C) {
+  for (const S S1 : C) {
   }
 }
 
Index: clang-tools-extra/clang-tidy/performance/ForRangeCopyCheck.cpp
===
--- clang-tools-extra/clang-tidy/performance/ForRangeCopyCheck.cpp
+++ clang-tools-extra/clang-tidy/performance/ForRangeCopyCheck.cpp
@@ -45,10 +45,14 @@
   hasOverloadedOperatorName("*"),
   callee(
   cxxMethodDecl(returns(unless(hasCanonicalType(referenceType()));
+  auto NotConstructedByCopy = cxxConstructExpr(
+  hasDeclaration(cxxConstructorDecl(unless(isCopyConstructor();
+  auto ConstructedByConversion = cxxMemberCallExpr(callee(cxxConversionDecl()));
   auto LoopVar =
   varDecl(HasReferenceOrPointerTypeOrIsAllowed,
-  unless(hasInitializer(expr(hasDescendant(expr(anyOf(
-  materializeTemporaryExpr(), IteratorReturnsValueType)));
+  unless(hasInitializer(expr(hasDescendant(expr(
+  anyOf(materializeTemporaryExpr(), IteratorReturnsValueType,
+NotConstructedByCopy, ConstructedByConversion)));
   Finder->addMatcher(
   traverse(TK_AsIs,
cxxForRangeStmt(hasLoopVariable(LoopVar.bind("loopVar")))
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D97577: [clang-tidy] performance-for-range-copy: Don't trigger on implicit type conversions.

2021-02-26 Thread Felix Berger via Phabricator via cfe-commits
flx updated this revision to Diff 326792.
flx added a comment.

Remove include.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97577/new/

https://reviews.llvm.org/D97577

Files:
  clang-tools-extra/clang-tidy/performance/ForRangeCopyCheck.cpp
  clang-tools-extra/test/clang-tidy/checkers/performance-for-range-copy.cpp


Index: clang-tools-extra/test/clang-tidy/checkers/performance-for-range-copy.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/performance-for-range-copy.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/performance-for-range-copy.cpp
@@ -60,13 +60,13 @@
 
 void negativeUserDefinedConversion() {
   Convertible C[0];
-  for (const S  : C) {
+  for (const S S1 : C) {
   }
 }
 
 void negativeImplicitConstructorConversion() {
   ConstructorConvertible C[0];
-  for (const S  : C) {
+  for (const S S1 : C) {
   }
 }
 
Index: clang-tools-extra/clang-tidy/performance/ForRangeCopyCheck.cpp
===
--- clang-tools-extra/clang-tidy/performance/ForRangeCopyCheck.cpp
+++ clang-tools-extra/clang-tidy/performance/ForRangeCopyCheck.cpp
@@ -12,6 +12,7 @@
 #include "../utils/Matchers.h"
 #include "../utils/OptionsUtils.h"
 #include "../utils/TypeTraits.h"
+#include 
"third_party/llvm/llvm-project/clang/include/clang/ASTMatchers/ASTMatchers.h"
 #include "clang/Analysis/Analyses/ExprMutationAnalyzer.h"
 #include "clang/Basic/Diagnostic.h"
 
@@ -45,10 +46,14 @@
   hasOverloadedOperatorName("*"),
   callee(
   cxxMethodDecl(returns(unless(hasCanonicalType(referenceType()));
+  auto NotConstructedByCopy = cxxConstructExpr(
+  hasDeclaration(cxxConstructorDecl(unless(isCopyConstructor();
+  auto ConstructedByConversion = 
cxxMemberCallExpr(callee(cxxConversionDecl()));
   auto LoopVar =
   varDecl(HasReferenceOrPointerTypeOrIsAllowed,
-  unless(hasInitializer(expr(hasDescendant(expr(anyOf(
-  materializeTemporaryExpr(), IteratorReturnsValueType)));
+  unless(hasInitializer(expr(hasDescendant(expr(
+  anyOf(materializeTemporaryExpr(), IteratorReturnsValueType,
+NotConstructedByCopy, ConstructedByConversion)));
   Finder->addMatcher(
   traverse(TK_AsIs,
cxxForRangeStmt(hasLoopVariable(LoopVar.bind("loopVar")))


Index: clang-tools-extra/test/clang-tidy/checkers/performance-for-range-copy.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/performance-for-range-copy.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/performance-for-range-copy.cpp
@@ -60,13 +60,13 @@
 
 void negativeUserDefinedConversion() {
   Convertible C[0];
-  for (const S  : C) {
+  for (const S S1 : C) {
   }
 }
 
 void negativeImplicitConstructorConversion() {
   ConstructorConvertible C[0];
-  for (const S  : C) {
+  for (const S S1 : C) {
   }
 }
 
Index: clang-tools-extra/clang-tidy/performance/ForRangeCopyCheck.cpp
===
--- clang-tools-extra/clang-tidy/performance/ForRangeCopyCheck.cpp
+++ clang-tools-extra/clang-tidy/performance/ForRangeCopyCheck.cpp
@@ -12,6 +12,7 @@
 #include "../utils/Matchers.h"
 #include "../utils/OptionsUtils.h"
 #include "../utils/TypeTraits.h"
+#include "third_party/llvm/llvm-project/clang/include/clang/ASTMatchers/ASTMatchers.h"
 #include "clang/Analysis/Analyses/ExprMutationAnalyzer.h"
 #include "clang/Basic/Diagnostic.h"
 
@@ -45,10 +46,14 @@
   hasOverloadedOperatorName("*"),
   callee(
   cxxMethodDecl(returns(unless(hasCanonicalType(referenceType()));
+  auto NotConstructedByCopy = cxxConstructExpr(
+  hasDeclaration(cxxConstructorDecl(unless(isCopyConstructor();
+  auto ConstructedByConversion = cxxMemberCallExpr(callee(cxxConversionDecl()));
   auto LoopVar =
   varDecl(HasReferenceOrPointerTypeOrIsAllowed,
-  unless(hasInitializer(expr(hasDescendant(expr(anyOf(
-  materializeTemporaryExpr(), IteratorReturnsValueType)));
+  unless(hasInitializer(expr(hasDescendant(expr(
+  anyOf(materializeTemporaryExpr(), IteratorReturnsValueType,
+NotConstructedByCopy, ConstructedByConversion)));
   Finder->addMatcher(
   traverse(TK_AsIs,
cxxForRangeStmt(hasLoopVariable(LoopVar.bind("loopVar")))
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D97577: [clang-tidy] performance-for-range-copy: Don't trigger on implicit type conversions.

2021-02-26 Thread Felix Berger via Phabricator via cfe-commits
flx created this revision.
flx added reviewers: aaron.ballman, alexfh, sbenza.
Herald added a subscriber: xazax.hun.
flx requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This disables the check for false positive cases where implicit type conversion
through either an implicit single argument constructor or a member conversion
operator is triggered when constructing the loop variable.

Fix the test cases that meant to cover these cases.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D97577

Files:
  clang-tools-extra/clang-tidy/performance/ForRangeCopyCheck.cpp
  clang-tools-extra/test/clang-tidy/checkers/performance-for-range-copy.cpp


Index: clang-tools-extra/test/clang-tidy/checkers/performance-for-range-copy.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/performance-for-range-copy.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/performance-for-range-copy.cpp
@@ -60,13 +60,13 @@
 
 void negativeUserDefinedConversion() {
   Convertible C[0];
-  for (const S  : C) {
+  for (const S S1 : C) {
   }
 }
 
 void negativeImplicitConstructorConversion() {
   ConstructorConvertible C[0];
-  for (const S  : C) {
+  for (const S S1 : C) {
   }
 }
 
Index: clang-tools-extra/clang-tidy/performance/ForRangeCopyCheck.cpp
===
--- clang-tools-extra/clang-tidy/performance/ForRangeCopyCheck.cpp
+++ clang-tools-extra/clang-tidy/performance/ForRangeCopyCheck.cpp
@@ -12,6 +12,7 @@
 #include "../utils/Matchers.h"
 #include "../utils/OptionsUtils.h"
 #include "../utils/TypeTraits.h"
+#include 
"third_party/llvm/llvm-project/clang/include/clang/ASTMatchers/ASTMatchers.h"
 #include "clang/Analysis/Analyses/ExprMutationAnalyzer.h"
 #include "clang/Basic/Diagnostic.h"
 
@@ -45,10 +46,14 @@
   hasOverloadedOperatorName("*"),
   callee(
   cxxMethodDecl(returns(unless(hasCanonicalType(referenceType()));
+  auto NotConstructedByCopy = cxxConstructExpr(
+  hasDeclaration(cxxConstructorDecl(unless(isCopyConstructor();
+  auto ConstructedByConversion = 
cxxMemberCallExpr(callee(cxxConversionDecl()));
   auto LoopVar =
   varDecl(HasReferenceOrPointerTypeOrIsAllowed,
-  unless(hasInitializer(expr(hasDescendant(expr(anyOf(
-  materializeTemporaryExpr(), IteratorReturnsValueType)));
+  unless(hasInitializer(expr(hasDescendant(expr(
+  anyOf(materializeTemporaryExpr(), IteratorReturnsValueType,
+NotConstructedByCopy, ConstructedByConversion)));
   Finder->addMatcher(
   traverse(TK_AsIs,
cxxForRangeStmt(hasLoopVariable(LoopVar.bind("loopVar")))


Index: clang-tools-extra/test/clang-tidy/checkers/performance-for-range-copy.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/performance-for-range-copy.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/performance-for-range-copy.cpp
@@ -60,13 +60,13 @@
 
 void negativeUserDefinedConversion() {
   Convertible C[0];
-  for (const S  : C) {
+  for (const S S1 : C) {
   }
 }
 
 void negativeImplicitConstructorConversion() {
   ConstructorConvertible C[0];
-  for (const S  : C) {
+  for (const S S1 : C) {
   }
 }
 
Index: clang-tools-extra/clang-tidy/performance/ForRangeCopyCheck.cpp
===
--- clang-tools-extra/clang-tidy/performance/ForRangeCopyCheck.cpp
+++ clang-tools-extra/clang-tidy/performance/ForRangeCopyCheck.cpp
@@ -12,6 +12,7 @@
 #include "../utils/Matchers.h"
 #include "../utils/OptionsUtils.h"
 #include "../utils/TypeTraits.h"
+#include "third_party/llvm/llvm-project/clang/include/clang/ASTMatchers/ASTMatchers.h"
 #include "clang/Analysis/Analyses/ExprMutationAnalyzer.h"
 #include "clang/Basic/Diagnostic.h"
 
@@ -45,10 +46,14 @@
   hasOverloadedOperatorName("*"),
   callee(
   cxxMethodDecl(returns(unless(hasCanonicalType(referenceType()));
+  auto NotConstructedByCopy = cxxConstructExpr(
+  hasDeclaration(cxxConstructorDecl(unless(isCopyConstructor();
+  auto ConstructedByConversion = cxxMemberCallExpr(callee(cxxConversionDecl()));
   auto LoopVar =
   varDecl(HasReferenceOrPointerTypeOrIsAllowed,
-  unless(hasInitializer(expr(hasDescendant(expr(anyOf(
-  materializeTemporaryExpr(), IteratorReturnsValueType)));
+  unless(hasInitializer(expr(hasDescendant(expr(
+  anyOf(materializeTemporaryExpr(), IteratorReturnsValueType,
+NotConstructedByCopy, ConstructedByConversion)));
   Finder->addMatcher(
   traverse(TK_AsIs,
cxxForRangeStmt(hasLoopVariable(LoopVar.bind("loopVar")))
___
cfe-commits mailing list
cfe-commits@lists.llvm.org

[PATCH] D97411: [DebugInfo] Add an attribute to force type info to be emitted for types that are required to be complete.

2021-02-26 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 326787.
akhuang marked 3 inline comments as done.
akhuang added a comment.

address comments


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97411/new/

https://reviews.llvm.org/D97411

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/test/CodeGenCXX/standalone-debug-attribute.cpp
  clang/test/Sema/attr-standalonedebug.cpp

Index: clang/test/Sema/attr-standalonedebug.cpp
===
--- /dev/null
+++ clang/test/Sema/attr-standalonedebug.cpp
@@ -0,0 +1,14 @@
+// RUN: %clang_cc1 %s -verify -fsyntax-only
+// RUN: %clang_cc1 %s -verify -fsyntax-only -x c
+
+#ifdef __cplusplus
+int a __attribute__((standalone_debug)); // expected-warning {{'standalone_debug' attribute only applies to classes}}
+
+void __attribute__((standalone_debug)) b(); // expected-warning {{'standalone_debug' attribute only applies to classes}}
+
+struct __attribute__((standalone_debug(1))) c {}; // expected-error {{'standalone_debug' attribute takes no arguments}}
+
+#else
+// Check that attribute only works in C++.
+struct __attribute__((standalone_debug)) a {}; // expected-warning {{'standalone_debug' attribute ignored}}
+#endif
Index: clang/test/CodeGenCXX/standalone-debug-attribute.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/standalone-debug-attribute.cpp
@@ -0,0 +1,54 @@
+// RUN: %clang_cc1 -DSETATTR=0 -triple x86_64-unknown-linux-gnu -emit-llvm -debug-info-kind=constructor %s -o - | FileCheck %s --check-prefix=DEBUG
+// RUN: %clang_cc1 -DSETATTR=1 -triple x86_64-unknown-linux-gnu -emit-llvm -debug-info-kind=constructor %s -o - | FileCheck %s --check-prefix=WITHATTR
+// Use -debug-info-kind=constructor because it includes all the optimizations.
+
+#if SETATTR
+#define STANDALONEDEBUGATTR __attribute__((standalone_debug))
+#else
+#define STANDALONEDEBUGATTR
+#endif
+
+struct STANDALONEDEBUGATTR StructWithConstructor {
+  StructWithConstructor() {}
+};
+void f(StructWithConstructor s) {}
+// DEBUG:  !DICompositeType({{.*}}name: "StructWithConstructor"
+// DEBUG-SAME:  flags: {{.*}}DIFlagFwdDecl
+// WITHATTR: !DICompositeType({{.*}}name: "StructWithConstructor"
+// WITHATTR-NOT: DIFlagFwdDecl
+
+union STANDALONEDEBUGATTR UnionWithConstructor {
+  UnionWithConstructor() {}
+};
+void f(UnionWithConstructor u) {}
+// DEBUG:  !DICompositeType({{.*}}name: "UnionWithConstructor"
+// DEBUG-SAME:  flags: {{.*}}DIFlagFwdDecl
+// WITHATTR: !DICompositeType({{.*}}name: "UnionWithConstructor"
+// WITHATTR-NOT: DIFlagFwdDecl
+
+template  struct ExternTemplate {
+  ExternTemplate() {}
+  T x;
+};
+extern template struct STANDALONEDEBUGATTR ExternTemplate;
+void f(ExternTemplate s) {}
+// DEBUG: !DICompositeType({{.*}}name: "ExternTemplate"
+// DEBUG-SAME: flags: {{.*}}DIFlagFwdDecl
+// WITHATTR: !DICompositeType({{.*}}name: "ExternTemplate"
+// WITHATTR-NOT: DIFlagFwdDecl
+
+struct STANDALONEDEBUGATTR CompleteTypeRequired {};
+void f(CompleteTypeRequired ) {}
+// DEBUG: !DICompositeType({{.*}}name: "CompleteTypeRequired"
+// DEBUG-SAME: flags: {{.*}}DIFlagFwdDecl
+// WITHATTR: !DICompositeType({{.*}}name: "CompleteTypeRequired"
+// WITHATTR-NOT: DIFlagFwdDecl
+
+struct STANDALONEDEBUGATTR Redecl;
+struct Redecl {};
+void f(Redecl ) {}
+// DEBUG: !DICompositeType({{.*}}name: "Redecl"
+// DEBUG-SAME: flags: {{.*}}DIFlagFwdDecl
+// WITHATTR: !DICompositeType({{.*}}name: "Redecl"
+// WITHATTR-NOT: DIFlagFwdDecl
+
Index: clang/lib/CodeGen/CGDebugInfo.cpp
===
--- clang/lib/CodeGen/CGDebugInfo.cpp
+++ clang/lib/CodeGen/CGDebugInfo.cpp
@@ -2385,7 +2385,8 @@
   if (DebugKind == codegenoptions::DebugLineTablesOnly)
 return true;
 
-  if (DebugKind > codegenoptions::LimitedDebugInfo)
+  if (DebugKind > codegenoptions::LimitedDebugInfo ||
+  RD->hasAttr())
 return false;
 
   if (!LangOpts.CPlusPlus)
Index: clang/include/clang/Basic/AttrDocs.td
===
--- clang/include/clang/Basic/AttrDocs.td
+++ clang/include/clang/Basic/AttrDocs.td
@@ -1053,6 +1053,16 @@
   }];
 }
 
+def StandaloneDebugDocs : Documentation {
+  let Category = DocCatVariable;
+  let Content = [{
+The ``standalone_debug`` attribute causes debug info to be emitted for a record
+type regardless of the debug info optimizations that are enabled with
+-fno-standalone-debug. This attribute only has an effect when debug info
+optimizations are enabled (e.g. with -fno-standalone-debug), and is C++-only.
+  }];
+}
+
 def NoDuplicateDocs : Documentation {
   let Category = DocCatFunction;
   let Content = [{
Index: clang/include/clang/Basic/Attr.td
===
--- 

[PATCH] D97411: [DebugInfo] Add an attribute to force type info to be emitted for types that are required to be complete.

2021-02-26 Thread Amy Huang via Phabricator via cfe-commits
akhuang added a comment.

In D97411#2591030 , @aaron.ballman 
wrote:

> Thanks! I am still curious about the forward declare/redeclaration behavior 
> and whether that is a situation that makes sense or not. I suspect this case 
> may make sense (and likely already works):
>
>   // Should test redeclaration behavior.
>   struct [[clang::standalone_debug]] redecl;
>   struct redecl {};
>
> but I'm not certain if this case makes sense:
>
>   struct [[clang::standalone_debug]] S; // Does this make sense on forward 
> declare that's never defined?

The purpose of the redecl being to test if the attribute still works when 
there's a redeclaration? I don't know if testing just the forward declare makes 
sense - I think the attribute wouldn't do anything in that case?

Oh, also, what's the difference between writing `__attribute__((attrname))` and 
`[[clang::attrname]]`?

In D97411#2591047 , @ldionne wrote:

> In D97411#2588181 , @akhuang wrote:
>
>> @ldionne Do you think it'd be reasonable to add this debug info attribute to 
>> some types in libc++? (For types that have constructors but don't call them; 
>> some previous discussion in https://reviews.llvm.org/D90719).
>
> Like I said in D90719 , I think it would be 
> best to fix the issue at its root and call those constructors (we must have 
> UB if we use these types but never call any constructors, right?).

True, I am still planning to look into the libc++ fix, but not sure how large / 
difficult that change would be. In the meantime we could do this? (And I think 
it would still be nice to have the attribute, regardless of the libc++ thing).


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97411/new/

https://reviews.llvm.org/D97411

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D97411: [DebugInfo] Add an attribute to force type info to be emitted for types that are required to be complete.

2021-02-26 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added a comment.

In D97411#2591030 , @aaron.ballman 
wrote:

> Thanks! I am still curious about the forward declare/redeclaration behavior 
> and whether that is a situation that makes sense or not. I suspect this case 
> may make sense (and likely already works):
>
>   // Should test redeclaration behavior.
>   struct [[clang::standalone_debug]] redecl;
>   struct redecl {};
>
> but I'm not certain if this case makes sense:
>
>   struct [[clang::standalone_debug]] S; // Does this make sense on forward 
> declare that's never defined?

It's not meaningful on a pure declaration - and I don't think there's much 
value in providing support for applying it to a declaration iff that 
declaration is followed by a definition.

(any prior art for other attributes we should try to be consistent with for an 
attribute that only has an effect on how a definition is handled?)

In D97411#2591047 , @ldionne wrote:

> In D97411#2588181 , @akhuang wrote:
>
>> @ldionne Do you think it'd be reasonable to add this debug info attribute to 
>> some types in libc++? (For types that have constructors but don't call them; 
>> some previous discussion in https://reviews.llvm.org/D90719).
>
> Like I said in D90719 , I think it would be 
> best to fix the issue at its root and call those constructors (we must have 
> UB if we use these types but never call any constructors, right?).

I'm generally in favor of that direction, but it doesn't look like I or 
@akhuang have the context to fix libc++ - if you or other libc++ maintainers 
might be able to help it'd be great.

Yes, I believe there is UB - if I recall correctly from some codepaths "create" 
instances of these objects without calling their ctor & use a custom deleter in 
a unique_ptr or similar to ensure the dtor doesn't run, while other uses call 
the ctor and let the dtor run as normal. Given the destruction semantics aren't 
built into the type, but imposed by the unique_ptr (or similar) outside, it's 
tricky to change the type. Perhaps changing the type to have a data buffer to 
construct into, using a factory function for the current "does real 
construction" case and then the custom deleter inverts - defaulting to doing 
nothing, but when activated deletes the object in the data buffer.

Though perhaps the issue is that the default codepath (that currently deals 
with real constructed/destructed objects) doesn't have space for customizing 
the deleter...

It's weird/complicated, would really like help fixing it, if this attribute 
sort of path isn't an option.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97411/new/

https://reviews.llvm.org/D97411

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D82547: [Debugify] Expose original debug info preservation check as CC1 option

2021-02-26 Thread Djordje Todorovic via Phabricator via cfe-commits
djtodoro added a comment.

Ping :)


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D82547/new/

https://reviews.llvm.org/D82547

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D84924: [clang-tidy] Added command line option `fix-notes`

2021-02-26 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 326779.
njames93 marked 6 inline comments as done.
njames93 added a comment.

Rebased and address comments


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D84924/new/

https://reviews.llvm.org/D84924

Files:
  clang-tools-extra/clang-tidy/ClangTidy.cpp
  clang-tools-extra/clang-tidy/ClangTidy.h
  clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
  clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h
  clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/index.rst
  clang-tools-extra/test/clang-tidy/checkers/misc-definitions-in-headers.hpp
  clang-tools-extra/test/clang-tidy/checkers/misc-unused-using-decls-cxx17.cpp
  clang-tools-extra/test/clang-tidy/checkers/misc-unused-using-decls.cpp
  
clang-tools-extra/test/clang-tidy/checkers/readability-inconsistent-declaration-parameter-name.cpp
  clang-tools-extra/test/clang-tidy/infrastructure/alternative-fixes.cpp
  clang-tools-extra/test/clang-tidy/infrastructure/clean-up-code.cpp

Index: clang-tools-extra/test/clang-tidy/infrastructure/clean-up-code.cpp
===
--- clang-tools-extra/test/clang-tidy/infrastructure/clean-up-code.cpp
+++ clang-tools-extra/test/clang-tidy/infrastructure/clean-up-code.cpp
@@ -1,6 +1,6 @@
-// RUN: %check_clang_tidy %s misc-unused-using-decls %t
-// RUN: %check_clang_tidy %s misc-unused-using-decls %t -- -format-style=none --
-// RUN: %check_clang_tidy %s misc-unused-using-decls %t -- -format-style=llvm --
+// RUN: %check_clang_tidy %s misc-unused-using-decls %t -- --fix-notes
+// RUN: %check_clang_tidy %s misc-unused-using-decls %t -- --fix-notes -format-style=none --
+// RUN: %check_clang_tidy %s misc-unused-using-decls %t -- --fix-notes -format-style=llvm --
 namespace a { class A {}; }
 namespace b {
 using a::A;
Index: clang-tools-extra/test/clang-tidy/infrastructure/alternative-fixes.cpp
===
--- clang-tools-extra/test/clang-tidy/infrastructure/alternative-fixes.cpp
+++ clang-tools-extra/test/clang-tidy/infrastructure/alternative-fixes.cpp
@@ -1,9 +1,10 @@
-// RUN: %check_clang_tidy %s "llvm-namespace-comment,clang-diagnostic-*" %t
+// RUN: %check_clang_tidy %s "llvm-namespace-comment,clang-diagnostic-*" %t -- --fix-notes
 void foo(int a) {
   if (a = 1) {
-  // CHECK-NOTES: [[@LINE-1]]:9: warning: using the result of an assignment as a condition without parentheses [clang-diagnostic-parentheses]
-  // CHECK-NOTES: [[@LINE-2]]:9: note: place parentheses around the assignment to silence this warning
-  // CHECK-NOTES: [[@LINE-3]]:9: note: use '==' to turn this assignment into an equality comparison
-  // CHECK-FIXES: if ((a = 1)) {
+// CHECK-NOTES: [[@LINE-1]]:9: warning: using the result of an assignment as a condition without parentheses [clang-diagnostic-parentheses]
+// CHECK-NOTES: [[@LINE-2]]:9: note: place parentheses around the assignment to silence this warning
+// CHECK-NOTES: [[@LINE-3]]:9: note: use '==' to turn this assignment into an equality comparison
+// As we have 2 conflicting fixes in notes, don't apply any fix.
+// CHECK-FIXES: if (a = 1) {
   }
 }
Index: clang-tools-extra/test/clang-tidy/checkers/readability-inconsistent-declaration-parameter-name.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability-inconsistent-declaration-parameter-name.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability-inconsistent-declaration-parameter-name.cpp
@@ -1,4 +1,4 @@
-// RUN: %check_clang_tidy %s readability-inconsistent-declaration-parameter-name %t -- -- -fno-delayed-template-parsing
+// RUN: %check_clang_tidy %s readability-inconsistent-declaration-parameter-name %t -- --fix-notes -- -fno-delayed-template-parsing
 
 void consistentFunction(int a, int b, int c);
 void consistentFunction(int a, int b, int c);
Index: clang-tools-extra/test/clang-tidy/checkers/misc-unused-using-decls.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/misc-unused-using-decls.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/misc-unused-using-decls.cpp
@@ -1,5 +1,4 @@
-// RUN: %check_clang_tidy %s misc-unused-using-decls %t -- -- -fno-delayed-template-parsing -isystem %S/Inputs/
-
+// RUN: %check_clang_tidy %s misc-unused-using-decls %t -- --fix-notes -- -fno-delayed-template-parsing -isystem %S/Inputs/
 
 // - Definitions -
 template  class vector {};
Index: clang-tools-extra/test/clang-tidy/checkers/misc-unused-using-decls-cxx17.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/misc-unused-using-decls-cxx17.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/misc-unused-using-decls-cxx17.cpp
@@ 

[PATCH] D97411: [DebugInfo] Add an attribute to force type info to be emitted for types that are required to be complete.

2021-02-26 Thread Louis Dionne via Phabricator via cfe-commits
ldionne added a comment.

In D97411#2588181 , @akhuang wrote:

> @ldionne Do you think it'd be reasonable to add this debug info attribute to 
> some types in libc++? (For types that have constructors but don't call them; 
> some previous discussion in https://reviews.llvm.org/D90719).

Like I said in D90719 , I think it would be 
best to fix the issue at its root and call those constructors (we must have UB 
if we use these types but never call any constructors, right?).


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97411/new/

https://reviews.llvm.org/D97411

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D97574: [AIX][clang][driver] Restrict /usr/lib to internal library search paths

2021-02-26 Thread David Tenty via Phabricator via cfe-commits
daltenty created this revision.
daltenty added reviewers: hubert.reinterpretcast, stevewan, jasonliu.
daltenty requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Adding it to the general filepaths results in it being added to the
linker arguments. The AIX linker always looks in this path anyway
and adds it as a default library path component. Adding this duplicate
explicitly results in duplicate entries in path in the loader section
of executables and messes up tools like CMake that parse the default
library flags.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D97574

Files:
  clang/lib/Driver/ToolChains/AIX.cpp
  clang/test/Driver/aix-ld.c

Index: clang/test/Driver/aix-ld.c
===
--- clang/test/Driver/aix-ld.c
+++ clang/test/Driver/aix-ld.c
@@ -17,7 +17,6 @@
 // CHECK-LD32: "-bpT:0x1000" "-bpD:0x2000"
 // CHECK-LD32: "[[SYSROOT]]/usr/lib{{/|}}crt0.o"
 // CHECK-LD32: "[[SYSROOT]]/usr/lib{{/|}}crti.o"
-// CHECK-LD32: "-L[[SYSROOT]]/usr/lib"
 // CHECK-LD32-NOT: "-lc++"
 // CHECK-LD32: "[[RESOURCE_DIR]]{{/|}}lib{{/|}}aix{{/|}}libclang_rt.builtins-powerpc.a"
 // CHECK-LD32-NOT: "-lm"
@@ -39,7 +38,6 @@
 // CHECK-LD64: "-bpT:0x1" "-bpD:0x11000"
 // CHECK-LD64: "[[SYSROOT]]/usr/lib{{/|}}crt0_64.o"
 // CHECK-LD64: "[[SYSROOT]]/usr/lib{{/|}}crti_64.o"
-// CHECK-LD64: "-L[[SYSROOT]]/usr/lib"
 // CHECK-LD64-NOT: "-lc++"
 // CHECK-LD64: "[[RESOURCE_DIR]]{{/|}}lib{{/|}}aix{{/|}}libclang_rt.builtins-powerpc64.a"
 // CHECK-LD64-NOT: "-lm"
@@ -62,7 +60,6 @@
 // CHECK-LD32-PTHREAD: "-bpT:0x1000" "-bpD:0x2000"
 // CHECK-LD32-PTHREAD: "[[SYSROOT]]/usr/lib{{/|}}crt0.o"
 // CHECK-LD32-PTHREAD: "[[SYSROOT]]/usr/lib{{/|}}crti.o"
-// CHECK-LD32-PTHREAD: "-L[[SYSROOT]]/usr/lib"
 // CHECK-LD32-PTHREAD-NOT: "-lc++"
 // CHECK-LD32-PTHREAD: "[[RESOURCE_DIR]]{{/|}}lib{{/|}}aix{{/|}}libclang_rt.builtins-powerpc.a"
 // CHECK-LD32-PTHREAD: "-lpthreads"
@@ -86,7 +83,6 @@
 // CHECK-LD64-PTHREAD: "-bpT:0x1" "-bpD:0x11000"
 // CHECK-LD64-PTHREAD: "[[SYSROOT]]/usr/lib{{/|}}crt0_64.o"
 // CHECK-LD64-PTHREAD: "[[SYSROOT]]/usr/lib{{/|}}crti_64.o"
-// CHECK-LD64-PTHREAD: "-L[[SYSROOT]]/usr/lib"
 // CHECK-LD64-PTHREAD-NOT: "-lc++"
 // CHECK-LD64-PTHREAD: "[[RESOURCE_DIR]]{{/|}}lib{{/|}}aix{{/|}}libclang_rt.builtins-powerpc64.a"
 // CHECK-LD64-PTHREAD: "-lpthreads"
@@ -110,7 +106,6 @@
 // CHECK-LD32-PROF: "-bpT:0x1000" "-bpD:0x2000"
 // CHECK-LD32-PROF: "[[SYSROOT]]/usr/lib{{/|}}mcrt0.o"
 // CHECK-LD32-PROF: "[[SYSROOT]]/usr/lib{{/|}}crti.o"
-// CHECK-LD32-PROF: "-L[[SYSROOT]]/usr/lib"
 // CHECK-LD32-PROF-NOT: "-lc++"
 // CHECK-LD32-PROF: "[[RESOURCE_DIR]]{{/|}}lib{{/|}}aix{{/|}}libclang_rt.builtins-powerpc.a"
 // CHECK-LD32-PROF-NOT: "-lm"
@@ -133,7 +128,6 @@
 // CHECK-LD64-GPROF: "-bpT:0x1" "-bpD:0x11000"
 // CHECK-LD64-GPROF: "[[SYSROOT]]/usr/lib{{/|}}gcrt0_64.o"
 // CHECK-LD64-GPROF: "[[SYSROOT]]/usr/lib{{/|}}crti_64.o"
-// CHECK-LD64-GPROF: "-L[[SYSROOT]]/usr/lib"
 // CHECK-LD64-GPROF-NOT: "-lc++"
 // CHECK-LD64-GPROF: "[[RESOURCE_DIR]]{{/|}}lib{{/|}}aix{{/|}}libclang_rt.builtins-powerpc64.a"
 // CHECK-LD64-GPROF-NOT: "-lm"
@@ -156,7 +150,6 @@
 // CHECK-LD32-STATIC: "-bpT:0x1000" "-bpD:0x2000"
 // CHECK-LD32-STATIC: "[[SYSROOT]]/usr/lib{{/|}}crt0.o"
 // CHECK-LD32-STATIC: "[[SYSROOT]]/usr/lib{{/|}}crti.o"
-// CHECK-LD32-STATIC: "-L[[SYSROOT]]/usr/lib"
 // CHECK-LD32-STATIC-NOT: "-lc++"
 // CHECK-LD32-STATIC: "[[RESOURCE_DIR]]{{/|}}lib{{/|}}aix{{/|}}libclang_rt.builtins-powerpc.a"
 // CHECK-LD32-STATIC-NOT: "-lm"
@@ -180,7 +173,6 @@
 // CHECK-LD32-LIBP: "[[SYSROOT]]/usr/lib{{/|}}crt0.o"
 // CHECK-LD32-LIBP: "[[SYSROOT]]/usr/lib{{/|}}crti.o"
 // CHECK-LD32-LIBP: "-L[[SYSROOT]]/powerpc-ibm-aix7.1.0.0"
-// CHECK-LD32-LIBP: "-L[[SYSROOT]]/usr/lib"
 // CHECK-LD32-LIBP-NOT: "-lc++"
 // CHECK-LD32-LIBP: "[[RESOURCE_DIR]]{{/|}}lib{{/|}}aix{{/|}}libclang_rt.builtins-powerpc.a"
 // CHECK-LD32-LIBP-NOT: "-lm"
@@ -204,7 +196,6 @@
 // CHECK-LD32-NO-STD-LIB: "-bpT:0x1000" "-bpD:0x2000"
 // CHECK-LD32-NO-STD-LIB-NOT: "[[SYSROOT]]/usr/lib{{/|}}crt0.o"
 // CHECK-LD32-NO-STD-LIB-NOT: "[[SYSROOT]]/usr/lib{{/|}}crti.o"
-// CHECK-LD32-NO-STD-LIB: "-L[[SYSROOT]]/usr/lib"
 // CHECK-LD32-NO-STD-LIB-NOT: "-lc++"
 // CHECK-LD32-NO-STD-LIB-NOT: "[[RESOURCE_DIR]]{{/|}}lib{{/|}}aix{{/|}}libclang_rt.builtins-powerpc.a"
 // CHECK-LD32-NO-STD-LIB-NOT: "-lpthreads"
@@ -229,7 +220,6 @@
 // CHECK-LD64-NO-DEFAULT-LIBS: "-bpT:0x1" "-bpD:0x11000"
 // CHECK-LD64-NO-DEFAULT-LIBS: 

[PATCH] D96744: clang-format IncludeBlocks: Regroup determination of "main" for framework-style includes fix

2021-02-26 Thread Conrad Poelman via Phabricator via cfe-commits
poelmanc added a comment.

In D96744#2564828 , @MyDeveloperDay 
wrote:

> Does this need to be an option?

It's easy to add an option, but there are already two //main include//-related 
options, so before adding a third I wanted to give this some thought. As 
someone new to `IncludeCategories`, I was genuinely impressed at how easy it 
was to use and how it gave me such complete control over the grouping via 
regular expressions. Yet in comparison the determination of //main// headers 
was less clear and more hard-coded; I had to examine the source code to figure 
out that the comparison is case-insensitive, it doesn't consider `<>` includes, 
only file stems are considered (e.g. the `foo/bar` in `foo/bar/baz.h` is 
ignored), and the behaviors of `IncludeIsMainSourceRegex` and 
`IncludeIsMainRegex` were a bit murky.

That's all fixable with a patch and minor documentation tweaks, but I wanted to 
consider some alternatives. Users of the `IncludeCategories` feature are 
comfortable with regular expressions, so imagine eliminating special handling 
of //main headers// entirely, and instead enabling users to write their own 
`IncludeCategories` rules for putting main headers first? We'd need to give 
them some bits of the source file path to use in their `Regex`, say called 
`${SourceStem}` and `${SourcePath}`.

Users unconcerned with formatting `foo_test.cc` or `foo_proto.cc` files could 
get the current functionality by including a simple rule like:

  - Regex:   '"(.*\/)?${SourceStem}(\..*)?"'
Priority:0
CaseSensitive:   false

I want case sensitivity, matching at least one component of the path, and angle 
brackets, so I'd use something like:

  - Regex:   '[<"]${SourcePath:1}${SourceStem}\..*[>"]'
Priority:0
CaseSensitive:   true

Then adding a generally-useful `ApplyToSourcesRegex` feature to apply any 
category regex only to certain source files, and an ability to trim a regular 
expression from the end of `${SourceStem}`, gives users full control, including 
mimicking current `isMainHeader()` behavior with rules like:

  - Regex:   
'"(.*\/)?${SourceStem-}(\..*)?"'
Priority:0
CaseSensitive:   false
ApplyToSourcesRegex: 
`((.*\.(c|cc|cpp|c\+\+|cxx|m|mm))|)`

For backwards-compatibility we'd automatically add the above rule if no special 
`${Source` tokens appear in any rules, and we can deprecate 
`IncludeIsMainRegex` and `IncludeIsMainSourceRegex` at any point. The special 
tokens for use in `Regex` are defined as:

- `${SourcePath:}` is a regular expression matching `n` or more trailing 
components of the source directory file path, using forward slashes and 
including any trailing slash (`0 <= n < 10`)
- `${SourceStem}` is a string starting after the last `/` in the source file 
path and includes up to but excluding the first dot
- `${SourceStem-}` is `${SourceStem}` with any trailing characters matching 
regular expression `re` removed

I have this coded up and it passes the ToolingTests, but wanted to run the idea 
by others. Thoughts? Should I update this patch with these changes? Start a 
separate issue? Stick with a new option `IncludeIsMainAllowBraces`?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D96744/new/

https://reviews.llvm.org/D96744

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D97411: [DebugInfo] Add an attribute to force type info to be emitted for types that are required to be complete.

2021-02-26 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

Thanks! I am still curious about the forward declare/redeclaration behavior and 
whether that is a situation that makes sense or not. I suspect this case may 
make sense (and likely already works):

  // Should test redeclaration behavior.
  struct [[clang::standalone_debug]] redecl;
  struct redecl {};

but I'm not certain if this case makes sense:

  struct [[clang::standalone_debug]] S; // Does this make sense on forward 
declare that's never defined?




Comment at: clang/test/Sema/attr-standalonedebug.cpp:1-4
+// RUN: %clang_cc1 %s -verify -fsyntax-only -DCPP
+// RUN: %clang_cc1 %s -verify -fsyntax-only -x c
+
+#ifdef CPP




Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97411/new/

https://reviews.llvm.org/D97411

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D97573: [OpenMP] Handle non-function context before checking for diagnostic emission

2021-02-26 Thread PremAnand Rao via Phabricator via cfe-commits
pmrao created this revision.
pmrao added reviewers: ABataev, bader, erichkeane, jdoerfert.
Herald added subscribers: guansong, yaxunl.
pmrao requested review of this revision.
Herald added a subscriber: sstefan1.
Herald added a project: clang.

Ensure that we are in a function declaration context before checking
the diagnostic emission status, to avoid dereferencing a NULL function
declaration.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D97573

Files:
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaOpenMP.cpp
  clang/test/OpenMP/simd_null_pointer_access.cpp


Index: clang/test/OpenMP/simd_null_pointer_access.cpp
===
--- /dev/null
+++ clang/test/OpenMP/simd_null_pointer_access.cpp
@@ -0,0 +1,8 @@
+// RUN: %clang_cc1 -fopenmp-simd -fsycl -fsycl-is-device -triple spir64 
-verify -fsyntax-only %s
+
+// Test that in the presence of SYCL options, that null function
+// declarations are accounted for when checking to emit diagnostics.
+
+// expected-no-diagnostics
+
+__thread void *x;
Index: clang/lib/Sema/SemaOpenMP.cpp
===
--- clang/lib/Sema/SemaOpenMP.cpp
+++ clang/lib/Sema/SemaOpenMP.cpp
@@ -1939,20 +1939,23 @@
FunctionDecl *FD) {
   assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
  "Expected OpenMP host compilation.");
-  FunctionEmissionStatus FES = getEmissionStatus(FD);
+
   SemaDiagnosticBuilder::Kind Kind = SemaDiagnosticBuilder::K_Nop;
-  switch (FES) {
-  case FunctionEmissionStatus::Emitted:
-Kind = SemaDiagnosticBuilder::K_Immediate;
-break;
-  case FunctionEmissionStatus::Unknown:
-Kind = SemaDiagnosticBuilder::K_Deferred;
-break;
-  case FunctionEmissionStatus::TemplateDiscarded:
-  case FunctionEmissionStatus::OMPDiscarded:
-  case FunctionEmissionStatus::CUDADiscarded:
-Kind = SemaDiagnosticBuilder::K_Nop;
-break;
+  if (FD) {
+FunctionEmissionStatus FES = getEmissionStatus(FD);
+switch (FES) {
+case FunctionEmissionStatus::Emitted:
+  Kind = SemaDiagnosticBuilder::K_Immediate;
+  break;
+case FunctionEmissionStatus::Unknown:
+  Kind = SemaDiagnosticBuilder::K_Deferred;
+  break;
+case FunctionEmissionStatus::TemplateDiscarded:
+case FunctionEmissionStatus::OMPDiscarded:
+case FunctionEmissionStatus::CUDADiscarded:
+  Kind = SemaDiagnosticBuilder::K_Nop;
+  break;
+}
   }
 
   return SemaDiagnosticBuilder(Kind, Loc, DiagID, FD, *this);
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -18339,6 +18339,8 @@
 
 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
  bool Final) {
+  assert(FD && "Expected non-null FunctionDecl");
+
   // SYCL functions can be template, so we check if they have appropriate
   // attribute prior to checking if it is a template.
   if (LangOpts.SYCLIsDevice && FD->hasAttr())


Index: clang/test/OpenMP/simd_null_pointer_access.cpp
===
--- /dev/null
+++ clang/test/OpenMP/simd_null_pointer_access.cpp
@@ -0,0 +1,8 @@
+// RUN: %clang_cc1 -fopenmp-simd -fsycl -fsycl-is-device -triple spir64 -verify -fsyntax-only %s
+
+// Test that in the presence of SYCL options, that null function
+// declarations are accounted for when checking to emit diagnostics.
+
+// expected-no-diagnostics
+
+__thread void *x;
Index: clang/lib/Sema/SemaOpenMP.cpp
===
--- clang/lib/Sema/SemaOpenMP.cpp
+++ clang/lib/Sema/SemaOpenMP.cpp
@@ -1939,20 +1939,23 @@
FunctionDecl *FD) {
   assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
  "Expected OpenMP host compilation.");
-  FunctionEmissionStatus FES = getEmissionStatus(FD);
+
   SemaDiagnosticBuilder::Kind Kind = SemaDiagnosticBuilder::K_Nop;
-  switch (FES) {
-  case FunctionEmissionStatus::Emitted:
-Kind = SemaDiagnosticBuilder::K_Immediate;
-break;
-  case FunctionEmissionStatus::Unknown:
-Kind = SemaDiagnosticBuilder::K_Deferred;
-break;
-  case FunctionEmissionStatus::TemplateDiscarded:
-  case FunctionEmissionStatus::OMPDiscarded:
-  case FunctionEmissionStatus::CUDADiscarded:
-Kind = SemaDiagnosticBuilder::K_Nop;
-break;
+  if (FD) {
+FunctionEmissionStatus FES = getEmissionStatus(FD);
+switch (FES) {
+case FunctionEmissionStatus::Emitted:
+  Kind = SemaDiagnosticBuilder::K_Immediate;
+  break;
+case FunctionEmissionStatus::Unknown:
+  Kind = SemaDiagnosticBuilder::K_Deferred;
+  break;
+case FunctionEmissionStatus::TemplateDiscarded:
+case FunctionEmissionStatus::OMPDiscarded:
+case 

[PATCH] D97534: SEH: capture 'this'

2021-02-26 Thread Reid Kleckner via Phabricator via cfe-commits
rnk accepted this revision.
rnk added a comment.
This revision is now accepted and ready to land.

lgtm


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97534/new/

https://reviews.llvm.org/D97534

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D97513: Add ConfigVersion.cmake files

2021-02-26 Thread Alex Reinking via Phabricator via cfe-commits
alexreinking added a comment.

So with this patch, I tried to imitate the existing code as much as possible. 
However, I think it would be quite a bit better to use the 
`write_basic_package_version_file` command from `CMakePackageConfigHelpers`. It 
gained support for major + minor version compatibility matching in CMake 3.11. 
Since LLVM is on 3.13 now, I don't see a reason not to use this. Instead of the 
existing `configure_file` and `*ConfigVersion.cmake.in` combo, we would delete 
the template (`.in`) and just write:

  include(CMakePackageConfigHelpers)
  write_basic_package_version_file(
  ${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/PollyConfigVersion.cmake
  VERSION ${POLLY_VERSION}
  COMPATIBILITY SameMinorVersion
  )

If the subproject had proper calls to `project()`, like `project(Polly VERSION 
${POLLY_VERSION})`, then `write_basic_package_version_file` would default its 
`VERSION` argument to `${PROJECT_VERSION}`.

The template `ConfigVersion.cmake.in` files are also missing an architecture 
check, so it's possible that a 64-bit build of LLVM could get picked up by a 
project calling `find_package` while cross compiling to 32-bit. The ones 
generated by `write_basic_package_version_file` have this check.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97513/new/

https://reviews.llvm.org/D97513

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D97447: Add GNU attribute 'retain'

2021-02-26 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay updated this revision to Diff 326766.
MaskRay added a comment.

Improve doc as rnk suggested.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97447/new/

https://reviews.llvm.org/D97447

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/lib/CodeGen/CGDecl.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/test/CodeGen/attr-retain.c
  clang/test/CodeGenCXX/attr-retain.cpp
  clang/test/Sema/attr-retain.c

Index: clang/test/Sema/attr-retain.c
===
--- /dev/null
+++ clang/test/Sema/attr-retain.c
@@ -0,0 +1,29 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s -Wunused-function
+
+/// We allow 'retain' on non-ELF targets because 'retain' is often used together
+/// with 'used'. 'used' has GC root semantics on macOS and Windows. We want
+/// users to just write retain,used and don't need to dispatch on binary formats.
+
+extern char test1[] __attribute__((retain));   // expected-warning {{'retain' attribute ignored on a non-definition declaration}}
+extern const char test2[] __attribute__((retain)); // expected-warning {{'retain' attribute ignored on a non-definition declaration}}
+const char test3[] __attribute__((retain)) = "";
+
+struct __attribute__((retain)) s { // expected-warning {{'retain' attribute only applies to variables with non-local storage, functions, and Objective-C methods}}
+};
+
+void foo() {
+  static int a __attribute__((retain));
+  int b __attribute__((retain)); // expected-warning {{'retain' attribute only applies to variables with non-local storage, functions, and Objective-C methods}}
+  (void)a;
+  (void)b;
+}
+
+__attribute__((retain,used)) static void f0() {}
+__attribute__((retain)) static void f1() {} // expected-warning {{unused function 'f1'}}
+__attribute__((retain)) void f2() {}
+
+/// Test attribute merging.
+int tentative;
+int tentative __attribute__((retain));
+extern int tentative;
+int tentative = 0;
Index: clang/test/CodeGenCXX/attr-retain.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/attr-retain.cpp
@@ -0,0 +1,45 @@
+// RUN: %clang_cc1 -emit-llvm -triple %itanium_abi_triple -Werror %s -o - | FileCheck %s
+
+// CHECK:  @llvm.used = appending global [7 x i8*]
+// CHECK-SAME:   @_ZN2X0C2Ev
+// CHECK-SAME:   @_ZN2X0C1Ev
+// CHECK-SAME:   @_ZN2X0D2Ev
+// CHECK-SAME:   @_ZN2X0D1Ev
+// CHECK-SAME:   @_ZN2X16Nested2f1Ev
+// CHECK-SAME:   @_ZN10merge_declL4funcEv
+// CHECK-SAME:   @_ZN18instantiate_member1SIiE1fEv
+
+struct X0 {
+  // CHECK: define linkonce_odr{{.*}} @_ZN2X0C1Ev({{.*}}
+  __attribute__((used, retain)) X0() {}
+  // CHECK: define linkonce_odr{{.*}} @_ZN2X0D1Ev({{.*}}
+  __attribute__((used, retain)) ~X0() {}
+};
+
+struct X1 {
+  struct Nested {
+// CHECK-NOT: 2f0Ev
+// CHECK: define linkonce_odr{{.*}} @_ZN2X16Nested2f1Ev({{.*}}
+void __attribute__((retain)) f0() {}
+void __attribute__((used, retain)) f1() {}
+  };
+};
+
+// CHECK: define internal void @_ZN10merge_declL4funcEv(){{.*}}
+namespace merge_decl {
+static void func();
+void bar() { void func() __attribute__((used, retain)); }
+static void func() {}
+} // namespace merge_decl
+
+namespace instantiate_member {
+template 
+struct S {
+  void __attribute__((used, retain)) f() {}
+};
+
+void test() {
+  // CHECK: define linkonce_odr{{.*}} void @_ZN18instantiate_member1SIiE1fEv({{.*}}
+  S a;
+}
+} // namespace instantiate_member
Index: clang/test/CodeGen/attr-retain.c
===
--- /dev/null
+++ clang/test/CodeGen/attr-retain.c
@@ -0,0 +1,29 @@
+// RUN: %clang_cc1 -emit-llvm %s -o - | FileCheck %s
+
+/// Set !retain regardless of the target. The backend will lower !retain to
+/// SHF_GNU_RETAIN on ELF and ignore the metadata for other binary formats.
+// CHECK:  @c0 ={{.*}} constant i32 {{.*}}
+// CHECK:  @foo.l0 = internal global i32 {{.*}}
+// CHECK:  @g0 ={{.*}} global i32 {{.*}}
+// CHECK-NEXT: @g1 ={{.*}} global i32 {{.*}}
+// CHECK-NEXT: @g3 = internal global i32 {{.*}}
+// CHECK-NEXT: @g4 = internal global i32 0, section ".data.g"{{.*}}
+
+// CHECK:  @llvm.used = appending global [8 x i8*] [i8* bitcast (i32* @c0 to i8*), i8* bitcast (i32* @foo.l0 to i8*), i8* bitcast (void ()* @f0 to i8*), i8* bitcast (void ()* @f2 to i8*), i8* bitcast (i32* @g0 to i8*), i8* bitcast (i32* @g1 to i8*), i8* bitcast (i32* @g3 to i8*), i8* bitcast (i32* @g4 to i8*)], section "llvm.metadata"
+// CHECK:  @llvm.compiler.used = appending global [3 x i8*] [i8* bitcast (void ()* @f2 to i8*), i8* bitcast (i32* @g3 to i8*), i8* bitcast (i32* @g4 to i8*)], section "llvm.metadata"
+
+const int c0 __attribute__((retain)) = 42;
+
+void foo() {
+  static int l0 __attribute__((retain)) = 2;
+}
+
+__attribute__((retain)) int g0;
+int g1 __attribute__((retain));
+__attribute__((retain)) 

[PATCH] D95016: [Clang][RISCV] Add custom TableGen backend for riscv-vector intrinsics.

2021-02-26 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added inline comments.



Comment at: clang/include/clang/Basic/riscv_vector.td:66
+//  element type which is bool
+//   0: void type, ignores "t"
+//   z: size_t, ignores "t"

jrtc27 wrote:
> craig.topper wrote:
> > jrtc27 wrote:
> > > khchen wrote:
> > > > jrtc27 wrote:
> > > > > Then why aren't these just base types? We don't have to follow the 
> > > > > brain-dead nature of printf.
> > > > Basically builtin interface is instantiated by the "base type + LMUL" 
> > > > with type transformers. But in some intrinsic function we need a 
> > > > specific type regardless "base type + LMUL"
> > > > ex. `vuint32m2_t vssrl_vx_u32m2_vl (vuint32m2_t op1, uint8_t op2, 
> > > > size_t vl);`
> > > Then fix the way you define these? This is just bad design IMO.
> > For each signature there is effectively a single key type that is a vector. 
> > The type transformer is a list of rules for how to derive all of the other 
> > operands from that one key type. Conceptually similar to 
> > LLVMScalarOrSameVectorWidth or LLVMHalfElementsVectorType in Intrinsics.td. 
> > Some types are fixed and don't vary by the key type. Like the size_t vl 
> > operand or a store intrinsic returning void.  There is no separate place to 
> > put a base type.
> Oh I see, I hadn't appreciated that TypeRange got split up and each character 
> was a whole separate intrinsic, I had misinterpreted it as it being a list of 
> the types of arguments, i.e. an N-character string for an (N-1)-argument 
> (plus return type) intrinsic that you could then use as a base and apply 
> transformations too (e.g. "if" for a float-to-int intrinsic, with "vv" etc 
> giving you a vectorised versions) and so was confused as to why the 
> void/size_t/ptrdiff_t/uint8_t/bool-ness couldn't just be pushed into the 
> TypeRange and the corresponding transforms left as "e". But, how _would_ you 
> define vector float-to-int (and back) conversions with this scheme then?
> 
> On a related note, I feel one way to make this less obfuscated is change 
> v/w/q/o to be v1/v2/v4/v8 (maybe with the 1 being optional, don't really 
> care), and is also more extensible in future rather than ending up with yet 
> more alphabet soup, though it does change the parsing from being a list of 
> characters to a list of strings.
I think these transforms are used for the float-to-int and int-to-float. 

//   I: given a vector type, compute the vector type with integer type
//  elements of the same width
//   F: given a vector type, compute the vector type with floating-point type
//  elements of the same width

The float and integer types for conversion are always the same size or one lmul 
up or one lmul down. So combining I and F with v or w should cover it.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D95016/new/

https://reviews.llvm.org/D95016

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D95984: [CodeGen] Fix codegen for __attribute__((swiftasynccall)).

2021-02-26 Thread Varun Gandhi via Phabricator via cfe-commits
varungandhi-apple updated this revision to Diff 326762.
varungandhi-apple added a comment.

Added checks for C++.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D95984/new/

https://reviews.llvm.org/D95984

Files:
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/CGStmt.cpp
  clang/test/CodeGen/64bit-swiftcall.c
  clang/test/CodeGen/arm-swiftcall.c
  clang/test/CodeGen/swift-async-call-conv.c
  clang/test/CodeGen/swift-call-conv.c

Index: clang/test/CodeGen/swift-call-conv.c
===
--- clang/test/CodeGen/swift-call-conv.c
+++ clang/test/CodeGen/swift-call-conv.c
@@ -6,3 +6,5 @@
 void __attribute__((__swiftcall__)) f(void) {}
 // CHECK-LABEL: define dso_local swiftcc void @f()
 
+void __attribute__((__swiftasynccall__)) f_async(void) {}
+// CHECK-LABEL: define dso_local swifttailcc void @f_async()
Index: clang/test/CodeGen/swift-async-call-conv.c
===
--- /dev/null
+++ clang/test/CodeGen/swift-async-call-conv.c
@@ -0,0 +1,138 @@
+// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -target-cpu core2 -emit-llvm -o - %s | FileCheck %s
+// RUN: %clang_cc1 -triple arm64-apple-ios9 -target-cpu cyclone -emit-llvm -o - %s | FileCheck %s
+// RUN: %clang_cc1 -triple armv7-apple-darwin9 -emit-llvm -o - %s | FileCheck %s
+// RUN: %clang_cc1 -triple armv7s-apple-ios9 -emit-llvm -o - %s | FileCheck %s
+// RUN: %clang_cc1 -triple armv7k-apple-ios9 -emit-llvm -o - %s | FileCheck %s
+
+// RUN: %clang_cc1 -x c++ -triple x86_64-apple-darwin10 -target-cpu core2 -emit-llvm -o - %s | FileCheck %s
+// RUN: %clang_cc1 -x c++ -triple arm64-apple-ios9 -target-cpu cyclone -emit-llvm -o - %s | FileCheck %s
+// RUN: %clang_cc1 -x c++ -triple armv7-apple-darwin9 -emit-llvm -o - %s | FileCheck %s
+// RUN: %clang_cc1 -x c++ -triple armv7s-apple-ios9 -emit-llvm -o - %s | FileCheck %s
+// RUN: %clang_cc1 -x c++ -triple armv7k-apple-ios9 -emit-llvm -o - %s | FileCheck %s
+
+// Test tail call behavior when a swiftasynccall function is called
+// from another swiftasynccall function.
+
+#define SWIFTCALL __attribute__((swiftcall))
+#define SWIFTASYNCCALL __attribute__((swiftasynccall))
+#define ASYNC_CONTEXT __attribute__((swift_async_context))
+
+// CHECK-LABEL: swifttailcc void {{.*}}async_leaf1{{.*}}(i8* swiftasync
+SWIFTASYNCCALL void async_leaf1(char * ASYNC_CONTEXT ctx) {
+  *ctx += 1;
+}
+
+// CHECK-LABEL: swifttailcc void {{.*}}async_leaf2{{.*}}(i8* swiftasync
+SWIFTASYNCCALL void async_leaf2(char * ASYNC_CONTEXT ctx) {
+  *ctx += 2;
+}
+
+#if __cplusplus
+  #define MYBOOL bool
+#else
+  #define MYBOOL _Bool
+#endif
+
+// CHECK-LABEL: swifttailcc void {{.*}}async_branch{{.*}}i8* swiftasync
+// CHECK: tail call swifttailcc void @{{.*}}async_leaf1
+// CHECK-NEXT: ret void
+// CHECK: tail call swifttailcc void @{{.*}}async_leaf2
+// CHECK-NEXT: ret void
+SWIFTASYNCCALL void async_branch(MYBOOL b, char * ASYNC_CONTEXT ctx) {
+  if (b) {
+return async_leaf1(ctx);
+  } else {
+return async_leaf2(ctx);
+  }
+}
+
+// CHECK-LABEL: swifttailcc void {{.*}}async_not_all_tail
+// CHECK-NOT:  tail call swifttailcc void @{{.*}}async_leaf1
+// CHECK:  call swifttailcc void @{{.*}}async_leaf1
+// CHECK-NOT:  ret void
+// CHECK:  tail call swifttailcc void @{{.*}}async_leaf2
+// CHECK-NEXT: ret void
+SWIFTASYNCCALL void async_not_all_tail(char * ASYNC_CONTEXT ctx) {
+  async_leaf1(ctx);
+  return async_leaf2(ctx);
+}
+
+// CHECK-LABEL: swifttailcc void {{.*}}async_loop
+// CHECK: tail call swifttailcc void @{{.*}}async_leaf1
+// CHECK-NEXT: ret void
+// CHECK: tail call swifttailcc void @{{.*}}async_leaf2
+// CHECK-NEXT: ret void
+// CHECK: tail call swifttailcc void @{{.*}}async_loop
+// CHECK-NEXT: ret void
+SWIFTASYNCCALL void async_loop(unsigned u, char * ASYNC_CONTEXT ctx) {
+  if (u == 0) {
+return async_leaf1(ctx);
+  } else if (u == 1) {
+return async_leaf2(ctx);
+  }
+  return async_loop(u - 2, ctx);
+}
+
+// Forward-declaration + mutual recursion is okay.
+
+SWIFTASYNCCALL void async_mutual_loop2(unsigned u, char * ASYNC_CONTEXT ctx);
+
+// CHECK-LABEL: swifttailcc void {{.*}}async_mutual_loop1
+// CHECK: tail call swifttailcc void @{{.*}}async_leaf1
+// CHECK-NEXT: ret void
+// CHECK: tail call swifttailcc void @{{.*}}async_leaf2
+// CHECK-NEXT: ret void
+// There is some bugginess around FileCheck's greediness/matching,
+// so skipping the check for async_mutual_loop2 here.
+SWIFTASYNCCALL void async_mutual_loop1(unsigned u, char * ASYNC_CONTEXT ctx) {
+  if (u == 0) {
+return async_leaf1(ctx);
+  } else if (u == 1) {
+return async_leaf2(ctx);
+  }
+  return async_mutual_loop2(u - 2, ctx);
+}
+
+// CHECK-LABEL: swifttailcc void {{.*}}async_mutual_loop2
+// CHECK: tail call swifttailcc void @{{.*}}async_leaf1
+// CHECK-NEXT: ret void
+// CHECK: tail call swifttailcc void @{{.*}}async_leaf2
+// CHECK-NEXT: ret void
+// CHECK: tail call 

[PATCH] D97447: Add GNU attribute 'retain'

2021-02-26 Thread Reid Kleckner via Phabricator via cfe-commits
rnk accepted this revision.
rnk added a comment.
This revision is now accepted and ready to land.

lgtm with a minor doc tweak

My reading of the discussion is that this is ready, but please wait for others 
if you are aware of any outstanding concerns.




Comment at: clang/include/clang/Basic/AttrDocs.td:98
+
+This attribute only has an effect on ELF targets; other targets prevent the
+removal of definitions by the linker when using the ``used`` attribute alone.

The attribute does have an effect on non-ELF targets: a retained global will be 
added to llvm.used, if it ends up being emitted. Maybe you can say that the 
attribute is only necessary on ELF targets, and that there is no harm in using 
`retain` in addition to `used` on non-ELF targets. Using the attributes 
together should result in consistent behavior across platforms.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97447/new/

https://reviews.llvm.org/D97447

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D95016: [Clang][RISCV] Add custom TableGen backend for riscv-vector intrinsics.

2021-02-26 Thread Jessica Clarke via Phabricator via cfe-commits
jrtc27 added inline comments.



Comment at: clang/include/clang/Basic/riscv_vector.td:66
+//  element type which is bool
+//   0: void type, ignores "t"
+//   z: size_t, ignores "t"

craig.topper wrote:
> jrtc27 wrote:
> > khchen wrote:
> > > jrtc27 wrote:
> > > > Then why aren't these just base types? We don't have to follow the 
> > > > brain-dead nature of printf.
> > > Basically builtin interface is instantiated by the "base type + LMUL" 
> > > with type transformers. But in some intrinsic function we need a specific 
> > > type regardless "base type + LMUL"
> > > ex. `vuint32m2_t vssrl_vx_u32m2_vl (vuint32m2_t op1, uint8_t op2, size_t 
> > > vl);`
> > Then fix the way you define these? This is just bad design IMO.
> For each signature there is effectively a single key type that is a vector. 
> The type transformer is a list of rules for how to derive all of the other 
> operands from that one key type. Conceptually similar to 
> LLVMScalarOrSameVectorWidth or LLVMHalfElementsVectorType in Intrinsics.td. 
> Some types are fixed and don't vary by the key type. Like the size_t vl 
> operand or a store intrinsic returning void.  There is no separate place to 
> put a base type.
Oh I see, I hadn't appreciated that TypeRange got split up and each character 
was a whole separate intrinsic, I had misinterpreted it as it being a list of 
the types of arguments, i.e. an N-character string for an (N-1)-argument (plus 
return type) intrinsic that you could then use as a base and apply 
transformations too (e.g. "if" for a float-to-int intrinsic, with "vv" etc 
giving you a vectorised versions) and so was confused as to why the 
void/size_t/ptrdiff_t/uint8_t/bool-ness couldn't just be pushed into the 
TypeRange and the corresponding transforms left as "e". But, how _would_ you 
define vector float-to-int (and back) conversions with this scheme then?

On a related note, I feel one way to make this less obfuscated is change 
v/w/q/o to be v1/v2/v4/v8 (maybe with the 1 being optional, don't really care), 
and is also more extensible in future rather than ending up with yet more 
alphabet soup, though it does change the parsing from being a list of 
characters to a list of strings.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D95016/new/

https://reviews.llvm.org/D95016

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D97119: [flang][driver] Add options for -std=2018

2021-02-26 Thread Arnamoy B via Phabricator via cfe-commits
arnamoy10 updated this revision to Diff 326760.
arnamoy10 added a comment.

1. Updated the test case to include a check when the option is not given and 
make sure works with f18 as well (with `Mstandard`)
2. Changed variable names as suggested.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97119/new/

https://reviews.llvm.org/D97119

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Flang.cpp
  flang/include/flang/Frontend/CompilerInvocation.h
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/test/Flang-Driver/driver-help-hidden.f90
  flang/test/Flang-Driver/driver-help.f90
  flang/test/Flang-Driver/std2018.f90

Index: flang/test/Flang-Driver/std2018.f90
===
--- /dev/null
+++ flang/test/Flang-Driver/std2018.f90
@@ -0,0 +1,42 @@
+! Ensure argument -std=f2018 works as expected.
+
+!--
+! FLANG DRIVER (flang-new)
+!--
+! RUN: %flang-new -fsyntax-only %s  2>&1 | FileCheck %s --allow-empty --check-prefix=WITHOUT
+! RUN: %flang-new -fsyntax-only -std=f2018 %s  2>&1 | FileCheck %s --check-prefix=GIVEN
+! RUN: %f18 -fsyntax-only %s  2>&1 | FileCheck %s --allow-empty --check-prefix=WITHOUT
+! RUN: %f18 -fsyntax-only -Mstandard %s  2>&1 | FileCheck %s --check-prefix=GIVEN
+! RUN: not %flang-new -fsyntax-only -std=90 %s  2>&1 | FileCheck %s --check-prefix=WRONG
+
+!-
+! FRONTEND FLANG DRIVER (flang-new -fc1)
+!-
+!  RUN: %flang-new -fc1 %s  2>&1 | FileCheck %s --allow-empty --check-prefix=WITHOUT
+!  RUN: %flang-new -fc1 -std=f2018 %s  2>&1 | FileCheck %s --check-prefix=GIVEN
+!  RUN: not %flang-new -fc1 -std=90 %s  2>&1 | FileCheck %s --check-prefix=WRONG
+
+!-
+! EXPECTED OUTPUT WITHOUT
+!-
+! WITHOUT-NOT: A DO loop should terminate with an END DO or CONTINUE
+
+!-
+! EXPECTED OUTPUT WITH
+!-
+! GIVEN: A DO loop should terminate with an END DO or CONTINUE
+
+!-
+! EXPECTED OUTPUT WITH WRONG
+!-
+! WRONG: Only -std=2018 is allowed currently.
+
+subroutine foo2()
+do 01 m=1,2
+  select case (m)
+  case default
+print*, "default", m
+  case (1)
+print*, "start"
+01end select
+end subroutine
Index: flang/test/Flang-Driver/driver-help.f90
===
--- flang/test/Flang-Driver/driver-help.f90
+++ flang/test/Flang-Driver/driver-help.f90
@@ -38,6 +38,7 @@
 ! HELP-NEXT: -IAdd directory to the end of the list of include search paths
 ! HELP-NEXT: -module-dir   Put MODULE files in 
 ! HELP-NEXT: -o   Write output to 
+! HELP-NEXT: -std=   Language standard to compile for
 ! HELP-NEXT: -U  Undefine macro 
 ! HELP-NEXT: --version  Print version information
 
@@ -64,6 +65,7 @@
 ! HELP-FC1-NEXT: -IAdd directory to the end of the list of include search paths
 ! HELP-FC1-NEXT: -module-dir   Put MODULE files in 
 ! HELP-FC1-NEXT: -o   Write output to 
+! HELP-FC1-NEXT: -std=   Language standard to compile for
 ! HELP-FC1-NEXT: -U  Undefine macro 
 ! HELP-FC1-NEXT: --version  Print version information
 
Index: flang/test/Flang-Driver/driver-help-hidden.f90
===
--- flang/test/Flang-Driver/driver-help-hidden.f90
+++ flang/test/Flang-Driver/driver-help-hidden.f90
@@ -38,6 +38,7 @@
 ! CHECK-NEXT: -IAdd directory to the end of the list of include search paths
 ! CHECK-NEXT: -module-dir   Put MODULE files in 
 ! CHECK-NEXT: -o  Write output to 
+! CHECK-NEXT: -std=   Language standard to compile for
 ! CHECK-NEXT: -test-io  Run the InputOuputTest action. Use for development and testing only.
 ! CHECK-NEXT: -U  Undefine macro 
 ! CHECK-NEXT: --version Print version information
Index: flang/lib/Frontend/CompilerInvocation.cpp
===
--- flang/lib/Frontend/CompilerInvocation.cpp
+++ flang/lib/Frontend/CompilerInvocation.cpp
@@ -286,6 +286,21 @@
 res.frontendOpts().features_.Enable(
 Fortran::common::LanguageFeature::OpenMP);
   }
+
+  //-std=f2018
+  if (args.hasArg(clang::driver::options::OPT_std_EQ)) {
+auto standard = args.getLastArgValue(clang::driver::options::OPT_std_EQ);
+// We only allow 2018 as the given standard
+if (standard.equals("f2018")) {
+  res.set_EnableConformanceChecks();
+}
+else {
+  const unsigned diagID =
+  diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
+  "Only -std=f2018 is allowed currently.");
+  

[PATCH] D95016: [Clang][RISCV] Add custom TableGen backend for riscv-vector intrinsics.

2021-02-26 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added inline comments.



Comment at: clang/utils/TableGen/RISCVVEmitter.cpp:259-260
+
+LMULType ::operator*=(unsigned RHS) {
+  this->Log2LMUL = this->Log2LMUL + RHS;
+  return *this;

jrtc27 wrote:
> That's not how multiplication works. This is exponentiation. Multiplication 
> would be `Log2LMul + log2(RHS)`. Please don't abuse operators like this.
This seems like it must be broken, but since we don't do widening or narrowing 
in this patch we didn't notice?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D95016/new/

https://reviews.llvm.org/D95016

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D95016: [Clang][RISCV] Add custom TableGen backend for riscv-vector intrinsics.

2021-02-26 Thread Jessica Clarke via Phabricator via cfe-commits
jrtc27 added inline comments.



Comment at: clang/utils/TableGen/RISCVVEmitter.cpp:567
+  // Compute type transformers
+  for (char I : Transformer.take_front(Transformer.size() - 1)) {
+switch (I) {

craig.topper wrote:
> jrtc27 wrote:
> > craig.topper wrote:
> > > Can we do Transformer = Transformer.drop_back() right before this loop. 
> > > That take_front code is harder to think about.
> > Or would it be better as a pop_back in the switch above?
> I don't think StringRef has a pop_back.
Right, and it's an immutable data structure anyway so you'd need to have to 
deal with two return values. Never mind then.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D95016/new/

https://reviews.llvm.org/D95016

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D95016: [Clang][RISCV] Add custom TableGen backend for riscv-vector intrinsics.

2021-02-26 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added inline comments.



Comment at: clang/utils/TableGen/RISCVVEmitter.cpp:567
+  // Compute type transformers
+  for (char I : Transformer.take_front(Transformer.size() - 1)) {
+switch (I) {

jrtc27 wrote:
> craig.topper wrote:
> > Can we do Transformer = Transformer.drop_back() right before this loop. 
> > That take_front code is harder to think about.
> Or would it be better as a pop_back in the switch above?
I don't think StringRef has a pop_back.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D95016/new/

https://reviews.llvm.org/D95016

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D95016: [Clang][RISCV] Add custom TableGen backend for riscv-vector intrinsics.

2021-02-26 Thread Craig Topper via Phabricator via cfe-commits
craig.topper requested changes to this revision.
craig.topper added a comment.
This revision now requires changes to proceed.

Dropping my approval pending @jrtc27 comments.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D95016/new/

https://reviews.llvm.org/D95016

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D95016: [Clang][RISCV] Add custom TableGen backend for riscv-vector intrinsics.

2021-02-26 Thread Jessica Clarke via Phabricator via cfe-commits
jrtc27 added inline comments.



Comment at: clang/utils/TableGen/RISCVVEmitter.cpp:116
+  D = 1 << 2,
+  ZFH = 1 << 3
+};

Zfh



Comment at: clang/utils/TableGen/RISCVVEmitter.cpp:241
+  case 8:
+ExpResult = Log2LMUL + 3;
+break;

Please be consistent and use Log2 rather than Exp



Comment at: clang/utils/TableGen/RISCVVEmitter.cpp:259-260
+
+LMULType ::operator*=(unsigned RHS) {
+  this->Log2LMUL = this->Log2LMUL + RHS;
+  return *this;

That's not how multiplication works. This is exponentiation. Multiplication 
would be `Log2LMul + log2(RHS)`. Please don't abuse operators like this.



Comment at: clang/utils/TableGen/RISCVVEmitter.cpp:325
+  std::string  = BuiltinStr;
+  if (IsVoid) {
+S = "v";

This really needs to be an enum not a bunch of mutually-exclusive booleans, 
which I though I suggested in the past?



Comment at: clang/utils/TableGen/RISCVVEmitter.cpp:450-451
+  S += "uint";
+// Vector bool is special case, the formulate is `vbool_t =
+// MVT::nxv<64/N>i1` ex. vbool16_t = MVT::
+if (IsBool && isVector())

Please try and avoid wrapping code across lines



Comment at: clang/utils/TableGen/RISCVVEmitter.cpp:624
+  }
+  // Init RISCV_Extensions
+  for (const auto  : OutInTypes) {

Blank line



Comment at: clang/utils/TableGen/RISCVVEmitter.cpp:685
+  OS << "};\n";
+  OS << "break;\n";
+}

This is missing indentation?



Comment at: clang/utils/TableGen/RISCVVEmitter.cpp:870
+PrevDef = Def.get();
+OS << "case RISCV::BI__builtin_rvv_" << Def->getName() << ":\n";
+  }

Needs indentation?



Comment at: clang/utils/TableGen/RISCVVEmitter.cpp:567
+  // Compute type transformers
+  for (char I : Transformer.take_front(Transformer.size() - 1)) {
+switch (I) {

craig.topper wrote:
> Can we do Transformer = Transformer.drop_back() right before this loop. That 
> take_front code is harder to think about.
Or would it be better as a pop_back in the switch above?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D95016/new/

https://reviews.llvm.org/D95016

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D95016: [Clang][RISCV] Add custom TableGen backend for riscv-vector intrinsics.

2021-02-26 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added inline comments.



Comment at: clang/include/clang/Basic/riscv_vector.td:66
+//  element type which is bool
+//   0: void type, ignores "t"
+//   z: size_t, ignores "t"

jrtc27 wrote:
> khchen wrote:
> > jrtc27 wrote:
> > > Then why aren't these just base types? We don't have to follow the 
> > > brain-dead nature of printf.
> > Basically builtin interface is instantiated by the "base type + LMUL" with 
> > type transformers. But in some intrinsic function we need a specific type 
> > regardless "base type + LMUL"
> > ex. `vuint32m2_t vssrl_vx_u32m2_vl (vuint32m2_t op1, uint8_t op2, size_t 
> > vl);`
> Then fix the way you define these? This is just bad design IMO.
For each signature there is effectively a single key type that is a vector. The 
type transformer is a list of rules for how to derive all of the other operands 
from that one key type. Conceptually similar to LLVMScalarOrSameVectorWidth or 
LLVMHalfElementsVectorType in Intrinsics.td. Some types are fixed and don't 
vary by the key type. Like the size_t vl operand or a store intrinsic returning 
void.  There is no separate place to put a base type.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D95016/new/

https://reviews.llvm.org/D95016

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D94973: [clang][OpenMP] Use OpenMPIRBuilder for workshare loops.

2021-02-26 Thread Joel E. Denny via Phabricator via cfe-commits
jdenny added a comment.

One property of this patch that has bothered me is that OMPCanonicalLoop is not 
a loop.  Instead, it's an AST node that is sandwiched between a directive and a 
loop to contain extra information about the loop.  The TreeTransform issues 
we've been discussing highlight how that extra node can be confusing.

Now I remember that there's D95496 , which 
seems not to have that property.  I haven't reviewed that patch in any detail, 
and I haven't tried to locate any prior discussions.  Can you please summarize 
why you prefer the current patch over that one?




Comment at: clang/lib/Sema/TreeTransform.h:8321
+TreeTransform::TransformOMPCanonicalLoop(OMPCanonicalLoop *L) {
+  // The OMPCanonicalLoop will be recreated when transforming the 
loop-associted
+  // directive.

Meinersbur wrote:
> jdenny wrote:
> > Meinersbur wrote:
> > > jdenny wrote:
> > > > Meinersbur wrote:
> > > > > jdenny wrote:
> > > > > > Meinersbur wrote:
> > > > > > > jdenny wrote:
> > > > > > > > I'm used to seeing `TransformX` call `RebuildX` call `ActOnX`.  
> > > > > > > > Why not do that for `X=OMPCanonicalLoop`?  Does 
> > > > > > > > `TransformOMPExecutableDirective` really need a special case 
> > > > > > > > for `OMPCanonicalLoop`?
> > > > > > > The intended behaviour is: 
> > > > > > > 
> > > > > > > 1. Transform the child loop
> > > > > > > 2. Return the child loop as representing the OMPCanonicalLoop 
> > > > > > > (i.e. OMPCanonicalLoop wrapper is removed).
> > > > > > > 3. Parent loop-associated directive (e.g. workshare) is processed.
> > > > > > > 4. `ActOnOpenMPCanonicalLoop` adds new OMPCanonicalLoop wrapper 
> > > > > > > for loop nest.
> > > > > > > 
> > > > > > > This guarantees maximum flexibility on what of the loop can be 
> > > > > > > changed, such as
> > > > > > > * Change lower bound, upper bound, step
> > > > > > > * Convert between CXXForRangeStmt and ForStmt
> > > > > > > * Change the associated depth (e.g. different value for 
> > > > > > > `collapse` clause)
> > > > > > > * Remove the directive and no OMPCanonicalLoop remain
> > > > > > > 
> > > > > > > This also saves adding many lines of code handling transforming 
> > > > > > > each member of OMPCanonicalLoop separately.
> > > > > > > The intended behaviour is: 
> > > > > > > 
> > > > > > > 1. Transform the child loop
> > > > > > 
> > > > > > For  my suggestion, that call would remain within 
> > > > > > `TransformOMPCanonicalLoop` where it is now.
> > > > > > 
> > > > > > > 2. Return the child loop as representing the OMPCanonicalLoop 
> > > > > > > (i.e. OMPCanonicalLoop wrapper is removed).
> > > > > > 
> > > > > > For my suggestion, this would not happen.  I think it's normal for 
> > > > > > a `TransformX` to return the transformed `X` not the transformed 
> > > > > > child of `X`.  If a caller wants to transform the child, then it 
> > > > > > should transform the child directly instead.
> > > > > > 
> > > > > > > 3. Parent loop-associated directive (e.g. workshare) is processed.
> > > > > > 
> > > > > > It looks to me like step 3 is currently within 
> > > > > > `TransformOMPExecutableDirective` and starts before the call to 
> > > > > > `TranformOMPCanonicalLoop` and thus before step 1.  It completes 
> > > > > > after step 4.  Or am I misunderstanding what you're describing as 
> > > > > > step 3?
> > > > > > 
> > > > > > > 4. `ActOnOpenMPCanonicalLoop` adds new OMPCanonicalLoop wrapper 
> > > > > > > for loop nest.
> > > > > > 
> > > > > > For my suggestion, this would still happen.  However, instead of 
> > > > > > step 2: within `TransformOMPCanonicalLoop`, you would call 
> > > > > > `RebuildOMPCanonicalLoop`, which would call 
> > > > > > `ActOnOpenMPCanonicalLoop` as step 4.  The effect is you moved 
> > > > > > `ActOnOpenMPCanonicalLoop` from the caller 
> > > > > > (`TransformOMPExecutableDirective`) to the callee's callee, but the 
> > > > > > behavior should remain the same.
> > > > > > 
> > > > > > > This guarantees maximum flexibility on what of the loop can be 
> > > > > > > changed, such as
> > > > > > > * Change lower bound, upper bound, step
> > > > > > > * Convert between CXXForRangeStmt and ForStmt
> > > > > > > * Change the associated depth (e.g. different value for 
> > > > > > > `collapse` clause)
> > > > > > > * Remove the directive and no OMPCanonicalLoop remain
> > > > > > 
> > > > > > Flexibility for whom?
> > > > > > 
> > > > > > A class extending `TreeTransform`?  With my suggestion, it can 
> > > > > > override `TransformOMPCanonicalLoop` or `RebuildOMPCanonicalLoop`, 
> > > > > > depending on how much it wants to alter the transformation.
> > > > > > 
> > > > > > Or a caller of `TransformOMPCanonicalLoop` within `TreeTransform`?  
> > > > > > I only see one right now, `TransformOMPExecutableDirective`, and I 
> > > > > > don't see how it needs the flexibility.  Are there other callers I 
> > > > > > missed?
> > > > > > 
> > > 

[PATCH] D97183: [analyzer] Add NoteTag for smart-ptr get()

2021-02-26 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added a comment.

The warning should be emitted but it shouldn't have a note at `P.get()` telling 
the user that an inner pointer was obtained.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97183/new/

https://reviews.llvm.org/D97183

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D95016: [Clang][RISCV] Add custom TableGen backend for riscv-vector intrinsics.

2021-02-26 Thread Jessica Clarke via Phabricator via cfe-commits
jrtc27 added inline comments.



Comment at: clang/include/clang/Basic/riscv_vector.td:56
+//
+//   e: type of "t" as is (identity)
+//   v: computes a vector type whose element type is "t" for the current LMUL

khchen wrote:
> jrtc27 wrote:
> > Do we really need to invent an esoteric DSL?
> I think this is different design choose.
> Current design is based on 
> https://repo.hca.bsc.es/gitlab/rferrer/llvm-epi/-/blob/EPI/clang/include/clang/Basic/epi_builtins.td,
>  personally I think it makes td file more simpler.
> 
> Of course we can make td file more complex little bit and list all legal type 
> and combination like 
> https://github.com/isrc-cas/rvv-llvm/blob/rvv-iscas/clang/include/clang/Basic/riscv_vector.td
>  did.
> 
> In fact, I don't have a strong opinion on which one is better
> 
> ps. current approach is similar to arm_sve.td design, maybe they know the 
> some critical reason.
I just find it really obfuscates things when we have all these magic character 
sequences.



Comment at: clang/include/clang/Basic/riscv_vector.td:66
+//  element type which is bool
+//   0: void type, ignores "t"
+//   z: size_t, ignores "t"

khchen wrote:
> jrtc27 wrote:
> > Then why aren't these just base types? We don't have to follow the 
> > brain-dead nature of printf.
> Basically builtin interface is instantiated by the "base type + LMUL" with 
> type transformers. But in some intrinsic function we need a specific type 
> regardless "base type + LMUL"
> ex. `vuint32m2_t vssrl_vx_u32m2_vl (vuint32m2_t op1, uint8_t op2, size_t vl);`
Then fix the way you define these? This is just bad design IMO.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D95016/new/

https://reviews.llvm.org/D95016

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D97567: [clang-tidy] performance-* checks: Also allow allow member expressions to be used in a const manner.

2021-02-26 Thread Felix Berger via Phabricator via cfe-commits
flx created this revision.
flx added reviewers: aaron.ballman, sbenza.
Herald added a subscriber: xazax.hun.
flx requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Until now when determining all the const uses of a VarDecl we only considered
how the variable itself was used. This change extends checking for const usages
of the type's members as well.

This increases the number of true positives for various performance checks that
share the same const usage analysis.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D97567

Files:
  clang-tools-extra/clang-tidy/utils/DeclRefExprUtils.cpp
  clang-tools-extra/test/clang-tidy/checkers/performance-for-range-copy.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/performance-for-range-copy.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/performance-for-range-copy.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/performance-for-range-copy.cpp
@@ -296,3 +296,37 @@
 // SS : createView(*ValueReturningIterator())) {
   }
 }
+
+void positiveConstMemberExpr() {
+  struct Struct {
+Mutable Member;
+  };
+  for (Struct SS : View>()) {
+// CHECK-MESSAGES: [[@LINE-1]]:15: warning: loop variable is copied
+// CHECK-FIXES: for (const Struct& SS : View>()) {
+auto MemberCopy = SS.Member;
+const auto  = SS.Member;
+bool b = SS.Member.constMethod();
+use(SS.Member);
+useByConstValue(SS.Member);
+useByValue(SS.Member);
+  }
+}
+
+void negativeNonConstMemberExpr() {
+  struct Struct {
+Mutable Member;
+  };
+  for (Struct SS : View>()) {
+SS.Member.setBool(true);
+  }
+  for (Struct SS : View>()) {
+SS.Member[1];
+  }
+  for (Struct SS : View>()) {
+mutate(SS.Member);
+  }
+  for (Struct SS : View>()) {
+mutate();
+  }
+}
Index: clang-tools-extra/clang-tidy/utils/DeclRefExprUtils.cpp
===
--- clang-tools-extra/clang-tidy/utils/DeclRefExprUtils.cpp
+++ clang-tools-extra/clang-tidy/utils/DeclRefExprUtils.cpp
@@ -46,14 +46,19 @@
ASTContext ) {
   auto DeclRefToVar =
   declRefExpr(to(varDecl(equalsNode(.bind("declRef");
+  auto MemberExprOfVar = memberExpr(has(DeclRefToVar));
+  auto DeclRefToVarOrMemberExprOfVar =
+  stmt(anyOf(DeclRefToVar, MemberExprOfVar));
   auto ConstMethodCallee = callee(cxxMethodDecl(isConst()));
   // Match method call expressions where the variable is referenced as the this
   // implicit object argument and opertor call expression for member operators
   // where the variable is the 0-th argument.
   auto Matches = match(
-  findAll(expr(anyOf(cxxMemberCallExpr(ConstMethodCallee, on(DeclRefToVar)),
- cxxOperatorCallExpr(ConstMethodCallee,
- hasArgument(0, DeclRefToVar),
+  findAll(expr(anyOf(
+  cxxMemberCallExpr(ConstMethodCallee,
+on(DeclRefToVarOrMemberExprOfVar)),
+  cxxOperatorCallExpr(ConstMethodCallee,
+  hasArgument(0, DeclRefToVarOrMemberExprOfVar),
   Stmt, Context);
   SmallPtrSet DeclRefs;
   extractNodesByIdTo(Matches, "declRef", DeclRefs);
@@ -65,22 +70,23 @@
   ConstReferenceOrValue,
   substTemplateTypeParmType(hasReplacementType(ConstReferenceOrValue;
   auto UsedAsConstRefOrValueArg = forEachArgumentWithParam(
-  DeclRefToVar, parmVarDecl(hasType(ConstReferenceOrValueOrReplaced)));
+  DeclRefToVarOrMemberExprOfVar,
+  parmVarDecl(hasType(ConstReferenceOrValueOrReplaced)));
   Matches = match(findAll(invocation(UsedAsConstRefOrValueArg)), Stmt, Context);
   extractNodesByIdTo(Matches, "declRef", DeclRefs);
   // References and pointers to const assignments.
-  Matches =
-  match(findAll(declStmt(
-has(varDecl(hasType(qualType(matchers::isReferenceToConst())),
-hasInitializer(ignoringImpCasts(DeclRefToVar)),
-Stmt, Context);
+  Matches = match(
+  findAll(declStmt(has(varDecl(
+  hasType(qualType(matchers::isReferenceToConst())),
+  hasInitializer(ignoringImpCasts(DeclRefToVarOrMemberExprOfVar)),
+  Stmt, Context);
   extractNodesByIdTo(Matches, "declRef", DeclRefs);
-  Matches =
-  match(findAll(declStmt(has(varDecl(
-hasType(qualType(matchers::isPointerToConst())),
-hasInitializer(ignoringImpCasts(unaryOperator(
-hasOperatorName("&"), hasUnaryOperand(DeclRefToVar,
-Stmt, Context);
+  Matches = match(findAll(declStmt(has(varDecl(
+  hasType(qualType(matchers::isPointerToConst())),
+  hasInitializer(ignoringImpCasts(unaryOperator(
+  hasOperatorName("&"),
+  

[PATCH] D97512: [clang] removes check against integral-to-pointer conversion...

2021-02-26 Thread Christopher Di Bella via Phabricator via cfe-commits
cjdb marked an inline comment as done.
cjdb added inline comments.



Comment at: clang/lib/Sema/SemaChecking.cpp:10326
+  !isa(
+  Cast->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens()))
+return;

cjdb wrote:
> aaron.ballman wrote:
> > I'm not 100% certain, but would `IgnoreParenImpCasts()` be sufficient here? 
> > (`IgnoreImplicitAsWritten() seems to be a bit special -- the only use of it 
> > I can find in tree is for rewritten binary operator expressions.)
> @rsmith would you mind weighing in here please? My original use-case for 
> `IgnoreImplicitAsWritten` might be different to here and I don't have an 
> answer for @aaron.ballman.
I've tried out `IgnoreParenImpCasts` and it seems to work, but I'd appreciate 
an answer here for future patches please.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97512/new/

https://reviews.llvm.org/D97512

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D97512: [clang] removes check against integral-to-pointer conversion...

2021-02-26 Thread Christopher Di Bella via Phabricator via cfe-commits
cjdb updated this revision to Diff 326748.
cjdb added a comment.

`s/IgnoreImplicitAsWritten/IgnoreParenImpCasts/` since the latter seems to work.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97512/new/

https://reviews.llvm.org/D97512

Files:
  clang/lib/Sema/SemaChecking.cpp
  clang/test/Analysis/free.c
  clang/test/Analysis/free.cpp


Index: clang/test/Analysis/free.cpp
===
--- clang/test/Analysis/free.cpp
+++ clang/test/Analysis/free.cpp
@@ -208,3 +208,39 @@
   // Unknown value
   std::free(x[offset]); // no-warning
 }
+
+struct S {
+  const char* p;
+};
+
+void t18_C_style_C_style_free (S s) {
+  free((void*)(unsigned long long)s.p); // no warning
+}
+
+void t18_C_style_C_style_std_free (S s) {
+  std::free((void*)(unsigned long long)s.p); // no warning
+}
+
+void t18_C_style_reinterpret_free (S s) {
+  free((void*)reinterpret_cast(s.p)); // no warning
+}
+
+void t18_C_style_reinterpret_std_free (S s) {
+  std::free((void*)reinterpret_cast(s.p)); // no warning
+}
+
+void t18_reinterpret_C_style_free (S s) {
+  free(reinterpret_cast((unsigned long long)(s.p))); // no warning
+}
+
+void t18_reinterpret_C_style_std_free (S s) {
+  std::free(reinterpret_cast((unsigned long long)(s.p))); // no warning
+}
+
+void t18_reinterpret_reinterpret_free (S s) {
+  free(reinterpret_cast(reinterpret_cast(s.p))); // 
no warning
+}
+
+void t18_reinterpret_reinterpret_std_free (S s) {
+  std::free(reinterpret_cast(reinterpret_cast(s.p))); // no warning
+}
Index: clang/test/Analysis/free.c
===
--- clang/test/Analysis/free.c
+++ clang/test/Analysis/free.c
@@ -108,3 +108,11 @@
   // expected-warning@-1{{Argument to free() is the address of the function 
'iptr', which is not memory allocated by malloc()}}
   // expected-warning@-2{{attempt to call free on non-heap object 'iptr'}}
 }
+
+struct S {
+  const char* p;
+};
+
+void t18 (struct S s) {
+  free((void*)(unsigned long long)s.p); // no warning
+}
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -10316,11 +10316,18 @@
 const CastExpr *Cast) {
   SmallString<128> SizeString;
   llvm::raw_svector_ostream OS(SizeString);
+
+  clang::CastKind Kind = Cast->getCastKind();
+  if (Kind == clang::CK_BitCast &&
+  !Cast->getSubExpr()->getType()->isFunctionPointerType())
+return;
+  if (Kind == clang::CK_IntegralToPointer &&
+  !isa(
+  Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
+return;
+
   switch (Cast->getCastKind()) {
   case clang::CK_BitCast:
-if (!Cast->getSubExpr()->getType()->isFunctionPointerType())
-  return;
-LLVM_FALLTHROUGH;
   case clang::CK_IntegralToPointer:
   case clang::CK_FunctionToPointerDecay:
 OS << '\'';


Index: clang/test/Analysis/free.cpp
===
--- clang/test/Analysis/free.cpp
+++ clang/test/Analysis/free.cpp
@@ -208,3 +208,39 @@
   // Unknown value
   std::free(x[offset]); // no-warning
 }
+
+struct S {
+  const char* p;
+};
+
+void t18_C_style_C_style_free (S s) {
+  free((void*)(unsigned long long)s.p); // no warning
+}
+
+void t18_C_style_C_style_std_free (S s) {
+  std::free((void*)(unsigned long long)s.p); // no warning
+}
+
+void t18_C_style_reinterpret_free (S s) {
+  free((void*)reinterpret_cast(s.p)); // no warning
+}
+
+void t18_C_style_reinterpret_std_free (S s) {
+  std::free((void*)reinterpret_cast(s.p)); // no warning
+}
+
+void t18_reinterpret_C_style_free (S s) {
+  free(reinterpret_cast((unsigned long long)(s.p))); // no warning
+}
+
+void t18_reinterpret_C_style_std_free (S s) {
+  std::free(reinterpret_cast((unsigned long long)(s.p))); // no warning
+}
+
+void t18_reinterpret_reinterpret_free (S s) {
+  free(reinterpret_cast(reinterpret_cast(s.p))); // no warning
+}
+
+void t18_reinterpret_reinterpret_std_free (S s) {
+  std::free(reinterpret_cast(reinterpret_cast(s.p))); // no warning
+}
Index: clang/test/Analysis/free.c
===
--- clang/test/Analysis/free.c
+++ clang/test/Analysis/free.c
@@ -108,3 +108,11 @@
   // expected-warning@-1{{Argument to free() is the address of the function 'iptr', which is not memory allocated by malloc()}}
   // expected-warning@-2{{attempt to call free on non-heap object 'iptr'}}
 }
+
+struct S {
+  const char* p;
+};
+
+void t18 (struct S s) {
+  free((void*)(unsigned long long)s.p); // no warning
+}
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -10316,11 +10316,18 @@
 const CastExpr *Cast) {
   SmallString<128> SizeString;
   

[PATCH] D97488: [clang-tidy][NFC] Tweak some generation of diag messages

2021-02-26 Thread Nathan James via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG1a721b6a2634: [clang-tidy][NFC] Tweak some generation of 
diag messages (authored by njames93).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97488/new/

https://reviews.llvm.org/D97488

Files:
  clang-tools-extra/clang-tidy/abseil/DurationFactoryFloatCheck.cpp
  clang-tools-extra/clang-tidy/abseil/StringFindStartswithCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/ExceptionEscapeCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/ParentVirtualCallCheck.cpp
  clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp
  clang-tools-extra/clang-tidy/llvm/PreferRegisterOverUnsignedCheck.cpp
  clang-tools-extra/clang-tidy/misc/UnconventionalAssignOperatorCheck.cpp
  clang-tools-extra/clang-tidy/misc/UniqueptrResetReleaseCheck.cpp
  clang-tools-extra/clang-tidy/modernize/AvoidCArraysCheck.cpp
  clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
  clang-tools-extra/clang-tidy/modernize/UseNodiscardCheck.cpp
  clang-tools-extra/clang-tidy/modernize/UseTransparentFunctorsCheck.cpp
  clang-tools-extra/clang-tidy/performance/MoveConstructorInitCheck.cpp
  clang-tools-extra/clang-tidy/performance/NoexceptMoveConstructorCheck.cpp
  clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp
  clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp
  clang-tools-extra/clang-tidy/portability/SIMDIntrinsicsCheck.cpp
  clang-tools-extra/clang-tidy/readability/QualifiedAutoCheck.cpp
  clang-tools-extra/clang-tidy/readability/UseAnyOfAllOfCheck.cpp
  clang-tools-extra/test/clang-tidy/checkers/misc-uniqueptr-reset-release.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/misc-uniqueptr-reset-release.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/misc-uniqueptr-reset-release.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/misc-uniqueptr-reset-release.cpp
@@ -33,27 +33,27 @@
   std::unique_ptr *y = 
 
   a.reset(b.release());
-  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: prefer ptr1 = std::move(ptr2) over ptr1.reset(ptr2.release()) [misc-uniqueptr-reset-release]
+  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: prefer ptr = std::move(ptr2) over ptr.reset(ptr2.release()) [misc-uniqueptr-reset-release]
   // CHECK-FIXES: a = std::move(b);
   a.reset(c.release());
-  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: prefer ptr1 = std::move(ptr2)
+  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: prefer ptr = std::move(ptr2)
   // CHECK-FIXES: a = std::move(c);
   a.reset(Create().release());
   // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: prefer ptr = ReturnUnique() over ptr.reset(ReturnUnique().release()) [misc-uniqueptr-reset-release]
   // CHECK-FIXES: a = Create();
   x->reset(y->release());
-  // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: prefer ptr1 = std::move(ptr2)
+  // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: prefer ptr = std::move(ptr2)
   // CHECK-FIXES: *x = std::move(*y);
   Look().reset(Look().release());
-  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: prefer ptr1 = std::move(ptr2)
+  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: prefer ptr = std::move(ptr2)
   // CHECK-FIXES: Look() = std::move(Look());
   Get()->reset(Get()->release());
-  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: prefer ptr1 = std::move(ptr2)
+  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: prefer ptr = std::move(ptr2)
   // CHECK-FIXES: *Get() = std::move(*Get());
 
   std::unique_ptr func_a, func_b;
   func_a.reset(func_b.release());
-  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: prefer ptr1 = std::move(ptr2)
+  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: prefer ptr = std::move(ptr2)
   // CHECK-FIXES: func_a = std::move(func_b);
 }
 
Index: clang-tools-extra/clang-tidy/readability/UseAnyOfAllOfCheck.cpp
===
--- clang-tools-extra/clang-tidy/readability/UseAnyOfAllOfCheck.cpp
+++ clang-tools-extra/clang-tidy/readability/UseAnyOfAllOfCheck.cpp
@@ -88,19 +88,20 @@
 }
 
 void UseAnyOfAllOfCheck::check(const MatchFinder::MatchResult ) {
-  StringRef Ranges = getLangOpts().CPlusPlus20 ? "::ranges" : "";
 
   if (const auto *S = Result.Nodes.getNodeAs("any_of_loop")) {
 if (!isViableLoop(*S, *Result.Context))
   return;
 
-diag(S->getForLoc(), "replace loop by 'std%0::any_of()'") << Ranges;
+diag(S->getForLoc(), "replace loop by 'std%select{|::ranges}0::any_of()'")
+<< getLangOpts().CPlusPlus20;
   } else if (const auto *S =
  Result.Nodes.getNodeAs("all_of_loop")) {
 if (!isViableLoop(*S, *Result.Context))
   return;
 
-diag(S->getForLoc(), "replace loop by 'std%0::all_of()'") << Ranges;
+diag(S->getForLoc(), "replace loop by 'std%select{|::ranges}0::all_of()'")
+<< getLangOpts().CPlusPlus20;
   }
 }
 
Index: 

[clang-tools-extra] 1a721b6 - [clang-tidy][NFC] Tweak some generation of diag messages

2021-02-26 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2021-02-26T19:10:25Z
New Revision: 1a721b6a2634d9740b389a7604275b426c22600a

URL: 
https://github.com/llvm/llvm-project/commit/1a721b6a2634d9740b389a7604275b426c22600a
DIFF: 
https://github.com/llvm/llvm-project/commit/1a721b6a2634d9740b389a7604275b426c22600a.diff

LOG: [clang-tidy][NFC] Tweak some generation of diag messages

Fix up cases where diag is called by piecing together a string in favour of 
placeholders.
Fix up cases where select could be used instead of duplicating the message for 
sake of 1 word difference.

Reviewed By: aaron.ballman

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

Added: 


Modified: 
clang-tools-extra/clang-tidy/abseil/DurationFactoryFloatCheck.cpp
clang-tools-extra/clang-tidy/abseil/StringFindStartswithCheck.cpp
clang-tools-extra/clang-tidy/bugprone/ExceptionEscapeCheck.cpp
clang-tools-extra/clang-tidy/bugprone/ParentVirtualCallCheck.cpp
clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp
clang-tools-extra/clang-tidy/llvm/PreferRegisterOverUnsignedCheck.cpp
clang-tools-extra/clang-tidy/misc/UnconventionalAssignOperatorCheck.cpp
clang-tools-extra/clang-tidy/misc/UniqueptrResetReleaseCheck.cpp
clang-tools-extra/clang-tidy/modernize/AvoidCArraysCheck.cpp
clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
clang-tools-extra/clang-tidy/modernize/UseNodiscardCheck.cpp
clang-tools-extra/clang-tidy/modernize/UseTransparentFunctorsCheck.cpp
clang-tools-extra/clang-tidy/performance/MoveConstructorInitCheck.cpp
clang-tools-extra/clang-tidy/performance/NoexceptMoveConstructorCheck.cpp
clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp
clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp
clang-tools-extra/clang-tidy/portability/SIMDIntrinsicsCheck.cpp
clang-tools-extra/clang-tidy/readability/QualifiedAutoCheck.cpp
clang-tools-extra/clang-tidy/readability/UseAnyOfAllOfCheck.cpp
clang-tools-extra/test/clang-tidy/checkers/misc-uniqueptr-reset-release.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/abseil/DurationFactoryFloatCheck.cpp 
b/clang-tools-extra/clang-tidy/abseil/DurationFactoryFloatCheck.cpp
index 1f1dc07351ba..4b0ef1b3f4ee 100644
--- a/clang-tools-extra/clang-tidy/abseil/DurationFactoryFloatCheck.cpp
+++ b/clang-tools-extra/clang-tidy/abseil/DurationFactoryFloatCheck.cpp
@@ -59,10 +59,8 @@ void DurationFactoryFloatCheck::check(const 
MatchFinder::MatchResult ) {
 SimpleArg = stripFloatLiteralFraction(Result, *Arg);
 
   if (SimpleArg) {
-diag(MatchedCall->getBeginLoc(),
- (llvm::Twine("use the integer version of absl::") +
-  MatchedCall->getDirectCallee()->getName())
- .str())
+diag(MatchedCall->getBeginLoc(), "use the integer version of absl::%0")
+<< MatchedCall->getDirectCallee()->getName()
 << FixItHint::CreateReplacement(Arg->getSourceRange(), *SimpleArg);
   }
 }

diff  --git a/clang-tools-extra/clang-tidy/abseil/StringFindStartswithCheck.cpp 
b/clang-tools-extra/clang-tidy/abseil/StringFindStartswithCheck.cpp
index 850631300f7a..aa43e7dc3885 100644
--- a/clang-tools-extra/clang-tidy/abseil/StringFindStartswithCheck.cpp
+++ b/clang-tools-extra/clang-tidy/abseil/StringFindStartswithCheck.cpp
@@ -83,24 +83,18 @@ void StringFindStartswithCheck::check(const 
MatchFinder::MatchResult ) {
   Context.getLangOpts());
 
   // Create the StartsWith string, negating if comparison was "!=".
-  bool Neg = ComparisonExpr->getOpcodeStr() == "!=";
-  StringRef StartswithStr;
-  if (Neg) {
-StartswithStr = "!absl::StartsWith";
-  } else {
-StartswithStr = "absl::StartsWith";
-  }
+  bool Neg = ComparisonExpr->getOpcode() == BO_NE;
 
   // Create the warning message and a FixIt hint replacing the original expr.
-  auto Diagnostic =
-  diag(ComparisonExpr->getBeginLoc(),
-   (StringRef("use ") + StartswithStr + " instead of find() " +
-ComparisonExpr->getOpcodeStr() + " 0")
-   .str());
+  auto Diagnostic = diag(ComparisonExpr->getBeginLoc(),
+ "use %select{absl::StartsWith|!absl::StartsWith}0 "
+ "instead of find() %select{==|!=}0 0")
+<< Neg;
 
   Diagnostic << FixItHint::CreateReplacement(
   ComparisonExpr->getSourceRange(),
-  (StartswithStr + "(" + HaystackExprCode + ", " + NeedleExprCode + ")")
+  ((Neg ? "!absl::StartsWith(" : "absl::StartsWith(") + HaystackExprCode +
+   ", " + NeedleExprCode + ")")
   .str());
 
   // Create a preprocessor #include FixIt hint (CreateIncludeInsertion checks

diff  --git a/clang-tools-extra/clang-tidy/bugprone/ExceptionEscapeCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/ExceptionEscapeCheck.cpp
index a78e93aff550..85af540b48fb 100644
--- 

[PATCH] D97544: [clang-tidy] Remove some test c++ mode restrictions.

2021-02-26 Thread Nathan James via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGb18f14d6897b: [clang-tidy] Remove some test c++ mode 
restrictions. (authored by njames93).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97544/new/

https://reviews.llvm.org/D97544

Files:
  
clang-tools-extra/test/clang-tidy/checkers/abseil-faster-strsplit-delimiter.cpp
  clang-tools-extra/test/clang-tidy/checkers/abseil-time-subtraction.cpp
  
clang-tools-extra/test/clang-tidy/checkers/abseil-upgrade-duration-conversions.cpp
  clang-tools-extra/test/clang-tidy/checkers/google-readability-casting.cpp
  clang-tools-extra/test/clang-tidy/checkers/portability-simd-intrinsics-ppc.cpp
  clang-tools-extra/test/clang-tidy/checkers/portability-simd-intrinsics-x86.cpp


Index: 
clang-tools-extra/test/clang-tidy/checkers/portability-simd-intrinsics-x86.cpp
===
--- 
clang-tools-extra/test/clang-tidy/checkers/portability-simd-intrinsics-x86.cpp
+++ 
clang-tools-extra/test/clang-tidy/checkers/portability-simd-intrinsics-x86.cpp
@@ -2,7 +2,10 @@
 // RUN:  -config='{CheckOptions: [ \
 // RUN:{key: portability-simd-intrinsics.Suggest, value: 1} \
 // RUN:  ]}' -- -target x86_64
-// FIXME: Fix the checker to work in C++20 mode.
+// RUN: %check_clang_tidy -std=c++20-or-later %s portability-simd-intrinsics 
-check-suffix=CXX20 %t -- \
+// RUN:  -config='{CheckOptions: [ \
+// RUN:{key: portability-simd-intrinsics.Suggest, value: 1} \
+// RUN:  ]}' -- -target x86_64
 
 typedef long long __m128i __attribute__((vector_size(16)));
 typedef double __m256 __attribute__((vector_size(32)));
@@ -18,7 +21,8 @@
   __m256 d0;
 
   _mm_add_epi32(i0, i1);
-// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: '_mm_add_epi32' can be replaced by 
operator+ on std::experimental::simd objects [portability-simd-intrinsics]
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: '_mm_add_epi32' can be replaced 
by operator+ on std::experimental::simd objects [portability-simd-intrinsics]
+  // CHECK-MESSAGES-CXX20: :[[@LINE-2]]:3: warning: '_mm_add_epi32' can be 
replaced by operator+ on std::simd objects [portability-simd-intrinsics]
   d0 = _mm256_load_pd(0);
   _mm256_store_pd(0, d0);
 
Index: 
clang-tools-extra/test/clang-tidy/checkers/portability-simd-intrinsics-ppc.cpp
===
--- 
clang-tools-extra/test/clang-tidy/checkers/portability-simd-intrinsics-ppc.cpp
+++ 
clang-tools-extra/test/clang-tidy/checkers/portability-simd-intrinsics-ppc.cpp
@@ -2,7 +2,10 @@
 // RUN:  -config='{CheckOptions: [ \
 // RUN:{key: portability-simd-intrinsics.Suggest, value: 1} \
 // RUN:  ]}' -- -target ppc64le -maltivec
-// FIXME: Fix the checker to work in C++20 mode.
+// RUN: %check_clang_tidy -std=c++20-or-later %s portability-simd-intrinsics 
-check-suffix=CXX20 %t -- \
+// RUN:  -config='{CheckOptions: [ \
+// RUN:{key: portability-simd-intrinsics.Suggest, value: 1} \
+// RUN:  ]}' -- -target ppc64le -maltivec
 
 vector int vec_add(vector int, vector int);
 
@@ -10,5 +13,6 @@
   vector int i0, i1;
 
   vec_add(i0, i1);
-// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: 'vec_add' can be replaced by 
operator+ on std::experimental::simd objects [portability-simd-intrinsics]
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: 'vec_add' can be replaced by 
operator+ on std::experimental::simd objects [portability-simd-intrinsics]
+  // CHECK-MESSAGES-CXX20: :[[@LINE-2]]:3: warning: 'vec_add' can be replaced 
by operator+ on std::simd objects [portability-simd-intrinsics]
 }
Index: clang-tools-extra/test/clang-tidy/checkers/google-readability-casting.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/google-readability-casting.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/google-readability-casting.cpp
@@ -1,5 +1,4 @@
 // RUN: %check_clang_tidy -std=c++11-or-later %s google-readability-casting %t
-// FIXME: Fix the checker to work in C++17 mode.
 
 bool g() { return false; }
 
Index: 
clang-tools-extra/test/clang-tidy/checkers/abseil-upgrade-duration-conversions.cpp
===
--- 
clang-tools-extra/test/clang-tidy/checkers/abseil-upgrade-duration-conversions.cpp
+++ 
clang-tools-extra/test/clang-tidy/checkers/abseil-upgrade-duration-conversions.cpp
@@ -1,5 +1,4 @@
 // RUN: %check_clang_tidy -std=c++11-or-later %s 
abseil-upgrade-duration-conversions %t -- -- -I%S/Inputs
-// FIXME: Fix the checker to work in C++17 mode.
 
 using int64_t = long long;
 
Index: clang-tools-extra/test/clang-tidy/checkers/abseil-time-subtraction.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/abseil-time-subtraction.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/abseil-time-subtraction.cpp
@@ -1,5 +1,4 @@
 // RUN: 

[clang-tools-extra] b18f14d - [clang-tidy] Remove some test c++ mode restrictions.

2021-02-26 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2021-02-26T19:09:28Z
New Revision: b18f14d6897b9e9f34ffd0d8ed46b8ac596fbf05

URL: 
https://github.com/llvm/llvm-project/commit/b18f14d6897b9e9f34ffd0d8ed46b8ac596fbf05
DIFF: 
https://github.com/llvm/llvm-project/commit/b18f14d6897b9e9f34ffd0d8ed46b8ac596fbf05.diff

LOG: [clang-tidy] Remove some test c++ mode restrictions.

Some comments are redundant, others just simple fixes.

Reviewed By: aaron.ballman

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

Added: 


Modified: 

clang-tools-extra/test/clang-tidy/checkers/abseil-faster-strsplit-delimiter.cpp
clang-tools-extra/test/clang-tidy/checkers/abseil-time-subtraction.cpp

clang-tools-extra/test/clang-tidy/checkers/abseil-upgrade-duration-conversions.cpp
clang-tools-extra/test/clang-tidy/checkers/google-readability-casting.cpp

clang-tools-extra/test/clang-tidy/checkers/portability-simd-intrinsics-ppc.cpp

clang-tools-extra/test/clang-tidy/checkers/portability-simd-intrinsics-x86.cpp

Removed: 




diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/abseil-faster-strsplit-delimiter.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/abseil-faster-strsplit-delimiter.cpp
index ff8c034d2b1f..b5035941c9ce 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/abseil-faster-strsplit-delimiter.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/abseil-faster-strsplit-delimiter.cpp
@@ -1,5 +1,4 @@
 // RUN: %check_clang_tidy -std=c++11-or-later %s 
abseil-faster-strsplit-delimiter %t
-// FIXME: Fix the checker to work in C++17 mode.
 
 namespace absl {
 

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/abseil-time-subtraction.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/abseil-time-subtraction.cpp
index 6fd239bb457c..43d1feea1ec1 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/abseil-time-subtraction.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/abseil-time-subtraction.cpp
@@ -1,5 +1,4 @@
 // RUN: %check_clang_tidy -std=c++11-or-later %s abseil-time-subtraction %t -- 
-- -I %S/Inputs
-// FIXME: Fix the checker to work in C++17 mode.
 
 #include "absl/time/time.h"
 

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/abseil-upgrade-duration-conversions.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/abseil-upgrade-duration-conversions.cpp
index db393a96a50d..32e65a63eb1c 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/abseil-upgrade-duration-conversions.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/abseil-upgrade-duration-conversions.cpp
@@ -1,5 +1,4 @@
 // RUN: %check_clang_tidy -std=c++11-or-later %s 
abseil-upgrade-duration-conversions %t -- -- -I%S/Inputs
-// FIXME: Fix the checker to work in C++17 mode.
 
 using int64_t = long long;
 

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/google-readability-casting.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/google-readability-casting.cpp
index 4655e27cd8bc..bddc28c2d81e 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/google-readability-casting.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/google-readability-casting.cpp
@@ -1,5 +1,4 @@
 // RUN: %check_clang_tidy -std=c++11-or-later %s google-readability-casting %t
-// FIXME: Fix the checker to work in C++17 mode.
 
 bool g() { return false; }
 

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/portability-simd-intrinsics-ppc.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/portability-simd-intrinsics-ppc.cpp
index 963379141a13..5c03d39f736a 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/portability-simd-intrinsics-ppc.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/portability-simd-intrinsics-ppc.cpp
@@ -2,7 +2,10 @@
 // RUN:  -config='{CheckOptions: [ \
 // RUN:{key: portability-simd-intrinsics.Suggest, value: 1} \
 // RUN:  ]}' -- -target ppc64le -maltivec
-// FIXME: Fix the checker to work in C++20 mode.
+// RUN: %check_clang_tidy -std=c++20-or-later %s portability-simd-intrinsics 
-check-suffix=CXX20 %t -- \
+// RUN:  -config='{CheckOptions: [ \
+// RUN:{key: portability-simd-intrinsics.Suggest, value: 1} \
+// RUN:  ]}' -- -target ppc64le -maltivec
 
 vector int vec_add(vector int, vector int);
 
@@ -10,5 +13,6 @@ void PPC() {
   vector int i0, i1;
 
   vec_add(i0, i1);
-// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: 'vec_add' can be replaced by 
operator+ on std::experimental::simd objects [portability-simd-intrinsics]
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: 'vec_add' can be replaced by 
operator+ on std::experimental::simd objects [portability-simd-intrinsics]
+  // CHECK-MESSAGES-CXX20: :[[@LINE-2]]:3: warning: 'vec_add' can be replaced 
by operator+ on std::simd objects [portability-simd-intrinsics]
 }

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/portability-simd-intrinsics-x86.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/portability-simd-intrinsics-x86.cpp

[PATCH] D97563: [clang-tidy] Enable modernize-concat-nested-namespaces also on headers

2021-02-26 Thread Nathan James via Phabricator via cfe-commits
njames93 added inline comments.



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/modernize-concat-nested-namespaces.cpp:4
+// RUN: FileCheck -input-file=%T/modernize-concat-nested-namespaces.h 
%S/Inputs/modernize-concat-nested-namespaces/modernize-concat-nested-namespaces.h
 -check-prefix=CHECK-FIXES
+// Restore header file and re-run with c++2b:
+// RUN: cp 
%S/Inputs/modernize-concat-nested-namespaces/modernize-concat-nested-namespaces.h
 %T/modernize-concat-nested-namespaces.h

DmitryPolukhin wrote:
> njames93 wrote:
> > Why do we explicitly run on c++2b and not c++20? I understand there is no 
> > framework in place for using -std=c++17-or-later when header files are 
> > modified.
> There is no good reason, I just took highest current version. Changed to 
> c++20.
This is just me rambling, but i think we should think about introducing a test 
mode to clang tidy, where fixes can be applied to a test directory and maybe 
try and make use of the verify diagnostic consumer. The current implementation 
works, but is very rough round the edges. 


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97563/new/

https://reviews.llvm.org/D97563

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D95016: [Clang][RISCV] Add custom TableGen backend for riscv-vector intrinsics.

2021-02-26 Thread Craig Topper via Phabricator via cfe-commits
craig.topper accepted this revision.
craig.topper added a comment.
This revision is now accepted and ready to land.

LGTM




Comment at: clang/utils/TableGen/RISCVVEmitter.cpp:908
+
+// Compute Buitlin types
+SmallVector ProtoMaskSeq = ProtoSeq;

Buitlin->Builtin


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D95016/new/

https://reviews.llvm.org/D95016

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D97512: [clang] removes check against integral-to-pointer conversion...

2021-02-26 Thread Christopher Di Bella via Phabricator via cfe-commits
cjdb added a subscriber: rsmith.
cjdb added inline comments.



Comment at: clang/lib/Sema/SemaChecking.cpp:10320
+
+  const clang::CastKind Kind = Cast->getCastKind();
+  if (Kind == clang::CK_BitCast &&

aaron.ballman wrote:
> We don't typically use top-level `const` on locals or params.
This makes Christopher sad :(



Comment at: clang/lib/Sema/SemaChecking.cpp:10326
+  !isa(
+  Cast->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens()))
+return;

aaron.ballman wrote:
> I'm not 100% certain, but would `IgnoreParenImpCasts()` be sufficient here? 
> (`IgnoreImplicitAsWritten() seems to be a bit special -- the only use of it I 
> can find in tree is for rewritten binary operator expressions.)
@rsmith would you mind weighing in here please? My original use-case for 
`IgnoreImplicitAsWritten` might be different to here and I don't have an answer 
for @aaron.ballman.



Comment at: clang/test/Analysis/free.cpp:221
+void t18b (S s) {
+  std::free((void*)(unsigned long long)s.p); // no warning
+}

aaron.ballman wrote:
> I think it'd be useful to add tests for named casts as well as the C-style 
> casts.
Great idea!


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97512/new/

https://reviews.llvm.org/D97512

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D97512: [clang] removes check against integral-to-pointer conversion...

2021-02-26 Thread Christopher Di Bella via Phabricator via cfe-commits
cjdb updated this revision to Diff 326742.
cjdb marked 2 inline comments as done.
cjdb added a comment.

applies comments


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97512/new/

https://reviews.llvm.org/D97512

Files:
  clang/lib/Sema/SemaChecking.cpp
  clang/test/Analysis/free.c
  clang/test/Analysis/free.cpp


Index: clang/test/Analysis/free.cpp
===
--- clang/test/Analysis/free.cpp
+++ clang/test/Analysis/free.cpp
@@ -208,3 +208,39 @@
   // Unknown value
   std::free(x[offset]); // no-warning
 }
+
+struct S {
+  const char* p;
+};
+
+void t18_C_style_C_style_free (S s) {
+  free((void*)(unsigned long long)s.p); // no warning
+}
+
+void t18_C_style_C_style_std_free (S s) {
+  std::free((void*)(unsigned long long)s.p); // no warning
+}
+
+void t18_C_style_reinterpret_free (S s) {
+  free((void*)reinterpret_cast(s.p)); // no warning
+}
+
+void t18_C_style_reinterpret_std_free (S s) {
+  std::free((void*)reinterpret_cast(s.p)); // no warning
+}
+
+void t18_reinterpret_C_style_free (S s) {
+  free(reinterpret_cast((unsigned long long)(s.p))); // no warning
+}
+
+void t18_reinterpret_C_style_std_free (S s) {
+  std::free(reinterpret_cast((unsigned long long)(s.p))); // no warning
+}
+
+void t18_reinterpret_reinterpret_free (S s) {
+  free(reinterpret_cast(reinterpret_cast(s.p))); // 
no warning
+}
+
+void t18_reinterpret_reinterpret_std_free (S s) {
+  std::free(reinterpret_cast(reinterpret_cast(s.p))); // no warning
+}
Index: clang/test/Analysis/free.c
===
--- clang/test/Analysis/free.c
+++ clang/test/Analysis/free.c
@@ -108,3 +108,11 @@
   // expected-warning@-1{{Argument to free() is the address of the function 
'iptr', which is not memory allocated by malloc()}}
   // expected-warning@-2{{attempt to call free on non-heap object 'iptr'}}
 }
+
+struct S {
+  const char* p;
+};
+
+void t18 (struct S s) {
+  free((void*)(unsigned long long)s.p); // no warning
+}
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -10316,11 +10316,18 @@
 const CastExpr *Cast) {
   SmallString<128> SizeString;
   llvm::raw_svector_ostream OS(SizeString);
+
+  clang::CastKind Kind = Cast->getCastKind();
+  if (Kind == clang::CK_BitCast &&
+  !Cast->getSubExpr()->getType()->isFunctionPointerType())
+return;
+  if (Kind == clang::CK_IntegralToPointer &&
+  !isa(
+  Cast->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens()))
+return;
+
   switch (Cast->getCastKind()) {
   case clang::CK_BitCast:
-if (!Cast->getSubExpr()->getType()->isFunctionPointerType())
-  return;
-LLVM_FALLTHROUGH;
   case clang::CK_IntegralToPointer:
   case clang::CK_FunctionToPointerDecay:
 OS << '\'';


Index: clang/test/Analysis/free.cpp
===
--- clang/test/Analysis/free.cpp
+++ clang/test/Analysis/free.cpp
@@ -208,3 +208,39 @@
   // Unknown value
   std::free(x[offset]); // no-warning
 }
+
+struct S {
+  const char* p;
+};
+
+void t18_C_style_C_style_free (S s) {
+  free((void*)(unsigned long long)s.p); // no warning
+}
+
+void t18_C_style_C_style_std_free (S s) {
+  std::free((void*)(unsigned long long)s.p); // no warning
+}
+
+void t18_C_style_reinterpret_free (S s) {
+  free((void*)reinterpret_cast(s.p)); // no warning
+}
+
+void t18_C_style_reinterpret_std_free (S s) {
+  std::free((void*)reinterpret_cast(s.p)); // no warning
+}
+
+void t18_reinterpret_C_style_free (S s) {
+  free(reinterpret_cast((unsigned long long)(s.p))); // no warning
+}
+
+void t18_reinterpret_C_style_std_free (S s) {
+  std::free(reinterpret_cast((unsigned long long)(s.p))); // no warning
+}
+
+void t18_reinterpret_reinterpret_free (S s) {
+  free(reinterpret_cast(reinterpret_cast(s.p))); // no warning
+}
+
+void t18_reinterpret_reinterpret_std_free (S s) {
+  std::free(reinterpret_cast(reinterpret_cast(s.p))); // no warning
+}
Index: clang/test/Analysis/free.c
===
--- clang/test/Analysis/free.c
+++ clang/test/Analysis/free.c
@@ -108,3 +108,11 @@
   // expected-warning@-1{{Argument to free() is the address of the function 'iptr', which is not memory allocated by malloc()}}
   // expected-warning@-2{{attempt to call free on non-heap object 'iptr'}}
 }
+
+struct S {
+  const char* p;
+};
+
+void t18 (struct S s) {
+  free((void*)(unsigned long long)s.p); // no warning
+}
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -10316,11 +10316,18 @@
 const CastExpr *Cast) {
   SmallString<128> SizeString;
   

[PATCH] D97488: [clang-tidy][NFC] Tweak some generation of diag messages

2021-02-26 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.
This revision is now accepted and ready to land.

LGTM! Thanks, these are really nice cleanups!


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97488/new/

https://reviews.llvm.org/D97488

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D97446: Change some addUsedGlobal to addUsedOrCompilerUsedGlobal

2021-02-26 Thread Fangrui Song via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG28cb620321f5: Change some addUsedGlobal to 
addUsedOrCompilerUsedGlobal (authored by MaskRay).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97446/new/

https://reviews.llvm.org/D97446

Files:
  clang/lib/CodeGen/CGDecl.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/CodeGen/CodeGenModule.h
  clang/test/CodeGen/2005-12-04-AttributeUsed.c
  clang/test/CodeGen/attr-msp430.c
  clang/test/CodeGen/attr-target-mv.c
  clang/test/CodeGen/attr-used.c
  clang/test/CodeGen/attr-x86-interrupt.c
  clang/test/CodeGen/keep-static-consts.cpp
  clang/test/CodeGenCUDA/llvm-used.cu
  clang/test/CodeGenCXX/attr-x86-interrupt.cpp
  clang/test/CodeGenCXX/extern-c.cpp

Index: clang/test/CodeGenCXX/extern-c.cpp
===
--- clang/test/CodeGenCXX/extern-c.cpp
+++ clang/test/CodeGenCXX/extern-c.cpp
@@ -70,7 +70,7 @@
 __attribute__((used)) static int duplicate_internal_fn() { return 0; }
   }
 
-  // CHECK: @llvm.used = appending global {{.*}} @internal_var {{.*}} @internal_fn 
+  // CHECK: @llvm.compiler.used = appending global {{.*}} @internal_var {{.*}} @internal_fn
 
   // CHECK-NOT: @unused
   // CHECK-NOT: @duplicate_internal
Index: clang/test/CodeGenCXX/attr-x86-interrupt.cpp
===
--- clang/test/CodeGenCXX/attr-x86-interrupt.cpp
+++ clang/test/CodeGenCXX/attr-x86-interrupt.cpp
@@ -17,11 +17,11 @@
 struct St {
 static void foo9(int *a) __attribute__((interrupt)) {}
 };
-// X86_64_LINUX: @llvm.used = appending global [3 x i8*] [i8* bitcast (void (i32*, i64)* @{{.*}}foo7{{.*}} to i8*), i8* bitcast (void (i32*)* @{{.*}}foo8{{.*}} to i8*), i8* bitcast (void (i32*)* @{{.*}}foo9{{.*}} to i8*)], section "llvm.metadata"
+// X86_64_LINUX: @llvm.compiler.used = appending global [3 x i8*] [i8* bitcast (void (i32*, i64)* @{{.*}}foo7{{.*}} to i8*), i8* bitcast (void (i32*)* @{{.*}}foo8{{.*}} to i8*), i8* bitcast (void (i32*)* @{{.*}}foo9{{.*}} to i8*)], section "llvm.metadata"
 // X86_64_LINUX: define{{.*}} x86_intrcc void @{{.*}}foo7{{.*}}(i32* byval(i32) %{{.+}}, i64 %{{.+}})
 // X86_64_LINUX: define{{.*}} x86_intrcc void @{{.*}}foo8{{.*}}(i32* byval(i32) %{{.+}})
 // X86_64_LINUX: define linkonce_odr x86_intrcc void @{{.*}}foo9{{.*}}(i32* byval(i32) %{{.+}})
-// X86_LINUX: @llvm.used = appending global [3 x i8*] [i8* bitcast (void (i32*, i32)* @{{.*}}foo7{{.*}} to i8*), i8* bitcast (void (i32*)* @{{.*}}foo8{{.*}} to i8*), i8* bitcast (void (i32*)* @{{.*}}foo9{{.*}} to i8*)], section "llvm.metadata"
+// X86_LINUX: @llvm.compiler.used = appending global [3 x i8*] [i8* bitcast (void (i32*, i32)* @{{.*}}foo7{{.*}} to i8*), i8* bitcast (void (i32*)* @{{.*}}foo8{{.*}} to i8*), i8* bitcast (void (i32*)* @{{.*}}foo9{{.*}} to i8*)], section "llvm.metadata"
 // X86_LINUX: define{{.*}} x86_intrcc void @{{.*}}foo7{{.*}}(i32* byval(i32) %{{.+}}, i32 %{{.+}})
 // X86_LINUX: define{{.*}} x86_intrcc void @{{.*}}foo8{{.*}}(i32* byval(i32) %{{.+}})
 // X86_LINUX: define linkonce_odr x86_intrcc void @{{.*}}foo9{{.*}}(i32* byval(i32) %{{.+}})
Index: clang/test/CodeGenCUDA/llvm-used.cu
===
--- clang/test/CodeGenCUDA/llvm-used.cu
+++ clang/test/CodeGenCUDA/llvm-used.cu
@@ -4,5 +4,5 @@
 // Make sure we emit the proper addrspacecast for llvm.used.  PR22383 exposed an
 // issue where we were generating a bitcast instead of an addrspacecast.
 
-// CHECK: @llvm.used = appending global [1 x i8*] [i8* addrspacecast (i8 addrspace(1)* bitcast ([0 x i32] addrspace(1)* @a to i8 addrspace(1)*) to i8*)], section "llvm.metadata"
+// CHECK: @llvm.compiler.used = appending global [1 x i8*] [i8* addrspacecast (i8 addrspace(1)* bitcast ([0 x i32] addrspace(1)* @a to i8 addrspace(1)*) to i8*)], section "llvm.metadata"
 __attribute__((device)) __attribute__((__used__)) int a[] = {};
Index: clang/test/CodeGen/keep-static-consts.cpp
===
--- clang/test/CodeGen/keep-static-consts.cpp
+++ clang/test/CodeGen/keep-static-consts.cpp
@@ -3,7 +3,7 @@
 // CHECK: @_ZL7srcvers = internal constant [4 x i8] c"xyz\00", align 1
 // CHECK: @_ZL8srcvers2 = internal constant [4 x i8] c"abc\00", align 1
 // CHECK: @_ZL1N = internal constant i32 2, align 4
-// CHECK: @llvm.used = appending global [4 x i8*] [i8* getelementptr inbounds ([4 x i8], [4 x i8]* @_ZL7srcvers, i32 0, i32 0), i8* bitcast (i32* @b to i8*), i8* getelementptr inbounds ([4 x i8], [4 x i8]* @_ZL8srcvers2, i32 0, i32 0), i8* bitcast (i32* @_ZL1N to i8*)], section "llvm.metadata"
+// CHECK: @llvm.compiler.used = appending global [4 x i8*] [i8* getelementptr inbounds ([4 x i8], [4 x i8]* @_ZL7srcvers, i32 0, i32 0), i8* bitcast (i32* @b to i8*), i8* getelementptr inbounds ([4 x i8], 

[clang] 28cb620 - Change some addUsedGlobal to addUsedOrCompilerUsedGlobal

2021-02-26 Thread Fangrui Song via cfe-commits

Author: Fangrui Song
Date: 2021-02-26T10:42:07-08:00
New Revision: 28cb620321f5461255423f84c85e6891b5174c13

URL: 
https://github.com/llvm/llvm-project/commit/28cb620321f5461255423f84c85e6891b5174c13
DIFF: 
https://github.com/llvm/llvm-project/commit/28cb620321f5461255423f84c85e6891b5174c13.diff

LOG: Change some addUsedGlobal to addUsedOrCompilerUsedGlobal

An global value in the `llvm.used` list does not have GC root semantics on ELF 
targets.
This will be changed in a subsequent backend patch.

Change some `llvm.used` in the ELF code path to use `llvm.compiler.used` to
prevent undesired GC root semantics.

Change one extern "C" alias (due to `__attribute__((used))` in extern "C") to 
use `llvm.compiler.used` on all targets.

GNU ld has a rule "`__start_/__stop_` references from a live input section 
retain the associated C identifier name sections",
which LLD may drop entirely (currently refined to exclude 
SHF_LINK_ORDER/SHF_GROUP) in a future release (the rule makes it clumsy to GC 
metadata sections; D96914 added a way to try the potential future behavior).
For `llvm.used` global values defined in a C identifier name section, keep 
using `llvm.used` so that
the future LLD change will not affect them.

rnk kindly categorized the changes:
```
ObjC/blocks: this wants GC root semantics, since ObjC mainly runs on Mac.
MS C++ ABI stuff: wants GC root semantics, no change
OpenMP: unsure, but GC root semantics probably don't hurt
CodeGenModule: affected in this patch to *not* use GC root semantics so that 
__attribute__((used)) behavior remains the same on ELF, plus two other minor 
use cases that don't want GC semantics
Coverage: Probably want GC root semantics
CGExpr.cpp: refers to LTO, wants GC root
CGDeclCXX.cpp: one is MS ABI specific, so yes GC root, one is some other C++ 
init functionality, which should form GC roots (C++ initializers can have side 
effects and must run)
CGDecl.cpp: Changed in this patch for __attribute__((used))
```

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

Added: 


Modified: 
clang/lib/CodeGen/CGDecl.cpp
clang/lib/CodeGen/CodeGenModule.cpp
clang/lib/CodeGen/CodeGenModule.h
clang/test/CodeGen/2005-12-04-AttributeUsed.c
clang/test/CodeGen/attr-msp430.c
clang/test/CodeGen/attr-target-mv.c
clang/test/CodeGen/attr-used.c
clang/test/CodeGen/attr-x86-interrupt.c
clang/test/CodeGen/keep-static-consts.cpp
clang/test/CodeGenCUDA/llvm-used.cu
clang/test/CodeGenCXX/attr-x86-interrupt.cpp
clang/test/CodeGenCXX/extern-c.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGDecl.cpp b/clang/lib/CodeGen/CGDecl.cpp
index a01638f0b67b..ecf79dbbaffc 100644
--- a/clang/lib/CodeGen/CGDecl.cpp
+++ b/clang/lib/CodeGen/CGDecl.cpp
@@ -442,7 +442,7 @@ void CodeGenFunction::EmitStaticVarDecl(const VarDecl ,
 var->setSection(SA->getName());
 
   if (D.hasAttr())
-CGM.addUsedGlobal(var);
+CGM.addUsedOrCompilerUsedGlobal(var);
 
   // We may have to cast the constant because of the initializer
   // mismatch above.

diff  --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index 9dcdc8da4d92..564b07582376 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -1820,13 +1820,13 @@ void CodeGenModule::SetCommonAttributes(GlobalDecl GD, 
llvm::GlobalValue *GV) {
 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
 
   if (D && D->hasAttr())
-addUsedGlobal(GV);
+addUsedOrCompilerUsedGlobal(GV);
 
   if (CodeGenOpts.KeepStaticConsts && D && isa(D)) {
 const auto *VD = cast(D);
 if (VD->getType().isConstQualified() &&
 VD->getStorageDuration() == SD_Static)
-  addUsedGlobal(GV);
+  addUsedOrCompilerUsedGlobal(GV);
   }
 }
 
@@ -2087,6 +2087,15 @@ void 
CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
   LLVMCompilerUsed.emplace_back(GV);
 }
 
+void CodeGenModule::addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV) {
+  assert((isa(GV) || !GV->isDeclaration()) &&
+ "Only globals with definition can force usage.");
+  if (getTriple().isOSBinFormatELF())
+LLVMCompilerUsed.emplace_back(GV);
+  else
+LLVMUsed.emplace_back(GV);
+}
+
 static void emitUsed(CodeGenModule , StringRef Name,
  std::vector ) {
   // Don't create llvm.used if there is no need.
@@ -5912,7 +5921,7 @@ void CodeGenModule::EmitStaticExternCAliases() {
 IdentifierInfo *Name = I.first;
 llvm::GlobalValue *Val = I.second;
 if (Val && !getModule().getNamedValue(Name->getName()))
-  addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
+  addCompilerUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
   }
 }
 

diff  --git a/clang/lib/CodeGen/CodeGenModule.h 
b/clang/lib/CodeGen/CodeGenModule.h
index 49f94042a787..d495a169b609 100644
--- a/clang/lib/CodeGen/CodeGenModule.h
+++ 

[PATCH] D97446: Change some addUsedGlobal to addUsedOrCompilerUsedGlobal

2021-02-26 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay updated this revision to Diff 326739.
MaskRay added a comment.

Simplify with `CodeGenModule::getTriple()`


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97446/new/

https://reviews.llvm.org/D97446

Files:
  clang/lib/CodeGen/CGDecl.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/CodeGen/CodeGenModule.h
  clang/test/CodeGen/2005-12-04-AttributeUsed.c
  clang/test/CodeGen/attr-msp430.c
  clang/test/CodeGen/attr-target-mv.c
  clang/test/CodeGen/attr-used.c
  clang/test/CodeGen/attr-x86-interrupt.c
  clang/test/CodeGen/keep-static-consts.cpp
  clang/test/CodeGenCUDA/llvm-used.cu
  clang/test/CodeGenCXX/attr-x86-interrupt.cpp
  clang/test/CodeGenCXX/extern-c.cpp

Index: clang/test/CodeGenCXX/extern-c.cpp
===
--- clang/test/CodeGenCXX/extern-c.cpp
+++ clang/test/CodeGenCXX/extern-c.cpp
@@ -70,7 +70,7 @@
 __attribute__((used)) static int duplicate_internal_fn() { return 0; }
   }
 
-  // CHECK: @llvm.used = appending global {{.*}} @internal_var {{.*}} @internal_fn 
+  // CHECK: @llvm.compiler.used = appending global {{.*}} @internal_var {{.*}} @internal_fn
 
   // CHECK-NOT: @unused
   // CHECK-NOT: @duplicate_internal
Index: clang/test/CodeGenCXX/attr-x86-interrupt.cpp
===
--- clang/test/CodeGenCXX/attr-x86-interrupt.cpp
+++ clang/test/CodeGenCXX/attr-x86-interrupt.cpp
@@ -17,11 +17,11 @@
 struct St {
 static void foo9(int *a) __attribute__((interrupt)) {}
 };
-// X86_64_LINUX: @llvm.used = appending global [3 x i8*] [i8* bitcast (void (i32*, i64)* @{{.*}}foo7{{.*}} to i8*), i8* bitcast (void (i32*)* @{{.*}}foo8{{.*}} to i8*), i8* bitcast (void (i32*)* @{{.*}}foo9{{.*}} to i8*)], section "llvm.metadata"
+// X86_64_LINUX: @llvm.compiler.used = appending global [3 x i8*] [i8* bitcast (void (i32*, i64)* @{{.*}}foo7{{.*}} to i8*), i8* bitcast (void (i32*)* @{{.*}}foo8{{.*}} to i8*), i8* bitcast (void (i32*)* @{{.*}}foo9{{.*}} to i8*)], section "llvm.metadata"
 // X86_64_LINUX: define{{.*}} x86_intrcc void @{{.*}}foo7{{.*}}(i32* byval(i32) %{{.+}}, i64 %{{.+}})
 // X86_64_LINUX: define{{.*}} x86_intrcc void @{{.*}}foo8{{.*}}(i32* byval(i32) %{{.+}})
 // X86_64_LINUX: define linkonce_odr x86_intrcc void @{{.*}}foo9{{.*}}(i32* byval(i32) %{{.+}})
-// X86_LINUX: @llvm.used = appending global [3 x i8*] [i8* bitcast (void (i32*, i32)* @{{.*}}foo7{{.*}} to i8*), i8* bitcast (void (i32*)* @{{.*}}foo8{{.*}} to i8*), i8* bitcast (void (i32*)* @{{.*}}foo9{{.*}} to i8*)], section "llvm.metadata"
+// X86_LINUX: @llvm.compiler.used = appending global [3 x i8*] [i8* bitcast (void (i32*, i32)* @{{.*}}foo7{{.*}} to i8*), i8* bitcast (void (i32*)* @{{.*}}foo8{{.*}} to i8*), i8* bitcast (void (i32*)* @{{.*}}foo9{{.*}} to i8*)], section "llvm.metadata"
 // X86_LINUX: define{{.*}} x86_intrcc void @{{.*}}foo7{{.*}}(i32* byval(i32) %{{.+}}, i32 %{{.+}})
 // X86_LINUX: define{{.*}} x86_intrcc void @{{.*}}foo8{{.*}}(i32* byval(i32) %{{.+}})
 // X86_LINUX: define linkonce_odr x86_intrcc void @{{.*}}foo9{{.*}}(i32* byval(i32) %{{.+}})
Index: clang/test/CodeGenCUDA/llvm-used.cu
===
--- clang/test/CodeGenCUDA/llvm-used.cu
+++ clang/test/CodeGenCUDA/llvm-used.cu
@@ -4,5 +4,5 @@
 // Make sure we emit the proper addrspacecast for llvm.used.  PR22383 exposed an
 // issue where we were generating a bitcast instead of an addrspacecast.
 
-// CHECK: @llvm.used = appending global [1 x i8*] [i8* addrspacecast (i8 addrspace(1)* bitcast ([0 x i32] addrspace(1)* @a to i8 addrspace(1)*) to i8*)], section "llvm.metadata"
+// CHECK: @llvm.compiler.used = appending global [1 x i8*] [i8* addrspacecast (i8 addrspace(1)* bitcast ([0 x i32] addrspace(1)* @a to i8 addrspace(1)*) to i8*)], section "llvm.metadata"
 __attribute__((device)) __attribute__((__used__)) int a[] = {};
Index: clang/test/CodeGen/keep-static-consts.cpp
===
--- clang/test/CodeGen/keep-static-consts.cpp
+++ clang/test/CodeGen/keep-static-consts.cpp
@@ -3,7 +3,7 @@
 // CHECK: @_ZL7srcvers = internal constant [4 x i8] c"xyz\00", align 1
 // CHECK: @_ZL8srcvers2 = internal constant [4 x i8] c"abc\00", align 1
 // CHECK: @_ZL1N = internal constant i32 2, align 4
-// CHECK: @llvm.used = appending global [4 x i8*] [i8* getelementptr inbounds ([4 x i8], [4 x i8]* @_ZL7srcvers, i32 0, i32 0), i8* bitcast (i32* @b to i8*), i8* getelementptr inbounds ([4 x i8], [4 x i8]* @_ZL8srcvers2, i32 0, i32 0), i8* bitcast (i32* @_ZL1N to i8*)], section "llvm.metadata"
+// CHECK: @llvm.compiler.used = appending global [4 x i8*] [i8* getelementptr inbounds ([4 x i8], [4 x i8]* @_ZL7srcvers, i32 0, i32 0), i8* bitcast (i32* @b to i8*), i8* getelementptr inbounds ([4 x i8], [4 x i8]* @_ZL8srcvers2, i32 0, i32 0), i8* bitcast (i32* @_ZL1N to i8*)], section "llvm.metadata"
 
 static const char srcvers[] 

[PATCH] D97553: [clang][NFC] pack StaticDiagInfoRec

2021-02-26 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.
This revision is now accepted and ready to land.

LGTM!




Comment at: clang/lib/Basic/DiagnosticIDs.cpp:171
 const StaticDiagInfoRec StaticDiagInfo[] = {
+// clang-format off
 #define DIAG(ENUM, CLASS, DEFAULT_SEVERITY, DESC, GROUP, SFINAE, NOWERROR, 
\

FWIW, I'd personally prefer to remove the `clang-format on` comment below. I'm 
not keen on littering the code base with workarounds for clang-format.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97553/new/

https://reviews.llvm.org/D97553

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D97566: [WIP][RGT] Rotten Green Test checking for LLVM and Clang unittests

2021-02-26 Thread Paul Robinson via Phabricator via cfe-commits
probinson created this revision.
probinson added reviewers: MaskRay, dblaikie.
Herald added a subscriber: mgrang.
probinson requested review of this revision.
Herald added projects: clang, LLVM.
Herald added a subscriber: cfe-commits.

This is an enhancement of the 'googletest' support code, to report
test assertions (EXPECT_* and ASSERT_* macros) that are not executed.
An un-executed assertion looks like it tests something, and passes (so
is "green") but actually does nothing (so is "rotten").

Due to the number of false positives (for example, all DISABLED tests
will be reported as rotten), running the unittests under lit will
*not* report rotten tests; however, running a unittest program
manually (not under lit) will report these by default.

The RGT support has been tried on Linux using both Clang and GCC as
build compilers, and on Windows with MSVC.  MachO has not been tried.

The intent is to clean up more of the false positives before seeking
to commit the RGT support.  Some of this work has been done already.

This is a Work-In-Progress, not ready for final review, but it seems
mature enough to present to the community in its current form.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D97566

Files:
  clang/test/Unit/lit.cfg.py
  clang/unittests/ASTMatchers/ASTMatchersInternalTest.cpp
  clang/unittests/Tooling/Syntax/MutationsTest.cpp
  llvm/test/Unit/lit.cfg.py
  llvm/unittests/Support/ProgramTest.cpp
  llvm/utils/unittest/googletest/include/gtest/gtest.h
  llvm/utils/unittest/googletest/include/gtest/gtest_pred_impl.h
  llvm/utils/unittest/googletest/include/gtest/internal/gtest-internal.h
  llvm/utils/unittest/googletest/include/gtest/internal/rgt.h
  llvm/utils/unittest/googletest/src/gtest-all.cc
  llvm/utils/unittest/googletest/src/gtest-internal-inl.h
  llvm/utils/unittest/googletest/src/gtest.cc
  llvm/utils/unittest/googletest/src/rgt.cc

Index: llvm/utils/unittest/googletest/src/rgt.cc
===
--- /dev/null
+++ llvm/utils/unittest/googletest/src/rgt.cc
@@ -0,0 +1,236 @@
+//===- rgt.cc - Rotten Green Test support -===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// Support for the Rotten Green Test extension to LLVM's copy of the
+// googletest framework.
+
+#include "gtest/internal/rgt.h"
+#include 
+#include 
+#include 
+#include 
+
+// When we can't get pure static initialization of the array of items
+// describing test points, they get registered on startup and we keep
+// pointers to the data in this vector.
+
+#if GTEST_RGT_RUNTIME_INIT_
+
+namespace {
+
+using item_vector = std::vector;
+class RegisteredItems {
+  static item_vector *items;
+public:
+  RegisteredItems() = default;
+  item_vector *getItems() {
+if (!items)
+  items = new item_vector;
+return items;
+  }
+  int size() { return getItems()->size(); }
+  bool empty() { return getItems()->empty(); }
+  auto begin() { return getItems()->begin(); }
+  auto end() { return getItems()->end(); }
+  void push_back(testing::internal::RGT_item *item) {
+getItems()->push_back(item);
+  }
+};
+
+RegisteredItems registered_items;
+item_vector *RegisteredItems::items = nullptr;
+
+} // end anonymous namespace
+
+void testing::internal::RGT_record(testing::internal::RGT_item *item) {
+  registered_items.push_back(item);
+}
+
+#if GTEST_RGT_RUNTIME_INIT_MANUAL_
+// On Windows we have to allocate our own placeholder start/stop data items.
+// The linker will sort these into the right order relative to real data.
+// Because the section concatenation might be padded, we'll have to skip over
+// any items with a null file pointer, so make the first item look like it's
+// padding.
+
+#define START_SECTION_NAME GTEST_RGT_SECTION_NAME_WITH_SUFFIX_($a)
+#define STOP_SECTION_NAME GTEST_RGT_SECTION_NAME_WITH_SUFFIX_($z)
+
+#pragma section (START_SECTION_NAME,read,write)
+__declspec(allocate(START_SECTION_NAME))
+RGT_recorder RGT_manual_init_start = (RGT_recorder)1;
+
+#pragma section (STOP_SECTION_NAME,read,write)
+__declspec(allocate(STOP_SECTION_NAME))
+RGT_recorder RGT_manual_init_stop = (RGT_recorder)1;
+
+void testing::internal::RGT_init_manual() {
+  const RGT_recorder *F = _manual_init_start;
+  int call_count = 0;
+  int null_count = 0;
+  for (++F; F < _manual_init_stop; ++F) {
+if (*F) {
+  ++call_count;
+  (*F)();
+} else {
+  ++null_count;
+}
+  }
+  printf("RGT_init_manual: %d called, %d null\n", call_count, null_count);
+}
+
+#endif // GTEST_RGT_RUNTIME_INIT_MANUAL_
+#endif // GTEST_RGT_RUNTIME_INIT_
+
+// In order to deduplicate information due to template instantiations,
+// we combine all raw reports for the same source 

[PATCH] D97447: Add GNU attribute 'retain'

2021-02-26 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added a comment.

I have performed a large-scale internal test. I don't find any problem with a 
toolchain built with D97446 /D97447 
/D97448 .


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97447/new/

https://reviews.llvm.org/D97447

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D97411: [DebugInfo] Add an attribute to force type info to be emitted for types that are required to be complete.

2021-02-26 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 326738.
akhuang marked an inline comment as done.
akhuang added a comment.

-Add documentation
-Add more test cases and semantics tests


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97411/new/

https://reviews.llvm.org/D97411

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/test/CodeGenCXX/standalone-debug-attribute.cpp
  clang/test/Sema/attr-standalonedebug.cpp

Index: clang/test/Sema/attr-standalonedebug.cpp
===
--- /dev/null
+++ clang/test/Sema/attr-standalonedebug.cpp
@@ -0,0 +1,14 @@
+// RUN: %clang_cc1 %s -verify -fsyntax-only -DCPP
+// RUN: %clang_cc1 %s -verify -fsyntax-only -x c
+
+#ifdef CPP
+int a __attribute__((standalone_debug)); // expected-warning {{'standalone_debug' attribute only applies to classes}}
+
+void __attribute__((standalone_debug)) b(); // expected-warning {{'standalone_debug' attribute only applies to classes}}
+
+struct __attribute__((standalone_debug(1))) c {}; // expected-error {{'standalone_debug' attribute takes no arguments}}
+
+#else
+// Check that attribute only works in C++.
+struct __attribute__((standalone_debug)) a {}; // expected-warning {{'standalone_debug' attribute ignored}}
+#endif
Index: clang/test/CodeGenCXX/standalone-debug-attribute.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/standalone-debug-attribute.cpp
@@ -0,0 +1,46 @@
+// RUN: %clang_cc1 -DSETATTR=0 -triple x86_64-unknown-linux-gnu -emit-llvm -debug-info-kind=constructor %s -o - | FileCheck %s --check-prefix=DEBUG
+// RUN: %clang_cc1 -DSETATTR=1 -triple x86_64-unknown-linux-gnu -emit-llvm -debug-info-kind=constructor %s -o - | FileCheck %s --check-prefix=WITHATTR
+// Use -debug-info-kind=constructor because it includes all the optimizations.
+
+#if SETATTR
+#define STANDALONEDEBUGATTR __attribute__((standalone_debug))
+#else
+#define STANDALONEDEBUGATTR
+#endif
+
+struct STANDALONEDEBUGATTR StructWithConstructor {
+  StructWithConstructor() {}
+};
+void f(StructWithConstructor s) {}
+// DEBUG:  !DICompositeType({{.*}}name: "StructWithConstructor"
+// DEBUG-SAME:  flags: {{.*}}DIFlagFwdDecl
+// WITHATTR: !DICompositeType({{.*}}name: "StructWithConstructor"
+// WITHATTR-NOT: DIFlagFwdDecl
+
+union STANDALONEDEBUGATTR UnionWithConstructor {
+  UnionWithConstructor() {}
+};
+void f(UnionWithConstructor u) {}
+// DEBUG:  !DICompositeType({{.*}}name: "UnionWithConstructor"
+// DEBUG-SAME:  flags: {{.*}}DIFlagFwdDecl
+// WITHATTR: !DICompositeType({{.*}}name: "UnionWithConstructor"
+// WITHATTR-NOT: DIFlagFwdDecl
+
+template  struct ExternTemplate {
+  ExternTemplate() {}
+  T x;
+};
+extern template struct STANDALONEDEBUGATTR ExternTemplate;
+void f(ExternTemplate s) {}
+// DEBUG: !DICompositeType({{.*}}name: "ExternTemplate"
+// DEBUG-SAME: flags: {{.*}}DIFlagFwdDecl
+// WITHATTR: !DICompositeType({{.*}}name: "ExternTemplate"
+// WITHATTR-NOT: DIFlagFwdDecl
+
+struct STANDALONEDEBUGATTR CompleteTypeRequired {};
+void f(CompleteTypeRequired ) {}
+// DEBUG: !DICompositeType({{.*}}name: "CompleteTypeRequired"
+// DEBUG-SAME: flags: {{.*}}DIFlagFwdDecl
+// WITHATTR: !DICompositeType({{.*}}name: "CompleteTypeRequired"
+// WITHATTR-NOT: DIFlagFwdDecl
+
Index: clang/lib/CodeGen/CGDebugInfo.cpp
===
--- clang/lib/CodeGen/CGDebugInfo.cpp
+++ clang/lib/CodeGen/CGDebugInfo.cpp
@@ -2385,7 +2385,8 @@
   if (DebugKind == codegenoptions::DebugLineTablesOnly)
 return true;
 
-  if (DebugKind > codegenoptions::LimitedDebugInfo)
+  if (DebugKind > codegenoptions::LimitedDebugInfo ||
+  RD->hasAttr())
 return false;
 
   if (!LangOpts.CPlusPlus)
Index: clang/include/clang/Basic/AttrDocs.td
===
--- clang/include/clang/Basic/AttrDocs.td
+++ clang/include/clang/Basic/AttrDocs.td
@@ -1053,6 +1053,16 @@
   }];
 }
 
+def StandaloneDebugDocs : Documentation {
+  let Category = DocCatVariable;
+  let Content = [{
+The ``standalone_debug`` attribute causes debug info to be emitted for a record
+type regardless of the debug info optimizations that are enabled with
+-fno-standalone-debug. This attribute only has an effect when debug info
+optimizations are enabled (e.g. with -fno-standalone-debug), and is C++-only.
+  }];
+}
+
 def NoDuplicateDocs : Documentation {
   let Category = DocCatFunction;
   let Content = [{
Index: clang/include/clang/Basic/Attr.td
===
--- clang/include/clang/Basic/Attr.td
+++ clang/include/clang/Basic/Attr.td
@@ -1660,6 +1660,14 @@
   let Documentation = [NoDebugDocs];
 }
 
+def StandaloneDebug : InheritableAttr {
+  let Spellings = [Clang<"standalone_debug">];
+  let 

[PATCH] D97183: [analyzer] Add NoteTag for smart-ptr get()

2021-02-26 Thread Deep Majumder via Phabricator via cfe-commits
RedDocMD marked an inline comment as done.
RedDocMD added a comment.

In D97183#2589445 , @NoQ wrote:

> Nice!
>
> I suspect you're adding too many notes. The note needs to not be there if the 
> *raw* pointer is not tracked. Eg., I suspect that your patch would add a note 
> in the following case in which it shouldn't be there because the raw pointer 
> value doesn't participate in the report despite smart pointer region being 
> interesting:
>
>   std::unique_ptr P;
>   A *a = P.get(); // shound't emit a note here
>   P->foo();
>
> It's important to not emit redundant notes because users typically take these 
> checker-specific notes as an indication that this information is an essential 
> piece of evidence of the bug in their program. In this example they'd believe 
> that the analyzer has figured out that the smart pointer is null by looking 
> at what happens to the raw pointer value. So they may become very confused if 
> this isn't the case.

@NoQ, in the example you have given, isn't the smart-pointer `P` null? So 
shouldn't a warning be emitted for de-referencing it? Or is it that since `a` 
is not being used, a warning shouldn't be emitted? Sorry, I could not quite 
understand that point ...


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97183/new/

https://reviews.llvm.org/D97183

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D97563: [clang-tidy] Enable modernize-concat-nested-namespaces also on headers

2021-02-26 Thread Dmitry Polukhin via Phabricator via cfe-commits
DmitryPolukhin marked an inline comment as done.
DmitryPolukhin added a comment.

@njames93 thank you for quick response and good suggestion!




Comment at: 
clang-tools-extra/test/clang-tidy/checkers/modernize-concat-nested-namespaces.cpp:4
+// RUN: FileCheck -input-file=%T/modernize-concat-nested-namespaces.h 
%S/Inputs/modernize-concat-nested-namespaces/modernize-concat-nested-namespaces.h
 -check-prefix=CHECK-FIXES
+// Restore header file and re-run with c++2b:
+// RUN: cp 
%S/Inputs/modernize-concat-nested-namespaces/modernize-concat-nested-namespaces.h
 %T/modernize-concat-nested-namespaces.h

njames93 wrote:
> Why do we explicitly run on c++2b and not c++20? I understand there is no 
> framework in place for using -std=c++17-or-later when header files are 
> modified.
There is no good reason, I just took highest current version. Changed to c++20.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97563/new/

https://reviews.llvm.org/D97563

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D97544: [clang-tidy] Remove some test c++ mode restrictions.

2021-02-26 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.
This revision is now accepted and ready to land.

LGTM!


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97544/new/

https://reviews.llvm.org/D97544

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D97563: [clang-tidy] Enable modernize-concat-nested-namespaces also on headers

2021-02-26 Thread Dmitry Polukhin via Phabricator via cfe-commits
DmitryPolukhin updated this revision to Diff 326734.
DmitryPolukhin added a comment.

Comments resolved


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97563/new/

https://reviews.llvm.org/D97563

Files:
  clang-tools-extra/clang-tidy/modernize/ConcatNestedNamespacesCheck.cpp
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/modernize-concat-nested-namespaces/modernize-concat-nested-namespaces.h
  
clang-tools-extra/test/clang-tidy/checkers/modernize-concat-nested-namespaces.cpp


Index: 
clang-tools-extra/test/clang-tidy/checkers/modernize-concat-nested-namespaces.cpp
===
--- 
clang-tools-extra/test/clang-tidy/checkers/modernize-concat-nested-namespaces.cpp
+++ 
clang-tools-extra/test/clang-tidy/checkers/modernize-concat-nested-namespaces.cpp
@@ -1,4 +1,12 @@
-// RUN: %check_clang_tidy -std=c++17-or-later %s 
modernize-concat-nested-namespaces %t
+// RUN: cp 
%S/Inputs/modernize-concat-nested-namespaces/modernize-concat-nested-namespaces.h
 %T/modernize-concat-nested-namespaces.h
+// RUN: %check_clang_tidy -std=c++17 %s modernize-concat-nested-namespaces %t 
-- -header-filter=".*" -- -I %T
+// RUN: FileCheck -input-file=%T/modernize-concat-nested-namespaces.h 
%S/Inputs/modernize-concat-nested-namespaces/modernize-concat-nested-namespaces.h
 -check-prefix=CHECK-FIXES
+// Restore header file and re-run with c++20:
+// RUN: cp 
%S/Inputs/modernize-concat-nested-namespaces/modernize-concat-nested-namespaces.h
 %T/modernize-concat-nested-namespaces.h
+// RUN: %check_clang_tidy -std=c++20 %s modernize-concat-nested-namespaces %t 
-- -header-filter=".*" -- -I %T
+// RUN: FileCheck -input-file=%T/modernize-concat-nested-namespaces.h 
%S/Inputs/modernize-concat-nested-namespaces/modernize-concat-nested-namespaces.h
 -check-prefix=CHECK-FIXES
+
+#include "modernize-concat-nested-namespaces.h"
 
 namespace n1 {}
 
@@ -159,3 +167,5 @@
 
   return 0;
 }
+
+// CHECK-MESSAGES: modernize-concat-nested-namespaces.h:1:1: warning: nested 
namespaces can be concatenated [modernize-concat-nested-namespaces]
Index: 
clang-tools-extra/test/clang-tidy/checkers/Inputs/modernize-concat-nested-namespaces/modernize-concat-nested-namespaces.h
===
--- /dev/null
+++ 
clang-tools-extra/test/clang-tidy/checkers/Inputs/modernize-concat-nested-namespaces/modernize-concat-nested-namespaces.h
@@ -0,0 +1,8 @@
+namespace nn1 {
+namespace nn2 {
+// CHECK-FIXES: namespace nn1::nn2
+void t();
+} // namespace nn2
+} // namespace nn1
+// CHECK-FIXES: void t();
+// CHECK-FIXES-NEXT: } // namespace nn1
Index: clang-tools-extra/clang-tidy/modernize/ConcatNestedNamespacesCheck.cpp
===
--- clang-tools-extra/clang-tidy/modernize/ConcatNestedNamespacesCheck.cpp
+++ clang-tools-extra/clang-tidy/modernize/ConcatNestedNamespacesCheck.cpp
@@ -82,9 +82,6 @@
   if (!locationsInSameFile(Sources, ND.getBeginLoc(), ND.getRBraceLoc()))
 return;
 
-  if (!Sources.isInMainFile(ND.getBeginLoc()))
-return;
-
   if (anonymousOrInlineNamespace(ND))
 return;
 


Index: clang-tools-extra/test/clang-tidy/checkers/modernize-concat-nested-namespaces.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/modernize-concat-nested-namespaces.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/modernize-concat-nested-namespaces.cpp
@@ -1,4 +1,12 @@
-// RUN: %check_clang_tidy -std=c++17-or-later %s modernize-concat-nested-namespaces %t
+// RUN: cp %S/Inputs/modernize-concat-nested-namespaces/modernize-concat-nested-namespaces.h %T/modernize-concat-nested-namespaces.h
+// RUN: %check_clang_tidy -std=c++17 %s modernize-concat-nested-namespaces %t -- -header-filter=".*" -- -I %T
+// RUN: FileCheck -input-file=%T/modernize-concat-nested-namespaces.h %S/Inputs/modernize-concat-nested-namespaces/modernize-concat-nested-namespaces.h -check-prefix=CHECK-FIXES
+// Restore header file and re-run with c++20:
+// RUN: cp %S/Inputs/modernize-concat-nested-namespaces/modernize-concat-nested-namespaces.h %T/modernize-concat-nested-namespaces.h
+// RUN: %check_clang_tidy -std=c++20 %s modernize-concat-nested-namespaces %t -- -header-filter=".*" -- -I %T
+// RUN: FileCheck -input-file=%T/modernize-concat-nested-namespaces.h %S/Inputs/modernize-concat-nested-namespaces/modernize-concat-nested-namespaces.h -check-prefix=CHECK-FIXES
+
+#include "modernize-concat-nested-namespaces.h"
 
 namespace n1 {}
 
@@ -159,3 +167,5 @@
 
   return 0;
 }
+
+// CHECK-MESSAGES: modernize-concat-nested-namespaces.h:1:1: warning: nested namespaces can be concatenated [modernize-concat-nested-namespaces]
Index: clang-tools-extra/test/clang-tidy/checkers/Inputs/modernize-concat-nested-namespaces/modernize-concat-nested-namespaces.h
===
--- 

[PATCH] D96976: [analyzer] Fix reinterpret_cast handling for pointer-to-member

2021-02-26 Thread Deep Majumder via Phabricator via cfe-commits
RedDocMD updated this revision to Diff 326733.
RedDocMD added a comment.

Removed unnecessary includes


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D96976/new/

https://reviews.llvm.org/D96976

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h
  clang/lib/StaticAnalyzer/Core/BasicValueFactory.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
  clang/test/Analysis/reinterpret-cast-pointer-to-member.cpp

Index: clang/test/Analysis/reinterpret-cast-pointer-to-member.cpp
===
--- clang/test/Analysis/reinterpret-cast-pointer-to-member.cpp
+++ clang/test/Analysis/reinterpret-cast-pointer-to-member.cpp
@@ -1,11 +1,11 @@
 // RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection -verify %s
-// XFAIL: asserts
 
 void clang_analyzer_eval(bool);
 
-// TODO: The following test will work properly once reinterpret_cast on pointer-to-member is handled properly
 namespace testReinterpretCasting {
-struct Base {
+struct BaseOfBase {};
+
+struct Base : public BaseOfBase {
   int field;
 };
 
@@ -15,12 +15,51 @@
 
 struct Some {};
 
-void f() {
+void analyzableCasts() {
   int DoubleDerived::*ddf = ::field;
   int Base::*bf = reinterpret_cast(reinterpret_cast(reinterpret_cast(ddf)));
-  int Some::*sf = reinterpret_cast(ddf);
   Base base;
   base.field = 13;
   clang_analyzer_eval(base.*bf == 13); // expected-warning{{TRUE}}
 }
+
+void castOutsideHierarchy() {
+  int DoubleDerived::*ddf = ::field;
+  int Some::*sf = reinterpret_cast(ddf);
+  Some some;
+  some.*sf = 14;
+  clang_analyzer_eval(some.*sf == 14); // expected-warning{{UNKNOWN}}
+}
+
+void castAbove() {
+  int DoubleDerived::*ddf = ::field;
+  int BaseOfBase::*bbf = reinterpret_cast(ddf);
+  BaseOfBase bb;
+  bb.*bbf = 23;
+  clang_analyzer_eval(bb.*bbf == 23); // expected-warning{{UNKNOWN}}
+}
+
+namespace testMultipleInheritance {
+struct A {};
+struct B : public A {};
+struct C {
+  int field;
+};
+struct D : public C {};
+struct E : public B, public D {};
+struct F : public E {};
+
+void testMultiple() {
+  int F::*f = ::field;
+  int A::*a = reinterpret_cast(f);
+  int C::*c = reinterpret_cast(f);
+  A aobj;
+  C cobj;
+  aobj.*a = 13;
+  cobj.*c = 29;
+  clang_analyzer_eval(aobj.*a == 13); // expected-warning{{UNKNOWN}}
+  clang_analyzer_eval(cobj.*c == 29); // expected-warning{{TRUE}}
+}
+} // namespace testMultipleInheritance
+
 } // namespace testReinterpretCasting
Index: clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
===
--- clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
+++ clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
@@ -522,8 +522,7 @@
 continue;
   }
   case CK_DerivedToBaseMemberPointer:
-  case CK_BaseToDerivedMemberPointer:
-  case CK_ReinterpretMemberPointer: {
+  case CK_BaseToDerivedMemberPointer: {
 SVal V = state->getSVal(Ex, LCtx);
 if (auto PTMSV = V.getAs()) {
   SVal CastedPTMSV =
@@ -537,6 +536,25 @@
 state = handleLVectorSplat(state, LCtx, CastE, Bldr, Pred);
 continue;
   }
+  case CK_ReinterpretMemberPointer: {
+SVal V = state->getSVal(Ex, LCtx);
+if (auto PTMSV = V.getAs()) {
+  if (const auto *ReinterpretE =
+  llvm::dyn_cast(CastE)) {
+if (const PointerToMemberData *Data =
+getBasicVals().basesForReinterpretCast(ReinterpretE,
+   *PTMSV)) {
+  SVal CastedPTMSV = svalBuilder.makePointerToMember(Data);
+  state = state->BindExpr(CastE, LCtx, CastedPTMSV);
+  Bldr.generateNode(CastE, Pred, state);
+  continue;
+}
+  }
+}
+// Explicitly proceed with default handler for this case cascade.
+state = handleLVectorSplat(state, LCtx, CastE, Bldr, Pred);
+continue;
+  }
   // Various C++ casts that are not handled yet.
   case CK_ToUnion:
   case CK_VectorSplat: {
Index: clang/lib/StaticAnalyzer/Core/BasicValueFactory.cpp
===
--- clang/lib/StaticAnalyzer/Core/BasicValueFactory.cpp
+++ clang/lib/StaticAnalyzer/Core/BasicValueFactory.cpp
@@ -13,6 +13,7 @@
 //===--===//
 
 #include "clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h"
+#include "clang/AST/CXXInheritance.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/Store.h"
@@ -22,6 +23,7 @@
 #include "llvm/ADT/ImmutableList.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/SmallVector.h"
 #include 
 #include 
 #include 
@@ -239,13 +241,90 @@
 
 

[PATCH] D97094: [Driver] Print process statistics report on CC_PRINT_PROC_STAT env variable.

2021-02-26 Thread Vlad Vereschaka via Phabricator via cfe-commits
vvereschaka updated this revision to Diff 326729.
vvereschaka added a comment.

Updated diff:

- updated doc parts

@aganea thanks a lot for your suggestions for doc improvements. I have updated 
it accordingly.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97094/new/

https://reviews.llvm.org/D97094

Files:
  clang/docs/UsersManual.rst
  clang/include/clang/Driver/Driver.h
  clang/lib/Driver/Driver.cpp
  clang/test/Driver/cc-print-proc-stat.c
  clang/test/Driver/lit.local.cfg
  clang/tools/driver/driver.cpp

Index: clang/tools/driver/driver.cpp
===
--- clang/tools/driver/driver.cpp
+++ clang/tools/driver/driver.cpp
@@ -258,6 +258,11 @@
   TheDriver.CCLogDiagnostics = !!::getenv("CC_LOG_DIAGNOSTICS");
   if (TheDriver.CCLogDiagnostics)
 TheDriver.CCLogDiagnosticsFilename = ::getenv("CC_LOG_DIAGNOSTICS_FILE");
+
+  // Handle CC_PRINT_PROC_STAT and CC_PRINT_PROC_STAT_FILE.
+  TheDriver.CCPrintProcessStats = !!::getenv("CC_PRINT_PROC_STAT");
+  if (TheDriver.CCPrintProcessStats)
+TheDriver.CCPrintStatReportFilename = ::getenv("CC_PRINT_PROC_STAT_FILE");
 }
 
 static void FixupDiagPrefixExeName(TextDiagnosticPrinter *DiagClient,
Index: clang/test/Driver/lit.local.cfg
===
--- clang/test/Driver/lit.local.cfg
+++ clang/test/Driver/lit.local.cfg
@@ -11,7 +11,7 @@
  'IPHONEOS_DEPLOYMENT_TARGET',
  'SDKROOT', 'CCC_OVERRIDE_OPTIONS',
  'CC_PRINT_OPTIONS', 'CC_PRINT_HEADERS',
- 'CC_LOG_DIAGNOSTICS']
+ 'CC_LOG_DIAGNOSTICS', 'CC_PRINT_PROC_STAT']
 
 for name in driver_overwrite_env_vars:
   if name in config.environment:
Index: clang/test/Driver/cc-print-proc-stat.c
===
--- /dev/null
+++ clang/test/Driver/cc-print-proc-stat.c
@@ -0,0 +1,9 @@
+// RUN: env CC_PRINT_PROC_STAT=1 \
+// RUN: CC_PRINT_PROC_STAT_FILE=%t.csv \
+// RUN: %clang -no-canonical-prefixes -S -o %t.s %s
+// RUN: FileCheck --check-prefix=CHECK-CSV %s < %t.csv
+// CHECK-CSV: clang{{.*}},"{{.*}}.s",{{[0-9]+}},{{[0-9]+}},{{[0-9]+}}
+
+// RUN: env CC_PRINT_PROC_STAT=1 \
+// RUN: %clang -c -fintegrated-as %s | FileCheck %s
+// CHECK: clang{{.*}}: output={{.*}}.o, total={{[0-9.]+}} ms, user={{[0-9.]+}} ms, mem={{[0-9]+}} Kb
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -137,8 +137,9 @@
   ClangExecutable(ClangExecutable), SysRoot(DEFAULT_SYSROOT),
   DriverTitle(Title), CCPrintOptionsFilename(nullptr),
   CCPrintHeadersFilename(nullptr), CCLogDiagnosticsFilename(nullptr),
-  CCCPrintBindings(false), CCPrintOptions(false), CCPrintHeaders(false),
-  CCLogDiagnostics(false), CCGenDiagnostics(false),
+  CCPrintStatReportFilename(nullptr), CCCPrintBindings(false),
+  CCPrintOptions(false), CCPrintHeaders(false), CCLogDiagnostics(false),
+  CCGenDiagnostics(false), CCPrintProcessStats(false),
   TargetTriple(TargetTriple), CCCGenericGCCName(""), Saver(Alloc),
   CheckInputsExist(true), GenReproducer(false),
   SuppressMissingInputWarning(false) {
@@ -1096,6 +1097,15 @@
   GenReproducer = Args.hasFlag(options::OPT_gen_reproducer,
options::OPT_fno_crash_diagnostics,
!!::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH"));
+
+  // Process -fproc-stat-report options.
+  if (const Arg *A = Args.getLastArg(options::OPT_fproc_stat_report_EQ)) {
+CCPrintProcessStats = true;
+CCPrintStatReportFilename = A->getValue();
+  }
+  if (Args.hasArg(options::OPT_fproc_stat_report))
+CCPrintProcessStats = true;
+
   // FIXME: TargetTriple is used by the target-prefixed calls to as/ld
   // and getToolChain is const.
   if (IsCLMode()) {
@@ -4009,62 +4019,58 @@
/*TargetDeviceOffloadKind*/ Action::OFK_None);
   }
 
-  StringRef StatReportFile;
-  bool PrintProcessStat = false;
-  if (const Arg *A = C.getArgs().getLastArg(options::OPT_fproc_stat_report_EQ))
-StatReportFile = A->getValue();
-  if (C.getArgs().hasArg(options::OPT_fproc_stat_report))
-PrintProcessStat = true;
-
   // If we have more than one job, then disable integrated-cc1 for now. Do this
   // also when we need to report process execution statistics.
-  if (C.getJobs().size() > 1 || !StatReportFile.empty() || PrintProcessStat)
+  if (C.getJobs().size() > 1 || CCPrintProcessStats)
 for (auto  : C.getJobs())
   J.InProcess = false;
 
-  if (!StatReportFile.empty() || PrintProcessStat) {
+  if (CCPrintProcessStats) {
 C.setPostCallback([=](const Command , int Res) {
   Optional ProcStat =
   Cmd.getProcessStatistics();
   if (!ProcStat)
 

[PATCH] D97512: [clang] removes check against integral-to-pointer conversion...

2021-02-26 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/lib/Sema/SemaChecking.cpp:10320
+
+  const clang::CastKind Kind = Cast->getCastKind();
+  if (Kind == clang::CK_BitCast &&

We don't typically use top-level `const` on locals or params.



Comment at: clang/lib/Sema/SemaChecking.cpp:10326
+  !isa(
+  Cast->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens()))
+return;

I'm not 100% certain, but would `IgnoreParenImpCasts()` be sufficient here? 
(`IgnoreImplicitAsWritten() seems to be a bit special -- the only use of it I 
can find in tree is for rewritten binary operator expressions.)



Comment at: clang/test/Analysis/free.cpp:221
+void t18b (S s) {
+  std::free((void*)(unsigned long long)s.p); // no warning
+}

I think it'd be useful to add tests for named casts as well as the C-style 
casts.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97512/new/

https://reviews.llvm.org/D97512

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D96976: [analyzer] Fix reinterpret_cast handling for pointer-to-member

2021-02-26 Thread Deep Majumder via Phabricator via cfe-commits
RedDocMD added a comment.

@steakhal, you are absolutely right! It works. Thank you for pointing it out, 
not sure how I missed this earlier this evening.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D96976/new/

https://reviews.llvm.org/D96976

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D96976: [analyzer] Fix reinterpret_cast handling for pointer-to-member

2021-02-26 Thread Deep Majumder via Phabricator via cfe-commits
RedDocMD updated this revision to Diff 326731.
RedDocMD added a comment.

Replaced BFS with existing CXXRecordDeclMethod


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D96976/new/

https://reviews.llvm.org/D96976

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h
  clang/lib/StaticAnalyzer/Core/BasicValueFactory.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
  clang/test/Analysis/reinterpret-cast-pointer-to-member.cpp

Index: clang/test/Analysis/reinterpret-cast-pointer-to-member.cpp
===
--- clang/test/Analysis/reinterpret-cast-pointer-to-member.cpp
+++ clang/test/Analysis/reinterpret-cast-pointer-to-member.cpp
@@ -1,11 +1,11 @@
 // RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection -verify %s
-// XFAIL: asserts
 
 void clang_analyzer_eval(bool);
 
-// TODO: The following test will work properly once reinterpret_cast on pointer-to-member is handled properly
 namespace testReinterpretCasting {
-struct Base {
+struct BaseOfBase {};
+
+struct Base : public BaseOfBase {
   int field;
 };
 
@@ -15,12 +15,51 @@
 
 struct Some {};
 
-void f() {
+void analyzableCasts() {
   int DoubleDerived::*ddf = ::field;
   int Base::*bf = reinterpret_cast(reinterpret_cast(reinterpret_cast(ddf)));
-  int Some::*sf = reinterpret_cast(ddf);
   Base base;
   base.field = 13;
   clang_analyzer_eval(base.*bf == 13); // expected-warning{{TRUE}}
 }
+
+void castOutsideHierarchy() {
+  int DoubleDerived::*ddf = ::field;
+  int Some::*sf = reinterpret_cast(ddf);
+  Some some;
+  some.*sf = 14;
+  clang_analyzer_eval(some.*sf == 14); // expected-warning{{UNKNOWN}}
+}
+
+void castAbove() {
+  int DoubleDerived::*ddf = ::field;
+  int BaseOfBase::*bbf = reinterpret_cast(ddf);
+  BaseOfBase bb;
+  bb.*bbf = 23;
+  clang_analyzer_eval(bb.*bbf == 23); // expected-warning{{UNKNOWN}}
+}
+
+namespace testMultipleInheritance {
+struct A {};
+struct B : public A {};
+struct C {
+  int field;
+};
+struct D : public C {};
+struct E : public B, public D {};
+struct F : public E {};
+
+void testMultiple() {
+  int F::*f = ::field;
+  int A::*a = reinterpret_cast(f);
+  int C::*c = reinterpret_cast(f);
+  A aobj;
+  C cobj;
+  aobj.*a = 13;
+  cobj.*c = 29;
+  clang_analyzer_eval(aobj.*a == 13); // expected-warning{{UNKNOWN}}
+  clang_analyzer_eval(cobj.*c == 29); // expected-warning{{TRUE}}
+}
+} // namespace testMultipleInheritance
+
 } // namespace testReinterpretCasting
Index: clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
===
--- clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
+++ clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
@@ -522,8 +522,7 @@
 continue;
   }
   case CK_DerivedToBaseMemberPointer:
-  case CK_BaseToDerivedMemberPointer:
-  case CK_ReinterpretMemberPointer: {
+  case CK_BaseToDerivedMemberPointer: {
 SVal V = state->getSVal(Ex, LCtx);
 if (auto PTMSV = V.getAs()) {
   SVal CastedPTMSV =
@@ -537,6 +536,25 @@
 state = handleLVectorSplat(state, LCtx, CastE, Bldr, Pred);
 continue;
   }
+  case CK_ReinterpretMemberPointer: {
+SVal V = state->getSVal(Ex, LCtx);
+if (auto PTMSV = V.getAs()) {
+  if (const auto *ReinterpretE =
+  llvm::dyn_cast(CastE)) {
+if (const PointerToMemberData *Data =
+getBasicVals().basesForReinterpretCast(ReinterpretE,
+   *PTMSV)) {
+  SVal CastedPTMSV = svalBuilder.makePointerToMember(Data);
+  state = state->BindExpr(CastE, LCtx, CastedPTMSV);
+  Bldr.generateNode(CastE, Pred, state);
+  continue;
+}
+  }
+}
+// Explicitly proceed with default handler for this case cascade.
+state = handleLVectorSplat(state, LCtx, CastE, Bldr, Pred);
+continue;
+  }
   // Various C++ casts that are not handled yet.
   case CK_ToUnion:
   case CK_VectorSplat: {
Index: clang/lib/StaticAnalyzer/Core/BasicValueFactory.cpp
===
--- clang/lib/StaticAnalyzer/Core/BasicValueFactory.cpp
+++ clang/lib/StaticAnalyzer/Core/BasicValueFactory.cpp
@@ -13,6 +13,7 @@
 //===--===//
 
 #include "clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h"
+#include "clang/AST/CXXInheritance.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/Store.h"
@@ -22,8 +23,11 @@
 #include "llvm/ADT/ImmutableList.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/SmallVector.h"
 #include 
 #include 
+#include 
+#include 
 

[PATCH] D97563: [clang-tidy] Enable modernize-concat-nested-namespaces also on headers

2021-02-26 Thread Nathan James via Phabricator via cfe-commits
njames93 added inline comments.



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/Inputs/modernize-concat-nested-namespaces/modernize-concat-nested-namespaces.h:7
+} // namespace nn1
+// CHECK-FIXES: }

This fix line isn't actually contributing to the test.
Perhaps a better case, assuming clang-format doesn't update the comment, would 
be:
```lang=c++
// CHECK-FIXES: void t();
// CHECK-FIXES-NEXT: } namespace nn1
```



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/modernize-concat-nested-namespaces.cpp:4
+// RUN: FileCheck -input-file=%T/modernize-concat-nested-namespaces.h 
%S/Inputs/modernize-concat-nested-namespaces/modernize-concat-nested-namespaces.h
 -check-prefix=CHECK-FIXES
+// Restore header file and re-run with c++2b:
+// RUN: cp 
%S/Inputs/modernize-concat-nested-namespaces/modernize-concat-nested-namespaces.h
 %T/modernize-concat-nested-namespaces.h

Why do we explicitly run on c++2b and not c++20? I understand there is no 
framework in place for using -std=c++17-or-later when header files are modified.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97563/new/

https://reviews.llvm.org/D97563

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D94973: [clang][OpenMP] Use OpenMPIRBuilder for workshare loops.

2021-02-26 Thread Michael Kruse via Phabricator via cfe-commits
Meinersbur added inline comments.



Comment at: clang/lib/Sema/TreeTransform.h:8321
+TreeTransform::TransformOMPCanonicalLoop(OMPCanonicalLoop *L) {
+  // The OMPCanonicalLoop will be recreated when transforming the 
loop-associted
+  // directive.

jdenny wrote:
> Meinersbur wrote:
> > jdenny wrote:
> > > Meinersbur wrote:
> > > > jdenny wrote:
> > > > > Meinersbur wrote:
> > > > > > jdenny wrote:
> > > > > > > I'm used to seeing `TransformX` call `RebuildX` call `ActOnX`.  
> > > > > > > Why not do that for `X=OMPCanonicalLoop`?  Does 
> > > > > > > `TransformOMPExecutableDirective` really need a special case for 
> > > > > > > `OMPCanonicalLoop`?
> > > > > > The intended behaviour is: 
> > > > > > 
> > > > > > 1. Transform the child loop
> > > > > > 2. Return the child loop as representing the OMPCanonicalLoop (i.e. 
> > > > > > OMPCanonicalLoop wrapper is removed).
> > > > > > 3. Parent loop-associated directive (e.g. workshare) is processed.
> > > > > > 4. `ActOnOpenMPCanonicalLoop` adds new OMPCanonicalLoop wrapper for 
> > > > > > loop nest.
> > > > > > 
> > > > > > This guarantees maximum flexibility on what of the loop can be 
> > > > > > changed, such as
> > > > > > * Change lower bound, upper bound, step
> > > > > > * Convert between CXXForRangeStmt and ForStmt
> > > > > > * Change the associated depth (e.g. different value for `collapse` 
> > > > > > clause)
> > > > > > * Remove the directive and no OMPCanonicalLoop remain
> > > > > > 
> > > > > > This also saves adding many lines of code handling transforming 
> > > > > > each member of OMPCanonicalLoop separately.
> > > > > > The intended behaviour is: 
> > > > > > 
> > > > > > 1. Transform the child loop
> > > > > 
> > > > > For  my suggestion, that call would remain within 
> > > > > `TransformOMPCanonicalLoop` where it is now.
> > > > > 
> > > > > > 2. Return the child loop as representing the OMPCanonicalLoop (i.e. 
> > > > > > OMPCanonicalLoop wrapper is removed).
> > > > > 
> > > > > For my suggestion, this would not happen.  I think it's normal for a 
> > > > > `TransformX` to return the transformed `X` not the transformed child 
> > > > > of `X`.  If a caller wants to transform the child, then it should 
> > > > > transform the child directly instead.
> > > > > 
> > > > > > 3. Parent loop-associated directive (e.g. workshare) is processed.
> > > > > 
> > > > > It looks to me like step 3 is currently within 
> > > > > `TransformOMPExecutableDirective` and starts before the call to 
> > > > > `TranformOMPCanonicalLoop` and thus before step 1.  It completes 
> > > > > after step 4.  Or am I misunderstanding what you're describing as 
> > > > > step 3?
> > > > > 
> > > > > > 4. `ActOnOpenMPCanonicalLoop` adds new OMPCanonicalLoop wrapper for 
> > > > > > loop nest.
> > > > > 
> > > > > For my suggestion, this would still happen.  However, instead of step 
> > > > > 2: within `TransformOMPCanonicalLoop`, you would call 
> > > > > `RebuildOMPCanonicalLoop`, which would call 
> > > > > `ActOnOpenMPCanonicalLoop` as step 4.  The effect is you moved 
> > > > > `ActOnOpenMPCanonicalLoop` from the caller 
> > > > > (`TransformOMPExecutableDirective`) to the callee's callee, but the 
> > > > > behavior should remain the same.
> > > > > 
> > > > > > This guarantees maximum flexibility on what of the loop can be 
> > > > > > changed, such as
> > > > > > * Change lower bound, upper bound, step
> > > > > > * Convert between CXXForRangeStmt and ForStmt
> > > > > > * Change the associated depth (e.g. different value for `collapse` 
> > > > > > clause)
> > > > > > * Remove the directive and no OMPCanonicalLoop remain
> > > > > 
> > > > > Flexibility for whom?
> > > > > 
> > > > > A class extending `TreeTransform`?  With my suggestion, it can 
> > > > > override `TransformOMPCanonicalLoop` or `RebuildOMPCanonicalLoop`, 
> > > > > depending on how much it wants to alter the transformation.
> > > > > 
> > > > > Or a caller of `TransformOMPCanonicalLoop` within `TreeTransform`?  I 
> > > > > only see one right now, `TransformOMPExecutableDirective`, and I 
> > > > > don't see how it needs the flexibility.  Are there other callers I 
> > > > > missed?
> > > > > 
> > > > > Are you trying to create flexibility without requiring deriving from 
> > > > > `TreeTransform`?  But, as far as I can tell, you're doing so at the 
> > > > > expense of normal `TreeTransform` semantics.  Doesn't seem worth it.
> > > > > 
> > > > > If you see a precedent for your approach elsewhere in 
> > > > > `TreeTransform`, please point it out.
> > > > > 
> > > > > > This also saves adding many lines of code handling transforming 
> > > > > > each member of OMPCanonicalLoop separately.
> > > > > 
> > > > > Why would you need to?  In the other `TransformX` functions I looked 
> > > > > at, the arguments to the `RebuildX` function are transformed, and 
> > > > > those are typically just the arguments to the `ActOnX` function.  In 
> > > > > other words, 

[PATCH] D96120: [scudo] Port scudo sanitizer to Windows

2021-02-26 Thread Russell Gallop via Phabricator via cfe-commits
russell.gallop marked 2 inline comments as done.
russell.gallop added a comment.

In D96120#2550941 , @mstorsjo wrote:

> In D96120#2550876 , @russell.gallop 
> wrote:
>
>> In D96120#2546077 , @mstorsjo wrote:
>>
>>> As is, this breaks compilation for mingw. With the three modifications I 
>>> suggest here, it no longer breaks compilation for me - I have no idea if it 
>>> actually works in mingw configurations though, but not breaking compilation 
>>> is at least the first step.
>>
>> Thanks for the information I'll try to run up a mingw environment and check 
>> it works.
>
> In case that turns out to be tricky, I might be able to help with that, at 
> least for building a simple test program with it and running it, if you say 
> how it's supposed to be used  (building/linking with `-fsanitize=scudo`?) and 
> how to inspect whether it actually works.

Hi @mstorsjo. Thanks for the suggestions. I tried running up an mingw 
environment with msys but had trouble getting it working (running into cmake 
issues). Would you be able to help?

Yes, building and linking a program with -fsanitize=scudo is the simple way to 
build a simple program. The support for this is in 
clang/lib/Driver/ToolChains/MSVC.cpp. Would this require support in 
clang/lib/Driver/ToolChains/MinGW.cpp?

I think the best way to test is to run the scudo LIT tests with (e.g.) "ninja 
check-scudo". These build and run some simple test programs and check that 
problems are detected.

Beyond this I built LLVM with scudo and ran check-all. I don't know whether you 
want to go this far. Note that -fsanitize=scudo doesn't work for the MSVC LLVM 
build which uses link/lld-link for linking rather than going via the compiler 
driver so I hooked it into LLVM_INTEGRATED_CRT_ALLOC (see 
https://reviews.llvm.org/D96133). If mingw uses the compiler driver to link 
(like Linux) then you may be able to use -DLLVM_USE_SANITIZER=Scudo on a stage2 
build. This would require some changes to 
llvm/cmake/modules/HandleLLVMOptions.cmake to permit it (I had similar changes 
in https://reviews.llvm.org/D86694). It's harder to tell whether this has 
worked correctly. With MSVC faster ThinLTO links on multi-core machines are a 
good indicator but I guess mingw wouldn't be using the MSVC allocator.

Thanks
Russ




Comment at: compiler-rt/lib/scudo/scudo_new_delete.cpp:30
+#ifdef _WIN64
+COMMENT_EXPORT("??2@YAPEAX_K@Z")// operator new
+COMMENT_EXPORT("??2@YAPEAX_KAEBUnothrow_t@std@@@Z") // operator new nothrow

mstorsjo wrote:
> These don't work in this form for mingw targets (which use the itanium c++ 
> abi).
> 
> By changing `#if SANTIZER_WINDOWS` into `#if SANITIZER_WINDOWS && 
> !defined(__MINGW32__)`, I fixed the linker errors at least.
I've applied this suggestion.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D96120/new/

https://reviews.llvm.org/D96120

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D97563: [clang-tidy] Enable modernize-concat-nested-namespaces also on headers

2021-02-26 Thread Dmitry Polukhin via Phabricator via cfe-commits
DmitryPolukhin created this revision.
DmitryPolukhin added reviewers: hokein, aaron.ballman, alexfh, JonasToth, 
njames93.
DmitryPolukhin added a project: clang.
Herald added a subscriber: xazax.hun.
DmitryPolukhin requested review of this revision.

For some reason the initial implementation of the check had an explicit check
for the main file to avoid being applied in headers. This diff removes this
check and add a test for the check on a header.

Similar approach was proposed in D61989  but 
review there got stuck.

Test Plan: added new test case


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D97563

Files:
  clang-tools-extra/clang-tidy/modernize/ConcatNestedNamespacesCheck.cpp
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/modernize-concat-nested-namespaces/modernize-concat-nested-namespaces.h
  
clang-tools-extra/test/clang-tidy/checkers/modernize-concat-nested-namespaces.cpp


Index: 
clang-tools-extra/test/clang-tidy/checkers/modernize-concat-nested-namespaces.cpp
===
--- 
clang-tools-extra/test/clang-tidy/checkers/modernize-concat-nested-namespaces.cpp
+++ 
clang-tools-extra/test/clang-tidy/checkers/modernize-concat-nested-namespaces.cpp
@@ -1,4 +1,12 @@
-// RUN: %check_clang_tidy -std=c++17-or-later %s 
modernize-concat-nested-namespaces %t
+// RUN: cp 
%S/Inputs/modernize-concat-nested-namespaces/modernize-concat-nested-namespaces.h
 %T/modernize-concat-nested-namespaces.h
+// RUN: %check_clang_tidy -std=c++17 %s modernize-concat-nested-namespaces %t 
-- -header-filter=".*" -- -I %T
+// RUN: FileCheck -input-file=%T/modernize-concat-nested-namespaces.h 
%S/Inputs/modernize-concat-nested-namespaces/modernize-concat-nested-namespaces.h
 -check-prefix=CHECK-FIXES
+// Restore header file and re-run with c++2b:
+// RUN: cp 
%S/Inputs/modernize-concat-nested-namespaces/modernize-concat-nested-namespaces.h
 %T/modernize-concat-nested-namespaces.h
+// RUN: %check_clang_tidy -std=c++2b %s modernize-concat-nested-namespaces %t 
-- -header-filter=".*" -- -I %T
+// RUN: FileCheck -input-file=%T/modernize-concat-nested-namespaces.h 
%S/Inputs/modernize-concat-nested-namespaces/modernize-concat-nested-namespaces.h
 -check-prefix=CHECK-FIXES
+
+#include "modernize-concat-nested-namespaces.h"
 
 namespace n1 {}
 
@@ -159,3 +167,5 @@
 
   return 0;
 }
+
+// CHECK-MESSAGES: modernize-concat-nested-namespaces.h:1:1: warning: nested 
namespaces can be concatenated [modernize-concat-nested-namespaces]
Index: 
clang-tools-extra/test/clang-tidy/checkers/Inputs/modernize-concat-nested-namespaces/modernize-concat-nested-namespaces.h
===
--- /dev/null
+++ 
clang-tools-extra/test/clang-tidy/checkers/Inputs/modernize-concat-nested-namespaces/modernize-concat-nested-namespaces.h
@@ -0,0 +1,7 @@
+namespace nn1 {
+namespace nn2 {
+// CHECK-FIXES: namespace nn1::nn2
+void t();
+} // namespace nn2
+} // namespace nn1
+// CHECK-FIXES: }
Index: clang-tools-extra/clang-tidy/modernize/ConcatNestedNamespacesCheck.cpp
===
--- clang-tools-extra/clang-tidy/modernize/ConcatNestedNamespacesCheck.cpp
+++ clang-tools-extra/clang-tidy/modernize/ConcatNestedNamespacesCheck.cpp
@@ -82,9 +82,6 @@
   if (!locationsInSameFile(Sources, ND.getBeginLoc(), ND.getRBraceLoc()))
 return;
 
-  if (!Sources.isInMainFile(ND.getBeginLoc()))
-return;
-
   if (anonymousOrInlineNamespace(ND))
 return;
 


Index: clang-tools-extra/test/clang-tidy/checkers/modernize-concat-nested-namespaces.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/modernize-concat-nested-namespaces.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/modernize-concat-nested-namespaces.cpp
@@ -1,4 +1,12 @@
-// RUN: %check_clang_tidy -std=c++17-or-later %s modernize-concat-nested-namespaces %t
+// RUN: cp %S/Inputs/modernize-concat-nested-namespaces/modernize-concat-nested-namespaces.h %T/modernize-concat-nested-namespaces.h
+// RUN: %check_clang_tidy -std=c++17 %s modernize-concat-nested-namespaces %t -- -header-filter=".*" -- -I %T
+// RUN: FileCheck -input-file=%T/modernize-concat-nested-namespaces.h %S/Inputs/modernize-concat-nested-namespaces/modernize-concat-nested-namespaces.h -check-prefix=CHECK-FIXES
+// Restore header file and re-run with c++2b:
+// RUN: cp %S/Inputs/modernize-concat-nested-namespaces/modernize-concat-nested-namespaces.h %T/modernize-concat-nested-namespaces.h
+// RUN: %check_clang_tidy -std=c++2b %s modernize-concat-nested-namespaces %t -- -header-filter=".*" -- -I %T
+// RUN: FileCheck -input-file=%T/modernize-concat-nested-namespaces.h %S/Inputs/modernize-concat-nested-namespaces/modernize-concat-nested-namespaces.h -check-prefix=CHECK-FIXES
+
+#include "modernize-concat-nested-namespaces.h"
 
 namespace n1 {}
 
@@ -159,3 +167,5 @@
 
 

[PATCH] D94640: adds more checks to -Wfree-nonheap-object

2021-02-26 Thread Christopher Di Bella via Phabricator via cfe-commits
cjdb added a comment.

In D94640#2590512 , @thakis wrote:

> This seems to flag 
> https://source.chromium.org/chromium/chromium/src/+/master:third_party/libsync/src/sync.c;l=142?q=sync.c=chromium
>  :
>
>   info->sync_fence_info = (uint64_t) calloc(num_fences,
>   sizeof(struct sync_fence_info));
>   if ((void *)info->sync_fence_info == NULL)
>   goto free;
>   
>   err = ioctl(fd, SYNC_IOC_FILE_INFO, info);
>   if (err < 0) {
>   free((void *)info->sync_fence_info);
>   goto free;
>   }
>
> What's the motivation for flagging an integer that's >= sizeof(void*) and 
> that's explicitly cast to void*? That seems like code that's pretty explicit 
> about its intentions.
>
> Did you do true positive / false positive evaluation of this change?

This change was a bit too aggressive and is being rolled back in D97512 
.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D94640/new/

https://reviews.llvm.org/D94640

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D97512: [clang] removes check against integral-to-pointer conversion...

2021-02-26 Thread Christopher Di Bella via Phabricator via cfe-commits
cjdb updated this revision to Diff 326723.
cjdb edited the summary of this revision.
cjdb added a comment.

updates commit message to explain what's going on and why the change


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97512/new/

https://reviews.llvm.org/D97512

Files:
  clang/lib/Sema/SemaChecking.cpp
  clang/test/Analysis/free.c
  clang/test/Analysis/free.cpp


Index: clang/test/Analysis/free.cpp
===
--- clang/test/Analysis/free.cpp
+++ clang/test/Analysis/free.cpp
@@ -208,3 +208,15 @@
   // Unknown value
   std::free(x[offset]); // no-warning
 }
+
+struct S {
+  const char* p;
+};
+
+void t18a (S s) {
+  free((void*)(unsigned long long)s.p); // no warning
+}
+
+void t18b (S s) {
+  std::free((void*)(unsigned long long)s.p); // no warning
+}
Index: clang/test/Analysis/free.c
===
--- clang/test/Analysis/free.c
+++ clang/test/Analysis/free.c
@@ -108,3 +108,11 @@
   // expected-warning@-1{{Argument to free() is the address of the function 
'iptr', which is not memory allocated by malloc()}}
   // expected-warning@-2{{attempt to call free on non-heap object 'iptr'}}
 }
+
+struct S {
+  const char* p;
+};
+
+void t18 (struct S s) {
+  free((void*)(unsigned long long)s.p); // no warning
+}
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -10316,11 +10316,18 @@
 const CastExpr *Cast) {
   SmallString<128> SizeString;
   llvm::raw_svector_ostream OS(SizeString);
+
+  const clang::CastKind Kind = Cast->getCastKind();
+  if (Kind == clang::CK_BitCast &&
+  !Cast->getSubExpr()->getType()->isFunctionPointerType())
+return;
+  if (Kind == clang::CK_IntegralToPointer &&
+  !isa(
+  Cast->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens()))
+return;
+
   switch (Cast->getCastKind()) {
   case clang::CK_BitCast:
-if (!Cast->getSubExpr()->getType()->isFunctionPointerType())
-  return;
-[[clang::fallthrough]];
   case clang::CK_IntegralToPointer:
   case clang::CK_FunctionToPointerDecay:
 OS << '\'';


Index: clang/test/Analysis/free.cpp
===
--- clang/test/Analysis/free.cpp
+++ clang/test/Analysis/free.cpp
@@ -208,3 +208,15 @@
   // Unknown value
   std::free(x[offset]); // no-warning
 }
+
+struct S {
+  const char* p;
+};
+
+void t18a (S s) {
+  free((void*)(unsigned long long)s.p); // no warning
+}
+
+void t18b (S s) {
+  std::free((void*)(unsigned long long)s.p); // no warning
+}
Index: clang/test/Analysis/free.c
===
--- clang/test/Analysis/free.c
+++ clang/test/Analysis/free.c
@@ -108,3 +108,11 @@
   // expected-warning@-1{{Argument to free() is the address of the function 'iptr', which is not memory allocated by malloc()}}
   // expected-warning@-2{{attempt to call free on non-heap object 'iptr'}}
 }
+
+struct S {
+  const char* p;
+};
+
+void t18 (struct S s) {
+  free((void*)(unsigned long long)s.p); // no warning
+}
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -10316,11 +10316,18 @@
 const CastExpr *Cast) {
   SmallString<128> SizeString;
   llvm::raw_svector_ostream OS(SizeString);
+
+  const clang::CastKind Kind = Cast->getCastKind();
+  if (Kind == clang::CK_BitCast &&
+  !Cast->getSubExpr()->getType()->isFunctionPointerType())
+return;
+  if (Kind == clang::CK_IntegralToPointer &&
+  !isa(
+  Cast->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens()))
+return;
+
   switch (Cast->getCastKind()) {
   case clang::CK_BitCast:
-if (!Cast->getSubExpr()->getType()->isFunctionPointerType())
-  return;
-[[clang::fallthrough]];
   case clang::CK_IntegralToPointer:
   case clang::CK_FunctionToPointerDecay:
 OS << '\'';
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D97535: [clangd] Use URIs instead of paths in the index file list

2021-02-26 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added inline comments.



Comment at: clang-tools-extra/clangd/index/FileIndex.cpp:279
   SymbolSlabs.push_back(FileAndSymbols.second);
+  for (const auto  : *FileAndSymbols.second) {
+if (S.Definition)

iterating over all the symbols here (and refs below) seems really unfortunate. 
But looking at the previous discussions that seems to be best of both worlds 
until we populate a file list in SymbolCollector. However, I think it would be 
better to do the looping after releasing the lock (we already have the 
information copied over to our snapshots).

moreover we seem to be still inserting keys of the Symbol and RefSlabs into 
Files, but not doing that for RelationSlabs, why? (i believe we shouldn't be 
inserting the keys at all, if we indeed want to just insert URIs and keep 
treating the keys as opaque objects).


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97535/new/

https://reviews.llvm.org/D97535

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D96612: [clangd] Improve printing of Objective-C categories and methods

2021-02-26 Thread David Goldman via Phabricator via cfe-commits
dgoldman updated this revision to Diff 326719.
dgoldman marked an inline comment as done.
dgoldman added a comment.

Limit changes to document symbols


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D96612/new/

https://reviews.llvm.org/D96612

Files:
  clang-tools-extra/clangd/FindSymbols.cpp
  clang-tools-extra/clangd/unittests/FindSymbolsTests.cpp


Index: clang-tools-extra/clangd/unittests/FindSymbolsTests.cpp
===
--- clang-tools-extra/clangd/unittests/FindSymbolsTests.cpp
+++ clang-tools-extra/clangd/unittests/FindSymbolsTests.cpp
@@ -912,6 +912,42 @@
 WithDetail(""));
 }
 
+TEST(DocumentSymbolsTest, ObjCCategoriesAndClassExtensions) {
+  TestTU TU;
+  TU.ExtraArgs = {"-xobjective-c++", "-Wno-objc-root-class"};
+  Annotations Main(R"cpp(
+  $Cat[[@interface Cat
+  + (id)sharedCat;
+  @end]]
+  $SneakyCat[[@interface Cat (Sneaky)
+  - (id)sneak:(id)behavior;
+  @end]]
+
+  $MeowCat[[@interface Cat ()
+  - (void)meow;
+  @end]]
+  $PurCat[[@interface Cat ()
+  - (void)pur;
+  @end]]
+)cpp");
+  TU.Code = Main.code().str();
+  EXPECT_THAT(
+  getSymbols(TU.build()),
+  ElementsAre(
+  AllOf(WithName("Cat"), SymRange(Main.range("Cat")),
+Children(AllOf(WithName("+sharedCat"),
+   WithKind(SymbolKind::Method,
+  AllOf(WithName("Cat(Sneaky)"), SymRange(Main.range("SneakyCat")),
+Children(
+AllOf(WithName("-sneak:"), WithKind(SymbolKind::Method,
+  AllOf(
+  WithName("Cat()"), SymRange(Main.range("MeowCat")),
+  Children(AllOf(WithName("-meow"), 
WithKind(SymbolKind::Method,
+  AllOf(WithName("Cat()"), SymRange(Main.range("PurCat")),
+Children(
+AllOf(WithName("-pur"), WithKind(SymbolKind::Method));
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/FindSymbols.cpp
===
--- clang-tools-extra/clangd/FindSymbols.cpp
+++ clang-tools-extra/clangd/FindSymbols.cpp
@@ -172,6 +172,22 @@
 }
 
 namespace {
+std::string getSymbolName(ASTContext , const NamedDecl ) {
+  if (const auto *Container = dyn_cast())
+return printObjCContainer(*Container);
+  if (const auto *Method = dyn_cast()) {
+std::string Name;
+llvm::raw_string_ostream OS(Name);
+
+OS << (Method->isInstanceMethod() ? '-' : '+');
+Method->getSelector().print(OS);
+
+OS.flush();
+return Name;
+  }
+  return printName(Ctx, ND);
+}
+
 std::string getSymbolDetail(ASTContext , const NamedDecl ) {
   PrintingPolicy P(Ctx.getPrintingPolicy());
   P.SuppressScope = true;
@@ -220,7 +236,7 @@
   SymbolKind SK = indexSymbolKindToSymbolKind(SymInfo.Kind);
 
   DocumentSymbol SI;
-  SI.name = printName(Ctx, ND);
+  SI.name = getSymbolName(Ctx, ND);
   SI.kind = SK;
   SI.deprecated = ND.isDeprecated();
   SI.range = Range{sourceLocToPosition(SM, SymbolRange->getBegin()),


Index: clang-tools-extra/clangd/unittests/FindSymbolsTests.cpp
===
--- clang-tools-extra/clangd/unittests/FindSymbolsTests.cpp
+++ clang-tools-extra/clangd/unittests/FindSymbolsTests.cpp
@@ -912,6 +912,42 @@
 WithDetail(""));
 }
 
+TEST(DocumentSymbolsTest, ObjCCategoriesAndClassExtensions) {
+  TestTU TU;
+  TU.ExtraArgs = {"-xobjective-c++", "-Wno-objc-root-class"};
+  Annotations Main(R"cpp(
+  $Cat[[@interface Cat
+  + (id)sharedCat;
+  @end]]
+  $SneakyCat[[@interface Cat (Sneaky)
+  - (id)sneak:(id)behavior;
+  @end]]
+
+  $MeowCat[[@interface Cat ()
+  - (void)meow;
+  @end]]
+  $PurCat[[@interface Cat ()
+  - (void)pur;
+  @end]]
+)cpp");
+  TU.Code = Main.code().str();
+  EXPECT_THAT(
+  getSymbols(TU.build()),
+  ElementsAre(
+  AllOf(WithName("Cat"), SymRange(Main.range("Cat")),
+Children(AllOf(WithName("+sharedCat"),
+   WithKind(SymbolKind::Method,
+  AllOf(WithName("Cat(Sneaky)"), SymRange(Main.range("SneakyCat")),
+Children(
+AllOf(WithName("-sneak:"), WithKind(SymbolKind::Method,
+  AllOf(
+  WithName("Cat()"), SymRange(Main.range("MeowCat")),
+  Children(AllOf(WithName("-meow"), WithKind(SymbolKind::Method,
+  AllOf(WithName("Cat()"), SymRange(Main.range("PurCat")),
+Children(
+AllOf(WithName("-pur"), WithKind(SymbolKind::Method));
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/FindSymbols.cpp
===
--- 

[PATCH] D96120: [scudo] Port scudo sanitizer to Windows

2021-02-26 Thread Russell Gallop via Phabricator via cfe-commits
russell.gallop updated this revision to Diff 326716.
russell.gallop added a comment.

Added comment on AllocatorSize.

Applied Mingw changes suggested by @mstorsjo.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D96120/new/

https://reviews.llvm.org/D96120

Files:
  clang/lib/Driver/ToolChains/MSVC.cpp
  compiler-rt/cmake/config-ix.cmake
  compiler-rt/lib/sanitizer_common/sanitizer_win.cpp
  compiler-rt/lib/scudo/CMakeLists.txt
  compiler-rt/lib/scudo/scudo_allocator.cpp
  compiler-rt/lib/scudo/scudo_crc32.cpp
  compiler-rt/lib/scudo/scudo_new_delete.cpp
  compiler-rt/lib/scudo/scudo_platform.h
  compiler-rt/lib/scudo/scudo_tsd.h
  compiler-rt/lib/scudo/scudo_tsd_shared.cpp
  compiler-rt/lib/scudo/scudo_tsd_shared.inc
  compiler-rt/test/scudo/cxx_threads.cpp
  compiler-rt/test/scudo/dealloc-race.c
  compiler-rt/test/scudo/fsanitize.c
  compiler-rt/test/scudo/interface.cpp
  compiler-rt/test/scudo/lit.cfg.py
  compiler-rt/test/scudo/malloc.cpp
  compiler-rt/test/scudo/memalign.c
  compiler-rt/test/scudo/mismatch.cpp
  compiler-rt/test/scudo/overflow.c
  compiler-rt/test/scudo/preload.cpp
  compiler-rt/test/scudo/rss.c
  compiler-rt/test/scudo/secondary.c
  compiler-rt/test/scudo/symbols.test
  compiler-rt/test/scudo/threads.c
  compiler-rt/test/scudo/tsd_destruction.c
  compiler-rt/test/scudo/valloc.c

Index: compiler-rt/test/scudo/valloc.c
===
--- compiler-rt/test/scudo/valloc.c
+++ compiler-rt/test/scudo/valloc.c
@@ -2,7 +2,7 @@
 // RUN: %run %t valid   2>&1
 // RUN: not %run %t invalid 2>&1 | FileCheck %s
 // RUN: %env_scudo_opts=allocator_may_return_null=1 %run %t invalid 2>&1
-// UNSUPPORTED: android
+// UNSUPPORTED: android, windows
 
 // Tests that valloc and pvalloc work as intended.
 
Index: compiler-rt/test/scudo/tsd_destruction.c
===
--- compiler-rt/test/scudo/tsd_destruction.c
+++ compiler-rt/test/scudo/tsd_destruction.c
@@ -1,5 +1,6 @@
 // RUN: %clang_scudo %s -o %t
 // RUN: %run %t 2>&1
+// UNSUPPORTED: windows
 
 #include 
 #include 
Index: compiler-rt/test/scudo/threads.c
===
--- compiler-rt/test/scudo/threads.c
+++ compiler-rt/test/scudo/threads.c
@@ -1,6 +1,7 @@
 // RUN: %clang_scudo %s -o %t
 // RUN: %env_scudo_opts="QuarantineSizeKb=0:ThreadLocalQuarantineSizeKb=0" %run %t 5 100 2>&1
 // RUN: %env_scudo_opts="QuarantineSizeKb=1024:ThreadLocalQuarantineSizeKb=64" %run %t 5 100 2>&1
+// UNSUPPORTED: windows
 
 // Tests parallel allocations and deallocations of memory chunks from a number
 // of concurrent threads, with and without quarantine.
Index: compiler-rt/test/scudo/symbols.test
===
--- compiler-rt/test/scudo/symbols.test
+++ compiler-rt/test/scudo/symbols.test
@@ -1,4 +1,4 @@
-UNSUPPORTED: android
+UNSUPPORTED: android, windows
 
 Verify that various functions are *not* present in the minimal binary. Presence
 of those symbols in the minimal runtime would mean that the split code made it
Index: compiler-rt/test/scudo/secondary.c
===
--- compiler-rt/test/scudo/secondary.c
+++ compiler-rt/test/scudo/secondary.c
@@ -6,37 +6,60 @@
 // allocated by the Secondary allocator, or writing too far in front of it.
 
 #include 
-#include 
-#include 
+#include 
 #include 
 #include 
+#ifdef _WIN32
+#include 
+#else
+#include 
 #include 
+#endif
 
+#ifdef _WIN32
+DWORD getsystempagesize() {
+  SYSTEM_INFO si;
+  GetSystemInfo();
+  return si.dwPageSize;
+}
+LONG WINAPI handler(EXCEPTION_POINTERS *ExceptionInfo) {
+  fprintf(stderr, "AccessViolation\n");
+  ExitProcess(0);
+}
+#else
 void handler(int signo, siginfo_t *info, void *uctx) {
   if (info->si_code == SEGV_ACCERR) {
-fprintf(stderr, "SCUDO SIGSEGV\n");
+fprintf(stderr, "AccessViolation\n");
 exit(0);
   }
   exit(1);
 }
+long getsystempagesize() {
+  return sysconf(_SC_PAGESIZE);
+}
+#endif
 
 int main(int argc, char **argv)
 {
   // The size must be large enough to be serviced by the secondary allocator.
-  long page_size = sysconf(_SC_PAGESIZE);
-  size_t size = (1U << 17) + page_size;
-  struct sigaction a;
+  long page_size = getsystempagesize();
+  size_t size = (1U << 19) + page_size;
 
   assert(argc == 2);
-  memset(, 0, sizeof(a));
-  a.sa_sigaction = handler;
-  a.sa_flags = SA_SIGINFO;
 
   char *p = (char *)malloc(size);
   assert(p);
   memset(p, 'A', size); // This should not trigger anything.
   // Set up the SIGSEGV handler now, as the rest should trigger an AV.
+#ifdef _WIN32
+  SetUnhandledExceptionFilter(handler);
+#else
+  struct sigaction a = {0};
+  a.sa_sigaction = handler;
+  a.sa_flags = SA_SIGINFO;
   sigaction(SIGSEGV, , NULL);

[PATCH] D94640: adds more checks to -Wfree-nonheap-object

2021-02-26 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

This seems to flag 
https://source.chromium.org/chromium/chromium/src/+/master:third_party/libsync/src/sync.c;l=142?q=sync.c=chromium
 :

  info->sync_fence_info = (uint64_t) calloc(num_fences,
  sizeof(struct sync_fence_info));
  if ((void *)info->sync_fence_info == NULL)
  goto free;
  
  err = ioctl(fd, SYNC_IOC_FILE_INFO, info);
  if (err < 0) {
  free((void *)info->sync_fence_info);
  goto free;
  }

What's the motivation for flagging an integer that's >= sizeof(void*) and 
that's explicitly cast to void*? That seems like code that's pretty explicit 
about its intentions.

Did you do true positive / false positive evaluation of this change?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D94640/new/

https://reviews.llvm.org/D94640

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D97561: [clang] Use CompilerInstance::createTarget to createTarget

2021-02-26 Thread Tommy Chiang via Phabricator via cfe-commits
oToToT added inline comments.



Comment at: clang/lib/Frontend/PrecompiledPreamble.cpp:368
   // Create the target instance.
-  Clang->setTarget(TargetInfo::CreateTargetInfo(
-  Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
-  if (!Clang->hasTarget())
+  if (!Clang->createTarget())
 return BuildPreambleError::CouldntCreateTargetInfo;

Changing this without other further patch might cause `clangd` results in 
Runtime Error while handling files like CUDA.
Should I also include the patch of `clangd` or other related projects into this 
patch?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97561/new/

https://reviews.llvm.org/D97561

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D97561: [clang] Use CompilerInstance::createTarget to createTarget

2021-02-26 Thread Tommy Chiang via Phabricator via cfe-commits
oToToT created this revision.
oToToT added reviewers: sammccall, rsmith, klimek, dexonsmith.
oToToT added a project: clang.
oToToT requested review of this revision.
Herald added a subscriber: cfe-commits.

As proposed in D97109 , I tried to replace all 
similar target creating logics to a single CompilerInstance::createTarget call 
introduced in  D97493 .

This improve the consistency while creating Target.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D97561

Files:
  clang/lib/Frontend/ASTUnit.cpp
  clang/lib/Frontend/ChainedIncludesSource.cpp
  clang/lib/Frontend/PrecompiledPreamble.cpp
  clang/tools/clang-import-test/clang-import-test.cpp

Index: clang/tools/clang-import-test/clang-import-test.cpp
===
--- clang/tools/clang-import-test/clang-import-test.cpp
+++ clang/tools/clang-import-test/clang-import-test.cpp
@@ -205,10 +205,7 @@
 
   Ins->setInvocation(std::move(Inv));
 
-  TargetInfo *TI = TargetInfo::CreateTargetInfo(
-  Ins->getDiagnostics(), Ins->getInvocation().TargetOpts);
-  Ins->setTarget(TI);
-  Ins->getTarget().adjust(Ins->getLangOpts());
+  Ins->createTarget();
   Ins->createFileManager();
   Ins->createSourceManager(Ins->getFileManager());
   Ins->createPreprocessor(TU_Complete);
Index: clang/lib/Frontend/PrecompiledPreamble.cpp
===
--- clang/lib/Frontend/PrecompiledPreamble.cpp
+++ clang/lib/Frontend/PrecompiledPreamble.cpp
@@ -365,17 +365,9 @@
   Clang->setDiagnostics();
 
   // Create the target instance.
-  Clang->setTarget(TargetInfo::CreateTargetInfo(
-  Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
-  if (!Clang->hasTarget())
+  if (!Clang->createTarget())
 return BuildPreambleError::CouldntCreateTargetInfo;
 
-  // Inform the target of the language options.
-  //
-  // FIXME: We shouldn't need to do this, the target should be immutable once
-  // created. This complexity should be lifted elsewhere.
-  Clang->getTarget().adjust(Clang->getLangOpts());
-
   if (Clang->getFrontendOpts().Inputs.size() != 1 ||
   Clang->getFrontendOpts().Inputs[0].getKind().getFormat() !=
   InputKind::Source ||
Index: clang/lib/Frontend/ChainedIncludesSource.cpp
===
--- clang/lib/Frontend/ChainedIncludesSource.cpp
+++ clang/lib/Frontend/ChainedIncludesSource.cpp
@@ -149,8 +149,7 @@
 new CompilerInstance(CI.getPCHContainerOperations()));
 Clang->setInvocation(std::move(CInvok));
 Clang->setDiagnostics(Diags.get());
-Clang->setTarget(TargetInfo::CreateTargetInfo(
-Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
+Clang->createTarget();
 Clang->createFileManager();
 Clang->createSourceManager(Clang->getFileManager());
 Clang->createPreprocessor(TU_Prefix);
Index: clang/lib/Frontend/ASTUnit.cpp
===
--- clang/lib/Frontend/ASTUnit.cpp
+++ clang/lib/Frontend/ASTUnit.cpp
@@ -1150,17 +1150,9 @@
   Clang->setDiagnostics(());
 
   // Create the target instance.
-  Clang->setTarget(TargetInfo::CreateTargetInfo(
-  Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
-  if (!Clang->hasTarget())
+  if (!Clang->createTarget())
 return true;
 
-  // Inform the target of the language options.
-  //
-  // FIXME: We shouldn't need to do this, the target should be immutable once
-  // created. This complexity should be lifted elsewhere.
-  Clang->getTarget().adjust(Clang->getLangOpts());
-
   assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
  "Invocation must have exactly one source file!");
   assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
@@ -1568,17 +1560,9 @@
   Clang->setDiagnostics(>getDiagnostics());
 
   // Create the target instance.
-  Clang->setTarget(TargetInfo::CreateTargetInfo(
-  Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
-  if (!Clang->hasTarget())
+  if (!Clang->createTarget())
 return nullptr;
 
-  // Inform the target of the language options.
-  //
-  // FIXME: We shouldn't need to do this, the target should be immutable once
-  // created. This complexity should be lifted elsewhere.
-  Clang->getTarget().adjust(Clang->getLangOpts());
-
   assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
  "Invocation must have exactly one source file!");
   assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
@@ -2194,19 +2178,11 @@
   ProcessWarningOptions(Diag, Inv.getDiagnosticOpts());
 
   // Create the target instance.
-  Clang->setTarget(TargetInfo::CreateTargetInfo(
-  Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
-  if (!Clang->hasTarget()) {
+  if (!Clang->createTarget()) {
 Clang->setInvocation(nullptr);
 return;
   }
 
-  // Inform the target of 

  1   2   >