[PATCH] D114142: [clang-format] [PR52527] can join * with /* to form an outside of comment error C4138

2021-11-19 Thread Owen Pan via Phabricator via cfe-commits
owenpan added a comment.

In D114142#3139756 , @MyDeveloperDay 
wrote:

> I'm thinking that those cases are handled else where

I was aware of that, but I didn't see `* //` was handled and tested explicitly. 
IMO, using `tok::comment` and adding a test case would make it explicit at no 
extra cost.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114142

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


[PATCH] D107944: [hmaptool] Port to python3

2021-11-19 Thread Ivan Murashko via Phabricator via cfe-commits
ivanmurashko added inline comments.



Comment at: clang/utils/hmaptool/hmaptool:223
 with open(output_path, 'wb') as f:
 f.write(magic.encode())
 f.write(struct.pack(header_fmt, *header))

`magic` is a bytes object that does not have `encode()` method 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D107944

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


[PATCH] D114095: [clang][lex] Include tracking: simplify and move to preprocessor

2021-11-19 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 updated this revision to Diff 388407.
jansvoboda11 added a comment.

Add new record into block info.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114095

Files:
  clang/include/clang/Lex/HeaderSearch.h
  clang/include/clang/Lex/Preprocessor.h
  clang/include/clang/Serialization/ASTBitCodes.h
  clang/include/clang/Serialization/ASTReader.h
  clang/include/clang/Serialization/ASTWriter.h
  clang/lib/Lex/HeaderSearch.cpp
  clang/lib/Lex/PPDirectives.cpp
  clang/lib/Lex/Preprocessor.cpp
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTWriter.cpp

Index: clang/lib/Serialization/ASTWriter.cpp
===
--- clang/lib/Serialization/ASTWriter.cpp
+++ clang/lib/Serialization/ASTWriter.cpp
@@ -870,6 +870,7 @@
   RECORD(PP_MACRO_OBJECT_LIKE);
   RECORD(PP_MODULE_MACRO);
   RECORD(PP_TOKEN);
+  RECORD(PP_INCLUDED_FILES);
 
   // Submodule Block.
   BLOCK(SUBMODULE_BLOCK);
@@ -1765,7 +1766,7 @@
 std::pair
 EmitKeyDataLength(raw_ostream& Out, key_type_ref key, data_type_ref Data) {
   unsigned KeyLen = key.Filename.size() + 1 + 8 + 8;
-  unsigned DataLen = 1 + 2 + 4 + 4;
+  unsigned DataLen = 1 + 4 + 4;
   for (auto ModInfo : Data.KnownHeaders)
 if (Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule()))
   DataLen += 4;
@@ -1797,7 +1798,6 @@
   | (Data.HFI.DirInfo << 1)
   | Data.HFI.IndexHeaderMapHeader;
   LE.write(Flags);
-  LE.write(Data.HFI.NumIncludes);
 
   if (!Data.HFI.ControllingMacro)
 LE.write(Data.HFI.ControllingMacroID);
@@ -2246,6 +2246,25 @@
   return false;
 }
 
+void ASTWriter::writeIncludedFiles(raw_ostream &Out, const Preprocessor &PP) {
+  using namespace llvm::support;
+
+  std::vector IncludedInputFiles;
+  for (const auto &File : PP.getIncludedFiles()) {
+auto InputFileIt = InputFileIDs.find(File);
+if (InputFileIt == InputFileIDs.end())
+  continue;
+auto InputFileID = InputFileIt->second;
+if (IncludedInputFiles.size() <= InputFileID)
+  IncludedInputFiles.resize(InputFileID + 1);
+IncludedInputFiles[InputFileIt->second] = true;
+  }
+
+  endian::Writer LE(Out, little);
+  LE.write(IncludedInputFiles.size());
+  Out << bytes(IncludedInputFiles);
+}
+
 /// Writes the block containing the serialized form of the
 /// preprocessor.
 void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
@@ -2454,6 +2473,20 @@
MacroOffsetsBase - ASTBlockStartOffset};
 Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record, bytes(MacroOffsets));
   }
+
+  {
+auto Abbrev = std::make_shared();
+Abbrev->Add(BitCodeAbbrevOp(PP_INCLUDED_FILES));
+Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
+unsigned IncludedFilesAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
+
+SmallString<2048> Buffer;
+raw_svector_ostream Out(Buffer);
+writeIncludedFiles(Out, PP);
+RecordData::value_type Record[] = {PP_INCLUDED_FILES};
+Stream.EmitRecordWithBlob(IncludedFilesAbbrev, Record, Buffer.data(),
+  Buffer.size());
+  }
 }
 
 void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec,
Index: clang/lib/Serialization/ASTReader.cpp
===
--- clang/lib/Serialization/ASTReader.cpp
+++ clang/lib/Serialization/ASTReader.cpp
@@ -1888,10 +1888,6 @@
   HFI.isPragmaOnce |= (Flags >> 4) & 0x01;
   HFI.DirInfo = (Flags >> 1) & 0x07;
   HFI.IndexHeaderMapHeader = Flags & 0x01;
-  // FIXME: Find a better way to handle this. Maybe just store a
-  // "has been included" flag?
-  HFI.NumIncludes = std::max(endian::readNext(d),
- HFI.NumIncludes);
   HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
   M, endian::readNext(d));
   if (unsigned FrameworkOffset =
@@ -2963,6 +2959,22 @@
   }
 }
 
+void ASTReader::readIncludedFiles(ModuleFile &F, StringRef Blob,
+  Preprocessor &PP) {
+  using namespace llvm::support;
+
+  const unsigned char *D = (const unsigned char *)Blob.data();
+  unsigned FileCount = endian::readNext(D);
+
+  for (unsigned I = 0; I < FileCount; ++D)
+for (unsigned Bit = 0; Bit < 8 && I < FileCount; ++Bit, ++I)
+  if (*D & (1 << Bit)) {
+auto InputFileInfo = readInputFileInfo(F, I);
+if (auto File = PP.getFileManager().getFile(InputFileInfo.Filename))
+  PP.getIncludedFiles().insert(*File);
+  }
+}
+
 llvm::Error ASTReader::ReadASTBlock(ModuleFile &F,
 unsigned ClientLoadCapabilities) {
   BitstreamCursor &Stream = F.Stream;
@@ -3701,6 +3713,10 @@
   break;
 }
 
+case PP_INCLUDED_FILES:
+  readIncludedFiles(F, Blob, PP);
+  break;
+
 case LATE_PARSED_TEMPLATE:
   Late

[PATCH] D114095: [clang][lex] Include tracking: simplify and move to preprocessor

2021-11-19 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 marked an inline comment as done.
jansvoboda11 added inline comments.



Comment at: clang/lib/Lex/Preprocessor.cpp:552
+if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID)) {
+  HeaderInfo.getFileInfo(FE);
+  markIncluded(FE);

vsapsai wrote:
> Why do you need to `getFileInfo` but don't use it? I have no objections but 
> it looks like it deserves a comment because it's not obvious.
Without the call, I'm hitting some assertions when running C++20 modules tests:

```
Assertion failed: (CurDiagID == std::numeric_limits::max() && 
"Multiple diagnostics in flight at once!"), function Report, file Diagnostic.h, 
line 1526.
```

```
fatal error: error in backend: -verify directives found after rather than 
during normal parsing of 
/clang/test/CXX/modules-ts/basic/basic.def.odr/p6/global-vs-module.cpp
```

Might need to investigate more to be able to write up a reasonable comment here.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114095

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


[PATCH] D112915: [clang][modules] Track included files per submodule

2021-11-19 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 updated this revision to Diff 388409.
jansvoboda11 added a comment.

Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112915

Files:
  clang/include/clang/Lex/ExternalPreprocessorSource.h
  clang/include/clang/Lex/Preprocessor.h
  clang/include/clang/Serialization/ASTBitCodes.h
  clang/include/clang/Serialization/ASTReader.h
  clang/include/clang/Serialization/ASTWriter.h
  clang/include/clang/Serialization/ModuleFile.h
  clang/lib/Basic/Module.cpp
  clang/lib/Lex/PPLexerChange.cpp
  clang/lib/Lex/Preprocessor.cpp
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/test/Modules/import-submodule-visibility.c

Index: clang/test/Modules/import-submodule-visibility.c
===
--- /dev/null
+++ clang/test/Modules/import-submodule-visibility.c
@@ -0,0 +1,99 @@
+// This test checks that imports of headers that appeared in a different submodule than
+// what is imported by the current TU don't affect the compilation.
+
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+
+//--- A.framework/Headers/A.h
+#include "Textual.h"
+//--- A.framework/Modules/module.modulemap
+framework module A { header "A.h" }
+
+//--- B.framework/Headers/B1.h
+#include "Textual.h"
+//--- B.framework/Headers/B2.h
+//--- B.framework/Modules/module.modulemap
+framework module B {
+  module B1 { header "B1.h" }
+  module B2 { header "B2.h" }
+}
+
+//--- C/C.h
+#include "Textual.h"
+//--- C/module.modulemap
+module C { header "C.h" }
+
+//--- D/D1.h
+#include "Textual.h"
+//--- D/D2.h
+//--- D/module.modulemap
+module D {
+  module D1 { header "D1.h" }
+  module D2 { header "D2.h" }
+}
+
+//--- E/E1.h
+#include "E2.h"
+//--- E/E2.h
+#include "Textual.h"
+//--- E/module.modulemap
+module E {
+  module E1 { header "E1.h" }
+  module E2 { header "E2.h" }
+}
+
+//--- Textual.h
+#define MACRO_TEXTUAL 1
+
+//--- test.c
+
+#ifdef A
+//
+#endif
+
+#ifdef B
+#import 
+#endif
+
+#ifdef C
+//
+#endif
+
+#ifdef D
+#import "D/D2.h"
+#endif
+
+#ifdef E
+#import "E/E1.h"
+#endif
+
+#import "Textual.h"
+
+static int x = MACRO_TEXTUAL;
+
+// Specifying the PCM file on the command line (without actually importing "A") should not
+// prevent "Textual.h" to be included in the TU.
+//
+// RUN: %clang_cc1 -fmodules -I %t -emit-module %t/A.framework/Modules/module.modulemap -fmodule-name=A -o %t/A.pcm
+// RUN: %clang_cc1 -fmodules -I %t -fsyntax-only %t/test.c -DA -fmodule-file=%t/A.pcm
+
+// Specifying the PCM file on the command line and importing "B2" in the source does not
+// prevent "Textual.h" to be included in the TU.
+//
+// RUN: %clang_cc1 -fmodules -I %t -emit-module %t/B.framework/Modules/module.modulemap -fmodule-name=B -o %t/B.pcm
+// RUN: %clang_cc1 -fmodules -I %t -fsyntax-only %t/test.c -DB -iframework %t -fmodule-file=%t/B.pcm
+
+// Module-only version of the test with framework A.
+//
+// RUN: %clang_cc1 -fmodules -I %t -emit-module %t/C/module.modulemap -fmodule-name=C -o %t/C.pcm
+// RUN: %clang_cc1 -fmodules -I %t -fsyntax-only %t/test.c -DC -fmodule-file=%t/C.pcm
+
+// Module-only version of the test with framework B.
+//
+// RUN: %clang_cc1 -fmodules -I %t -emit-module %t/D/module.modulemap -fmodule-name=D -o %t/D.pcm
+// RUN: %clang_cc1 -fmodules -I %t -fsyntax-only %t/test.c -DD -fmodule-file=%t/D.pcm
+
+// Transitively imported, but not exported.
+//
+// RUN: %clang_cc1 -fmodules -I %t -emit-module %t/E/module.modulemap -fmodule-name=E -o %t/E.pcm
+// RUN: %clang_cc1 -fmodules -I %t -fsyntax-only %t/test.c -DE -fmodule-file=%t/E.pcm
Index: clang/lib/Serialization/ASTWriter.cpp
===
--- clang/lib/Serialization/ASTWriter.cpp
+++ clang/lib/Serialization/ASTWriter.cpp
@@ -2246,11 +2246,12 @@
   return false;
 }
 
-void ASTWriter::writeIncludedFiles(raw_ostream &Out, const Preprocessor &PP) {
+void ASTWriter::writeIncludedFiles(
+raw_ostream &Out, const Preprocessor::IncludedFilesSet &Files) {
   using namespace llvm::support;
 
   std::vector IncludedInputFiles;
-  for (const auto &File : PP.getIncludedFiles()) {
+  for (const auto &File : Files) {
 auto InputFileIt = InputFileIDs.find(File);
 if (InputFileIt == InputFileIDs.end())
   continue;
@@ -2474,15 +2475,15 @@
 Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record, bytes(MacroOffsets));
   }
 
-  {
-auto Abbrev = std::make_shared();
+  if (const auto *Includes = PP.getNullSubmoduleIncludes()) {
+Abbrev = std::make_shared();
 Abbrev->Add(BitCodeAbbrevOp(PP_INCLUDED_FILES));
 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
 unsigned IncludedFilesAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
 
 SmallString<2048> Buffer;
 raw_svector_ostream Out(Buffer);
-writeIncludedFiles(Out, PP);
+writeIncludedFiles(Out, *Includes);
 RecordData::value_type Record[] = {PP_INCLUDED_FILES}

[PATCH] D114142: [clang-format] [PR52527] can join * with /* to form an outside of comment error C4138

2021-11-19 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

> I only now this from the tests with `-debug`. Is there a way to get "normal" 
> clang-format to print these? Or did you write a test for that to print the 
> information?

I just use the --debug option to clang-format.exe?

I develop on windows, using Visual Studio 2019 (Command Shell)  - (with cygwin 
bash) and build with ninja (so much faster than anything else)

I build Debug  (its possible --debug is only available on Debug builds)

  export CC=cl.exe
  export CXX=cl.exe
  c:/Program\ Files/CMake/bin/cmake.exe ../llvm-project/llvm -G "Ninja" \
  -DLLVM_BUILD_TESTS=ON \
  -DCMAKE_BUILD_TYPE=Debug \
  -DCMAKE_EXPORT_COMPILE_COMMANDS=ON \
  -DLLVM_ENABLE_PROJECTS="clang;clang-tools-extra"

Then just run with --debug

  $ clang-format --debug test1.cpp
  Args: C:\llvm\build_ninja\bin\clang-format.exe --debug test
  1.cpp
  Trying C:\clang-format-examples\comment\.clang-format...
  Using configuration file C:\clang-format-examples\comment\.c
  lang-format
  File encoding: UTF8
  Language: C++
  
  Line(0, FSC=0): comment[T=93, OC=0]
  Line(0, FSC=0): eof[T=93, OC=119]




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114142

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


[PATCH] D114173: [clang][modules] Apply local submodule visibility to includes

2021-11-19 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 updated this revision to Diff 388410.
jansvoboda11 added a comment.

Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114173

Files:
  clang/include/clang/Lex/Preprocessor.h
  clang/lib/Lex/Preprocessor.cpp
  clang/test/Modules/import-textual-noguard.mm


Index: clang/test/Modules/import-textual-noguard.mm
===
--- clang/test/Modules/import-textual-noguard.mm
+++ clang/test/Modules/import-textual-noguard.mm
@@ -1,7 +1,9 @@
 // RUN: rm -rf %t
 // RUN: %clang_cc1 -fsyntax-only -std=c++11 -fmodules -fimplicit-module-maps 
-I%S/Inputs/import-textual/M2 -fmodules-cache-path=%t -x objective-c++ 
-fmodules-local-submodule-visibility %s -verify
 
-#include "A/A.h" // expected-error {{could not build module 'M'}}
+// expected-no-diagnostics
+
+#include "A/A.h"
 #include "B/B.h"
 
 typedef aint xxx;
Index: clang/lib/Lex/Preprocessor.cpp
===
--- clang/lib/Lex/Preprocessor.cpp
+++ clang/lib/Lex/Preprocessor.cpp
@@ -1482,16 +1482,16 @@
 CurrentSubmodule = BuildingSubmoduleStack.back().M;
   IncludedFilesPerSubmodule[CurrentSubmodule].insert(File);
 
-  return IncludedFiles.insert(File).second;
+  return CurSubmoduleState->IncludedFiles.insert(File).second;
 }
 
 void Preprocessor::markTransitivelyIncluded(const FileEntry *File) {
-  IncludedFiles.insert(File);
+  CurSubmoduleState->IncludedFiles.insert(File);
 }
 
 /// Return true if this header has already been included.
 bool Preprocessor::alreadyIncluded(const FileEntry *File) const {
-  return IncludedFiles.count(File);
+  return CurSubmoduleState->IncludedFiles.count(File);
 }
 
 const Preprocessor::IncludedFilesSet *
Index: clang/include/clang/Lex/Preprocessor.h
===
--- clang/include/clang/Lex/Preprocessor.h
+++ clang/include/clang/Lex/Preprocessor.h
@@ -752,6 +752,9 @@
 /// The macros for the submodule.
 MacroMap Macros;
 
+/// The set of files that have been included in the submodule.
+IncludedFilesSet IncludedFiles;
+
 /// The set of modules that are visible within the submodule.
 VisibleModuleSet VisibleModules;
 
@@ -771,10 +774,6 @@
   /// Files included outside of any module (e.g. in PCH) have nullptr key.
   llvm::DenseMap IncludedFilesPerSubmodule;
 
-  /// The global set of files that have been included.
-  // TODO: Move this into SubmoduleState.
-  IncludedFilesSet IncludedFiles;
-
   /// The set of known macros exported from modules.
   llvm::FoldingSet ModuleMacros;
 


Index: clang/test/Modules/import-textual-noguard.mm
===
--- clang/test/Modules/import-textual-noguard.mm
+++ clang/test/Modules/import-textual-noguard.mm
@@ -1,7 +1,9 @@
 // RUN: rm -rf %t
 // RUN: %clang_cc1 -fsyntax-only -std=c++11 -fmodules -fimplicit-module-maps -I%S/Inputs/import-textual/M2 -fmodules-cache-path=%t -x objective-c++ -fmodules-local-submodule-visibility %s -verify
 
-#include "A/A.h" // expected-error {{could not build module 'M'}}
+// expected-no-diagnostics
+
+#include "A/A.h"
 #include "B/B.h"
 
 typedef aint xxx;
Index: clang/lib/Lex/Preprocessor.cpp
===
--- clang/lib/Lex/Preprocessor.cpp
+++ clang/lib/Lex/Preprocessor.cpp
@@ -1482,16 +1482,16 @@
 CurrentSubmodule = BuildingSubmoduleStack.back().M;
   IncludedFilesPerSubmodule[CurrentSubmodule].insert(File);
 
-  return IncludedFiles.insert(File).second;
+  return CurSubmoduleState->IncludedFiles.insert(File).second;
 }
 
 void Preprocessor::markTransitivelyIncluded(const FileEntry *File) {
-  IncludedFiles.insert(File);
+  CurSubmoduleState->IncludedFiles.insert(File);
 }
 
 /// Return true if this header has already been included.
 bool Preprocessor::alreadyIncluded(const FileEntry *File) const {
-  return IncludedFiles.count(File);
+  return CurSubmoduleState->IncludedFiles.count(File);
 }
 
 const Preprocessor::IncludedFilesSet *
Index: clang/include/clang/Lex/Preprocessor.h
===
--- clang/include/clang/Lex/Preprocessor.h
+++ clang/include/clang/Lex/Preprocessor.h
@@ -752,6 +752,9 @@
 /// The macros for the submodule.
 MacroMap Macros;
 
+/// The set of files that have been included in the submodule.
+IncludedFilesSet IncludedFiles;
+
 /// The set of modules that are visible within the submodule.
 VisibleModuleSet VisibleModules;
 
@@ -771,10 +774,6 @@
   /// Files included outside of any module (e.g. in PCH) have nullptr key.
   llvm::DenseMap IncludedFilesPerSubmodule;
 
-  /// The global set of files that have been included.
-  // TODO: Move this into SubmoduleState.
-  IncludedFilesSet IncludedFiles;
-
   /// The set of known macros exported from modules.
   llvm::Folding

[PATCH] D113246: [clang][tests] Fix expected output of plugin-attribute test

2021-11-19 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder abandoned this revision.
tbaeder added a comment.

Already fixed by 50082e1882ae7fe101e563c5e18a27e0804d517b 



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113246

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


[PATCH] D114162: [X86][clang] Enable floating-point type for -mno-x87 option on 32-bits

2021-11-19 Thread Andrew Savonichev via Phabricator via cfe-commits
asavonic added inline comments.



Comment at: clang/lib/Basic/Targets/X86.cpp:385
 
-  if (!HasX87) {
-if (LongDoubleFormat == &llvm::APFloat::x87DoubleExtended())
-  HasLongDouble = false;
-if (getTriple().getArch() == llvm::Triple::x86)
-  HasFPReturn = false;
-  }
+  if (!HasX87 && getTriple().getArch() == llvm::Triple::x86_64 &&
+  LongDoubleFormat == &llvm::APFloat::x87DoubleExtended())

I see that D112143 changed the ABI so that FP return values do not use x87 
registers on i386. Therefore HasFPReturn flag can be removed.

However, operations with long double (x87 80-bit) should still be unsupported 
on both targets, because IIRC there is no SSE equivalent for them. GCC compiles 
them as soft-fp when -mno-x87 is set, but I haven't found 80-bit soft-fp 
implementation in LLVM.
```
long double baz(long double a, long double b) {
return a + b;
}
```

```
baz:
   [...]
   call  __addxf3
```
For some reason GCC only does this for for i386 target, for x86_64 it just 
emits the diagnostic about disabled x87.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114162

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


[clang-tools-extra] 85e03cb - [clang-tidy] fix debug-only test failure

2021-11-19 Thread Kirill Bobyrev via cfe-commits

Author: Matt Beardsley
Date: 2021-11-19T10:19:07+01:00
New Revision: 85e03cb7ebac50a13a9a9ac92a0b184a3bba9be1

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

LOG: [clang-tidy] fix debug-only test failure

The clang-tidy/infrastructure/pr37091.cpp test inherits the top-level 
.clang-tidy configuration because it doesn't specify its own checks. It'd be a 
more stable test if it operates independently of the top-level .clang-tidy 
settings.

I've made the clang-tidy/infrastructure/pr37091.cpp test independent of the 
top-level .clang-tidy (picked an arbitrary check that I saw another 
clang-tidy/infrastructure test was also using: 
clang-tidy/infrastructure/temporaries.cpp)

Reviewed By: kbobyrev

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

Added: 


Modified: 
clang-tools-extra/test/clang-tidy/infrastructure/pr37091.cpp

Removed: 




diff  --git a/clang-tools-extra/test/clang-tidy/infrastructure/pr37091.cpp 
b/clang-tools-extra/test/clang-tidy/infrastructure/pr37091.cpp
index e56115a5fe8ec..6772e9d29f34d 100644
--- a/clang-tools-extra/test/clang-tidy/infrastructure/pr37091.cpp
+++ b/clang-tools-extra/test/clang-tidy/infrastructure/pr37091.cpp
@@ -6,5 +6,5 @@
 //
 // Verify that no temporary files are left behind by the clang-tidy invocation.
 
-// RUN: env TMPDIR=%t TEMP=%t TMP=%t clang-tidy %s -- --target=mips64
+// RUN: env TMPDIR=%t TEMP=%t TMP=%t clang-tidy 
-checks='-*,clang-analyzer-core.NullDereference' %s -- --target=mips64
 // RUN: rmdir %t



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


[PATCH] D114034: [clang-tidy] fix debug-only test failure

2021-11-19 Thread Kirill Bobyrev via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG85e03cb7ebac: [clang-tidy] fix debug-only test failure 
(authored by mattbeardsley, committed by kbobyrev).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114034

Files:
  clang-tools-extra/test/clang-tidy/infrastructure/pr37091.cpp


Index: clang-tools-extra/test/clang-tidy/infrastructure/pr37091.cpp
===
--- clang-tools-extra/test/clang-tidy/infrastructure/pr37091.cpp
+++ clang-tools-extra/test/clang-tidy/infrastructure/pr37091.cpp
@@ -6,5 +6,5 @@
 //
 // Verify that no temporary files are left behind by the clang-tidy invocation.
 
-// RUN: env TMPDIR=%t TEMP=%t TMP=%t clang-tidy %s -- --target=mips64
+// RUN: env TMPDIR=%t TEMP=%t TMP=%t clang-tidy 
-checks='-*,clang-analyzer-core.NullDereference' %s -- --target=mips64
 // RUN: rmdir %t


Index: clang-tools-extra/test/clang-tidy/infrastructure/pr37091.cpp
===
--- clang-tools-extra/test/clang-tidy/infrastructure/pr37091.cpp
+++ clang-tools-extra/test/clang-tidy/infrastructure/pr37091.cpp
@@ -6,5 +6,5 @@
 //
 // Verify that no temporary files are left behind by the clang-tidy invocation.
 
-// RUN: env TMPDIR=%t TEMP=%t TMP=%t clang-tidy %s -- --target=mips64
+// RUN: env TMPDIR=%t TEMP=%t TMP=%t clang-tidy -checks='-*,clang-analyzer-core.NullDereference' %s -- --target=mips64
 // RUN: rmdir %t
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D114034: [clang-tidy] fix debug-only test failure

2021-11-19 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev added a comment.

In D114034#3141446 , @mattbeardsley 
wrote:

> @dstenb Thanks for the confirmation!
>
> @kbobyrev Sorry about my mixup! Would you be able to help me commit this?

Done! Thank you for the patch!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114034

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


[clang-tools-extra] 6259016 - [clang-tidy] Fix false positive in readability-identifier-naming check involving override attribute

2021-11-19 Thread Salman Javed via cfe-commits

Author: Fabian Wolff
Date: 2021-11-19T22:31:11+13:00
New Revision: 6259016361345e09f0607ef4e037e00bcbe4bd40

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

LOG: [clang-tidy] Fix false positive in readability-identifier-naming check 
involving override attribute

Overriding methods should not get a readability-identifier-naming
warning because the issue can only be fixed in the base class; but the
current check for whether a method is overriding does not take the
override attribute into account.

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

Added: 


Modified: 
clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
index d275b475f97c0..cfbe79c525942 100644
--- a/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
@@ -1257,7 +1257,7 @@ StyleKind IdentifierNamingCheck::findStyleKind(
 
   if (const auto *Decl = dyn_cast(D)) {
 if (Decl->isMain() || !Decl->isUserProvided() ||
-Decl->size_overridden_methods() > 0)
+Decl->size_overridden_methods() > 0 || Decl->hasAttr())
   return SK_Invalid;
 
 // If this method has the same name as any base method, this is likely

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
index 3622fe574a72b..01bcb34eadc0d 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
@@ -285,6 +285,10 @@ class AOverridden {
   virtual void BadBaseMethod() = 0;
   // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: invalid case style for virtual 
method 'BadBaseMethod'
   // CHECK-FIXES: {{^}}  virtual void v_Bad_Base_Method() = 0;
+
+  virtual void BadBaseMethodNoAttr() = 0;
+  // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: invalid case style for virtual 
method 'BadBaseMethodNoAttr'
+  // CHECK-FIXES: {{^}}  virtual void v_Bad_Base_Method_No_Attr() = 0;
 };
 
 class COverriding : public AOverridden {
@@ -293,6 +297,9 @@ class COverriding : public AOverridden {
   void BadBaseMethod() override {}
   // CHECK-FIXES: {{^}}  void v_Bad_Base_Method() override {}
 
+  void BadBaseMethodNoAttr() /* override */ {}
+  // CHECK-FIXES: {{^}}  void v_Bad_Base_Method_No_Attr() /* override */ {}
+
   void foo() {
 BadBaseMethod();
 // CHECK-FIXES: {{^}}v_Bad_Base_Method();
@@ -302,12 +309,79 @@ class COverriding : public AOverridden {
 // CHECK-FIXES: {{^}}AOverridden::v_Bad_Base_Method();
 COverriding::BadBaseMethod();
 // CHECK-FIXES: {{^}}COverriding::v_Bad_Base_Method();
+
+BadBaseMethodNoAttr();
+// CHECK-FIXES: {{^}}v_Bad_Base_Method_No_Attr();
+this->BadBaseMethodNoAttr();
+// CHECK-FIXES: {{^}}this->v_Bad_Base_Method_No_Attr();
+AOverridden::BadBaseMethodNoAttr();
+// CHECK-FIXES: {{^}}AOverridden::v_Bad_Base_Method_No_Attr();
+COverriding::BadBaseMethodNoAttr();
+// CHECK-FIXES: {{^}}COverriding::v_Bad_Base_Method_No_Attr();
   }
 };
 
-void VirtualCall(AOverridden &a_vItem) {
+// Same test as above, now with a dependent base class.
+template
+class ATOverridden {
+public:
+  virtual void BadBaseMethod() = 0;
+  // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: invalid case style for virtual 
method 'BadBaseMethod'
+  // CHECK-FIXES: {{^}}  virtual void v_Bad_Base_Method() = 0;
+
+  virtual void BadBaseMethodNoAttr() = 0;
+  // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: invalid case style for virtual 
method 'BadBaseMethodNoAttr'
+  // CHECK-FIXES: {{^}}  virtual void v_Bad_Base_Method_No_Attr() = 0;
+};
+
+template
+class CTOverriding : public ATOverridden {
+  // Overriding a badly-named base isn't a new violation.
+  // FIXME: The fixes from the base class should be propagated to the derived 
class here
+  //(note that there could be specializations of the template base 
class, though)
+  void BadBaseMethod() override {}
+
+  // Without the "override" attribute, and due to the dependent base class, it 
is not
+  // known whether this method overrides anything, so we get the warning here.
+  virtual void BadBaseMethodNoAttr() {};
+  // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: invalid case style for virtual 
method 'BadBaseMethodNoAttr'
+  // CHECK-FIXES: {{^}}  virtual void v_Bad_Base_Method_No_Attr() {};
+};
+
+template
+void VirtualCall(AOverridden &a_vItem, ATOverridden 

[PATCH] D113830: [clang-tidy] Fix false positive in `readability-identifier-naming` check involving `override` attribute

2021-11-19 Thread Salman Javed via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG625901636134: [clang-tidy] Fix false positive in 
readability-identifier-naming check… (authored by fwolff, committed by 
salman-javed-nz).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113830

Files:
  clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
  clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
@@ -285,6 +285,10 @@
   virtual void BadBaseMethod() = 0;
   // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: invalid case style for virtual method 'BadBaseMethod'
   // CHECK-FIXES: {{^}}  virtual void v_Bad_Base_Method() = 0;
+
+  virtual void BadBaseMethodNoAttr() = 0;
+  // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: invalid case style for virtual method 'BadBaseMethodNoAttr'
+  // CHECK-FIXES: {{^}}  virtual void v_Bad_Base_Method_No_Attr() = 0;
 };
 
 class COverriding : public AOverridden {
@@ -293,6 +297,9 @@
   void BadBaseMethod() override {}
   // CHECK-FIXES: {{^}}  void v_Bad_Base_Method() override {}
 
+  void BadBaseMethodNoAttr() /* override */ {}
+  // CHECK-FIXES: {{^}}  void v_Bad_Base_Method_No_Attr() /* override */ {}
+
   void foo() {
 BadBaseMethod();
 // CHECK-FIXES: {{^}}v_Bad_Base_Method();
@@ -302,12 +309,79 @@
 // CHECK-FIXES: {{^}}AOverridden::v_Bad_Base_Method();
 COverriding::BadBaseMethod();
 // CHECK-FIXES: {{^}}COverriding::v_Bad_Base_Method();
+
+BadBaseMethodNoAttr();
+// CHECK-FIXES: {{^}}v_Bad_Base_Method_No_Attr();
+this->BadBaseMethodNoAttr();
+// CHECK-FIXES: {{^}}this->v_Bad_Base_Method_No_Attr();
+AOverridden::BadBaseMethodNoAttr();
+// CHECK-FIXES: {{^}}AOverridden::v_Bad_Base_Method_No_Attr();
+COverriding::BadBaseMethodNoAttr();
+// CHECK-FIXES: {{^}}COverriding::v_Bad_Base_Method_No_Attr();
   }
 };
 
-void VirtualCall(AOverridden &a_vItem) {
+// Same test as above, now with a dependent base class.
+template
+class ATOverridden {
+public:
+  virtual void BadBaseMethod() = 0;
+  // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: invalid case style for virtual method 'BadBaseMethod'
+  // CHECK-FIXES: {{^}}  virtual void v_Bad_Base_Method() = 0;
+
+  virtual void BadBaseMethodNoAttr() = 0;
+  // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: invalid case style for virtual method 'BadBaseMethodNoAttr'
+  // CHECK-FIXES: {{^}}  virtual void v_Bad_Base_Method_No_Attr() = 0;
+};
+
+template
+class CTOverriding : public ATOverridden {
+  // Overriding a badly-named base isn't a new violation.
+  // FIXME: The fixes from the base class should be propagated to the derived class here
+  //(note that there could be specializations of the template base class, though)
+  void BadBaseMethod() override {}
+
+  // Without the "override" attribute, and due to the dependent base class, it is not
+  // known whether this method overrides anything, so we get the warning here.
+  virtual void BadBaseMethodNoAttr() {};
+  // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: invalid case style for virtual method 'BadBaseMethodNoAttr'
+  // CHECK-FIXES: {{^}}  virtual void v_Bad_Base_Method_No_Attr() {};
+};
+
+template
+void VirtualCall(AOverridden &a_vItem, ATOverridden &a_vTitem) {
+  a_vItem.BadBaseMethod();
+  // CHECK-FIXES: {{^}}  a_vItem.v_Bad_Base_Method();
+
+  // FIXME: The fixes from ATOverridden should be propagated to the following call
+  a_vTitem.BadBaseMethod();
+}
+
+// Same test as above, now with a dependent base class that is instantiated below.
+template
+class ATIOverridden {
+public:
+  virtual void BadBaseMethod() = 0;
+  // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: invalid case style for virtual method 'BadBaseMethod'
+  // CHECK-FIXES: {{^}}  virtual void v_Bad_Base_Method() = 0;
+};
+
+template
+class CTIOverriding : public ATIOverridden {
+public:
+  // Overriding a badly-named base isn't a new violation.
+  void BadBaseMethod() override {}
+  // CHECK-FIXES: {{^}}  void v_Bad_Base_Method() override {}
+};
+
+template class CTIOverriding;
+
+void VirtualCallI(ATIOverridden& a_vItem, CTIOverriding& a_vCitem) {
   a_vItem.BadBaseMethod();
   // CHECK-FIXES: {{^}}  a_vItem.v_Bad_Base_Method();
+
+  a_vCitem.BadBaseMethod();
+  // CHECK-FIXES: {{^}}  a_vCitem.v_Bad_Base_Method();
 }
 
 template 
Index: clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
===
--- clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
+++ clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck

[PATCH] D114162: [X86][clang] Enable floating-point type for -mno-x87 option on 32-bits

2021-11-19 Thread Phoebe Wang via Phabricator via cfe-commits
pengfei added inline comments.



Comment at: clang/lib/Basic/Targets/X86.cpp:385
 
-  if (!HasX87) {
-if (LongDoubleFormat == &llvm::APFloat::x87DoubleExtended())
-  HasLongDouble = false;
-if (getTriple().getArch() == llvm::Triple::x86)
-  HasFPReturn = false;
-  }
+  if (!HasX87 && getTriple().getArch() == llvm::Triple::x86_64 &&
+  LongDoubleFormat == &llvm::APFloat::x87DoubleExtended())

asavonic wrote:
> I see that D112143 changed the ABI so that FP return values do not use x87 
> registers on i386. Therefore HasFPReturn flag can be removed.
> 
> However, operations with long double (x87 80-bit) should still be unsupported 
> on both targets, because IIRC there is no SSE equivalent for them. GCC 
> compiles them as soft-fp when -mno-x87 is set, but I haven't found 80-bit 
> soft-fp implementation in LLVM.
> ```
> long double baz(long double a, long double b) {
> return a + b;
> }
> ```
> 
> ```
> baz:
>[...]
>call  __addxf3
> ```
> For some reason GCC only does this for for i386 target, for x86_64 it just 
> emits the diagnostic about disabled x87.
Thanks for looking at this patch.
I don't think we need to exclude f80 particularly. IIUC, backend tries all 
possible ways to lower a given operation. Lowering to library is always the 
last choice. So the behavior is not confined to soft-fp.
It's true LLVM has problems with f80 lowering without x87. I commented it in 
D112143 and hope D100091 will fix them. We don't need to bother to change it 
again in future.

> For some reason GCC only does this for for i386 target, for x86_64 it just 
> emits the diagnostic about disabled x87.
I think the root reason is the difference in ABI. 32-bits ABI allows passing 
and returning f80 without x87 registers while 64-bits doesn't. So we have to 
and only need to disable it for x86_64.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114162

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


[PATCH] D113250: [clang][driver] Add -fplugin-arg- to pass arguments to plugins

2021-11-19 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder updated this revision to Diff 388417.

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

https://reviews.llvm.org/D113250

Files:
  clang/docs/ClangPlugins.rst
  clang/docs/ReleaseNotes.rst
  clang/examples/CallSuperAttribute/CallSuperAttrInfo.cpp
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/Driver/plugin-driver-args.cpp
  clang/test/Frontend/plugin-call-super.cpp

Index: clang/test/Frontend/plugin-call-super.cpp
===
--- clang/test/Frontend/plugin-call-super.cpp
+++ clang/test/Frontend/plugin-call-super.cpp
@@ -1,5 +1,5 @@
-// RUN: %clang -fplugin=%llvmshlibdir/CallSuperAttr%pluginext -fsyntax-only -Xclang -verify=callsuper %s
-// RUN: %clang -fplugin=%llvmshlibdir/CallSuperAttr%pluginext -DBAD_CALLSUPER -fsyntax-only -Xclang -verify=badcallsuper %s
+// RUN: %clang_cc1 -load %llvmshlibdir/CallSuperAttr%pluginext -fsyntax-only -verify=callsuper %s
+// RUN: %clang_cc1 -load %llvmshlibdir/CallSuperAttr%pluginext -DBAD_CALLSUPER -fsyntax-only -verify=badcallsuper %s
 // REQUIRES: plugins, examples
 
 // callsuper-no-diagnostics
Index: clang/test/Driver/plugin-driver-args.cpp
===
--- /dev/null
+++ clang/test/Driver/plugin-driver-args.cpp
@@ -0,0 +1,13 @@
+// Test passing args to plugins via the clang driver and -fplugin-arg
+// RUN: %clang -fplugin=%llvmshlibdir/CallSuperAttr%pluginext -fplugin-arg-call_super_plugin-help -fsyntax-only -### %s 2>&1 | FileCheck %s
+
+// CHECK: "-load"
+// CHECK: CallSuperAttr
+// CHECK: "-plugin-arg-call_super_plugin"
+// CHECK: "help"
+
+
+// Check that dashed-args get forwarded like this to the plugin.
+// Dashes cannot be part of the plugin name here
+// RUN: %clang -fplugin=%llvmshlibdir/CallSuperAttr%pluginext -fplugin-arg-call_super_plugin-help-long -fsyntax-only %s 2>&1 -### | FileCheck %s --check-prefix=CHECK-CMD
+// CHECK-CMD: "-plugin-arg-call_super_plugin" "help-long"
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -6660,6 +6660,29 @@
 A->claim();
   }
 
+  // Turn -fplugin-arg-pluginname-key=value into
+  // -plugin-arg-pluginname key=value
+  // GCC has an actual plugin_argument struct with key/value pairs that it
+  // passes to its plugins, but we don't, so just pass it on as-is.
+  //
+  // The syntax for -fplugin-arg- is ambiguous if both plugin name and
+  // argument key are allowed to contain dashes. GCC therefore only
+  // allows dashes in the key. We do the same.
+  for (const Arg *A : Args.filtered(options::OPT_fplugin_arg)) {
+auto ArgValue = StringRef(A->getValue());
+auto FirstDashIndex = ArgValue.find('-');
+
+if (FirstDashIndex == StringRef::npos)
+  continue;
+
+auto Arg = ArgValue.substr(FirstDashIndex + 1);
+auto PluginName = ArgValue.substr(0, FirstDashIndex);
+
+CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-arg-") + PluginName));
+CmdArgs.push_back(Args.MakeArgString(Arg));
+A->claim();
+  }
+
   // Forward -fpass-plugin=name.so to -cc1.
   for (const Arg *A : Args.filtered(options::OPT_fpass_plugin_EQ)) {
 CmdArgs.push_back(
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -2504,6 +2504,9 @@
   NegFlag>;
 def fplugin_EQ : Joined<["-"], "fplugin=">, Group, Flags<[NoXarchOption]>, MetaVarName<"">,
   HelpText<"Load the named plugin (dynamic shared object)">;
+def fplugin_arg : Joined<["-"], "fplugin-arg-">,
+  MetaVarName<"-">,
+  HelpText<"Pass  to plugin ">;
 def fpass_plugin_EQ : Joined<["-"], "fpass-plugin=">,
   Group, Flags<[CC1Option]>, MetaVarName<"">,
   HelpText<"Load pass plugin from a dynamic shared object file (only with new pass manager).">,
Index: clang/examples/CallSuperAttribute/CallSuperAttrInfo.cpp
===
--- clang/examples/CallSuperAttribute/CallSuperAttrInfo.cpp
+++ clang/examples/CallSuperAttribute/CallSuperAttrInfo.cpp
@@ -145,6 +145,11 @@
 
   bool ParseArgs(const CompilerInstance &CI,
  const std::vector &args) override {
+if (!args.empty()) {
+  if (args[0] == "help") {
+llvm::errs() << "Help for the CallSuperAttr plugin goes here\n";
+  }
+}
 return true;
   }
 
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -62,7 +62,8 @@
 New Compiler Flags
 --
 
-- ...
+- Clang plugin arguments can now be passed through the compiler driver via
+  ``-fplugin-arg-pluginname-arg``, similar to GCC's ``-fplugin-arg``.
 
 Deprecated Compiler Flags
 -

[PATCH] D114151: [clang-format] [C++20] [Module] clang-format couldn't recognize partitions

2021-11-19 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay updated this revision to Diff 388419.
MyDeveloperDay added a comment.

Add yet more unit tests and cover those.

Mark one test as TODO as I'm not sure if its allowed syntax


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

https://reviews.llvm.org/D114151

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Format/FormatToken.h
  clang/lib/Format/TokenAnnotator.cpp
  clang/lib/Format/UnwrappedLineParser.cpp
  clang/unittests/Format/FormatTest.cpp

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -22397,6 +22397,66 @@
   EXPECT_EQ(Code, format(Code, Style));
 }
 
+TEST_F(FormatTest, Cpp20ModulesSupport) {
+  FormatStyle Style = getLLVMStyle();
+  Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
+  Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
+
+  verifyFormat("export import foo;", Style);
+  verifyFormat("export import foo:bar;", Style);
+  verifyFormat("export import foo.bar;", Style);
+  verifyFormat("export import foo.bar:baz;", Style);
+  verifyFormat("export import :bar;", Style);
+  verifyFormat("export module foo:bar;", Style);
+  verifyFormat("export module foo;", Style);
+  verifyFormat("export module foo.bar;", Style);
+  verifyFormat("export module foo.bar:baz;", Style);
+  verifyFormat("export import ;", Style);
+
+  verifyFormat("export type_name var;", Style);
+  verifyFormat("template  export using A = B;", Style);
+  verifyFormat("export using A = B;", Style);
+  verifyFormat("export int func() {\n"
+   "  foo();\n"
+   "}",
+   Style);
+  verifyFormat("export struct {\n"
+   "  int foo;\n"
+   "};",
+   Style);
+  verifyFormat("export {\n"
+   "  int foo;\n"
+   "};",
+   Style);
+  verifyFormat("export export char const *hello() { return \"hello\"; }");
+
+  verifyFormat("import bar;", Style);
+  verifyFormat("import foo.bar;", Style);
+  verifyFormat("import foo:bar;", Style);
+  verifyFormat("import :bar;", Style);
+  verifyFormat("import ;", Style);
+  verifyFormat("import \"header\";", Style);
+
+  verifyFormat("module foo;", Style);
+  verifyFormat("module foo:bar;", Style);
+  verifyFormat("module foo.bar;", Style);
+  verifyFormat("module;", Style);
+
+  verifyFormat("export namespace hi {\n"
+   "const char *sayhi();\n"
+   "}",
+   Style);
+
+  verifyFormat("module :private;", Style);
+  verifyFormat("import ;", Style);
+  verifyFormat("import foo...bar;", Style);
+  verifyFormat("import ..;", Style);
+  verifyFormat("module foo:private;", Style);
+
+  // TODO validate this use cases? can we have keywords here?
+  // verifyFormat("module public:while;", Style);
+}
+
 } // namespace
 } // namespace format
 } // namespace clang
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -1250,6 +1250,35 @@
 addUnwrappedLine();
 return;
   }
+  if (Style.isCpp()) {
+nextToken();
+while (FormatTok) {
+  if (FormatTok->is(tok::colon)) {
+FormatTok->setType(TT_ModulePartitionColon);
+  }
+  // Handle import  as we would an include statement
+  if (FormatTok && FormatTok->is(tok::less)) {
+nextToken();
+while (FormatTok) {
+  if (FormatTok->is(tok::semi))
+break;
+  // Mark tokens up to the trailing line comments as implicit string
+  // literals.
+  if (FormatTok->isNot(tok::comment) &&
+  !FormatTok->TokenText.startswith("//"))
+FormatTok->setType(TT_ImplicitStringLiteral);
+  nextToken();
+}
+  }
+  if (FormatTok->is(tok::semi)) {
+nextToken();
+break;
+  }
+  nextToken();
+}
+addUnwrappedLine();
+return;
+  }
 }
 if (Style.isCpp() &&
 FormatTok->isOneOf(Keywords.kw_signals, Keywords.kw_qsignals,
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -902,9 +902,13 @@
   break;
 }
   }
-  if (Contexts.back().ColonIsDictLiteral ||
-  Style.Language == FormatStyle::LK_Proto ||
-  Style.Language == FormatStyle::LK_TextProto) {
+  if (Line.First->isOneOf(Keywords.kw_module, Keywords.kw_import) ||
+  Line.First->startsSequence(tok::kw_export, Keywords.kw_module) ||
+  Line.First->startsSequence(tok::kw_export, Keywords.kw_import)) {
+Tok->setType(TT_ModulePart

[PATCH] D112913: Misleading bidirectional detection

2021-11-19 Thread serge via Phabricator via cfe-commits
serge-sans-paille updated this revision to Diff 388424.
serge-sans-paille added a comment.

Rebase on main branch


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

https://reviews.llvm.org/D112913

Files:
  clang-tools-extra/clang-tidy/misc/CMakeLists.txt
  clang-tools-extra/clang-tidy/misc/MiscTidyModule.cpp
  clang-tools-extra/clang-tidy/misc/MisleadingBidirectional.cpp
  clang-tools-extra/clang-tidy/misc/MisleadingBidirectional.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/docs/clang-tidy/checks/misc-misleading-bidirectional.rst
  clang-tools-extra/test/clang-tidy/checkers/misc-misleading-bidirectional.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/misc-misleading-bidirectional.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/misc-misleading-bidirectional.cpp
@@ -0,0 +1,31 @@
+// RUN: %check_clang_tidy %s misc-misleading-bidirectional %t
+
+void func(void) {
+  int admin = 0;
+  /*‮ }⁦if(admin)⁩ ⁦ begin*/
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: comment contains misleading bidirectional Unicode characters [misc-misleading-bidirectional]
+  const char msg[] = "‮⁦if(admin)⁩ ⁦tes";
+  // CHECK-MESSAGES: :[[@LINE-1]]:22: warning: string literal contains misleading bidirectional Unicode characters [misc-misleading-bidirectional]
+}
+
+void all_fine(void) {
+  char valid[] = "some‮valid‬sequence";
+  /* EOL ends bidi‮ sequence
+   * end it's fine to do so.
+   * EOL ends ⁧isolate too
+   */
+}
+
+int invalid_utf_8(void) {
+  bool isAdmin = false;
+
+  // the comment below contains an invalid utf8 character, but should still be
+  // processed.
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:5: warning: comment contains misleading bidirectional Unicode characters [misc-misleading-bidirectional]
+  /*€‮ } ⁦if (isAdmin)⁩ ⁦ begin admins only */
+  return 1;
+  /* end admins only ‮ { ⁦*/
+  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: comment contains misleading bidirectional Unicode characters [misc-misleading-bidirectional]
+  return 0;
+}
Index: clang-tools-extra/docs/clang-tidy/checks/misc-misleading-bidirectional.rst
===
--- /dev/null
+++ clang-tools-extra/docs/clang-tidy/checks/misc-misleading-bidirectional.rst
@@ -0,0 +1,21 @@
+.. title:: clang-tidy - misc-misleading-bidirectional
+
+misc-misleading-bidirectional
+=
+
+Warn about unterminated bidirectional unicode sequence, detecting potential attack
+as described in the `Trojan Source `_ attack.
+
+Example:
+
+.. code-block:: c++
+
+#include 
+
+int main() {
+bool isAdmin = false;
+/*‮ } ⁦if (isAdmin)⁩ ⁦ begin admins only */
+std::cout << "You are an admin.\n";
+/* end admins only ‮ { ⁦*/
+return 0;
+}
Index: clang-tools-extra/docs/clang-tidy/checks/list.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/list.rst
+++ clang-tools-extra/docs/clang-tidy/checks/list.rst
@@ -212,6 +212,7 @@
`llvmlibc-implementation-in-namespace `_,
`llvmlibc-restrict-system-libc-headers `_, "Yes"
`misc-definitions-in-headers `_, "Yes"
+   `misc-misleading-bidirectional `_,
`misc-misleading-identifier `_,
`misc-misplaced-const `_,
`misc-new-delete-overloads `_,
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -111,6 +111,10 @@
   Reports identifiers whose names are too short. Currently checks local
   variables and function parameters only.
 
+- New :doc:`misc-misleading-bidirectional ` check.
+
+  Inspect string literal and comments for unterminated bidirectional Unicode
+  characters.
 
 New check aliases
 ^
Index: clang-tools-extra/clang-tidy/misc/MisleadingBidirectional.h
===
--- /dev/null
+++ clang-tools-extra/clang-tidy/misc/MisleadingBidirectional.h
@@ -0,0 +1,38 @@
+//===--- MisleadingBidirectionalCheck.h - clang-tidy *- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_MISLEADINGBIDIRECTIONALCHECK_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_MISLEADINGBIDIRECTIONALCHECK_H
+
+#include "../ClangTidyCheck.h"
+
+namespace clang {
+namespace tidy {
+namespace misc {
+
+class MisleadingBidirectionalCheck : public ClangTidyCheck {
+public:
+ 

[PATCH] D112913: Misleading bidirectional detection

2021-11-19 Thread serge via Phabricator via cfe-commits
serge-sans-paille added a comment.

Patch rebased on main, all comments addressed. Looks good?


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

https://reviews.llvm.org/D112913

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


[PATCH] D112913: Misleading bidirectional detection

2021-11-19 Thread serge via Phabricator via cfe-commits
serge-sans-paille updated this revision to Diff 388425.
serge-sans-paille added a comment.

Nits


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

https://reviews.llvm.org/D112913

Files:
  clang-tools-extra/clang-tidy/misc/CMakeLists.txt
  clang-tools-extra/clang-tidy/misc/MiscTidyModule.cpp
  clang-tools-extra/clang-tidy/misc/MisleadingBidirectional.cpp
  clang-tools-extra/clang-tidy/misc/MisleadingBidirectional.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/docs/clang-tidy/checks/misc-misleading-bidirectional.rst
  clang-tools-extra/test/clang-tidy/checkers/misc-misleading-bidirectional.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/misc-misleading-bidirectional.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/misc-misleading-bidirectional.cpp
@@ -0,0 +1,31 @@
+// RUN: %check_clang_tidy %s misc-misleading-bidirectional %t
+
+void func(void) {
+  int admin = 0;
+  /*‮ }⁦if(admin)⁩ ⁦ begin*/
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: comment contains misleading bidirectional Unicode characters [misc-misleading-bidirectional]
+  const char msg[] = "‮⁦if(admin)⁩ ⁦tes";
+  // CHECK-MESSAGES: :[[@LINE-1]]:22: warning: string literal contains misleading bidirectional Unicode characters [misc-misleading-bidirectional]
+}
+
+void all_fine(void) {
+  char valid[] = "some‮valid‬sequence";
+  /* EOL ends bidi‮ sequence
+   * end it's fine to do so.
+   * EOL ends ⁧isolate too
+   */
+}
+
+int invalid_utf_8(void) {
+  bool isAdmin = false;
+
+  // the comment below contains an invalid utf8 character, but should still be
+  // processed.
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:5: warning: comment contains misleading bidirectional Unicode characters [misc-misleading-bidirectional]
+  /*€‮ } ⁦if (isAdmin)⁩ ⁦ begin admins only */
+  return 1;
+  /* end admins only ‮ { ⁦*/
+  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: comment contains misleading bidirectional Unicode characters [misc-misleading-bidirectional]
+  return 0;
+}
Index: clang-tools-extra/docs/clang-tidy/checks/misc-misleading-bidirectional.rst
===
--- /dev/null
+++ clang-tools-extra/docs/clang-tidy/checks/misc-misleading-bidirectional.rst
@@ -0,0 +1,21 @@
+.. title:: clang-tidy - misc-misleading-bidirectional
+
+misc-misleading-bidirectional
+=
+
+Warn about unterminated bidirectional unicode sequence, detecting potential attack
+as described in the `Trojan Source `_ attack.
+
+Example:
+
+.. code-block:: c++
+
+#include 
+
+int main() {
+bool isAdmin = false;
+/*‮ } ⁦if (isAdmin)⁩ ⁦ begin admins only */
+std::cout << "You are an admin.\n";
+/* end admins only ‮ { ⁦*/
+return 0;
+}
Index: clang-tools-extra/docs/clang-tidy/checks/list.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/list.rst
+++ clang-tools-extra/docs/clang-tidy/checks/list.rst
@@ -212,6 +212,7 @@
`llvmlibc-implementation-in-namespace `_,
`llvmlibc-restrict-system-libc-headers `_, "Yes"
`misc-definitions-in-headers `_, "Yes"
+   `misc-misleading-bidirectional `_,
`misc-misleading-identifier `_,
`misc-misplaced-const `_,
`misc-new-delete-overloads `_,
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -111,6 +111,10 @@
   Reports identifiers whose names are too short. Currently checks local
   variables and function parameters only.
 
+- New :doc:`misc-misleading-bidirectional ` check.
+
+  Inspects string literal and comments for unterminated bidirectional Unicode
+  characters.
 
 New check aliases
 ^
Index: clang-tools-extra/clang-tidy/misc/MisleadingBidirectional.h
===
--- /dev/null
+++ clang-tools-extra/clang-tidy/misc/MisleadingBidirectional.h
@@ -0,0 +1,38 @@
+//===--- MisleadingBidirectionalCheck.h - clang-tidy *- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_MISLEADINGBIDIRECTIONALCHECK_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_MISLEADINGBIDIRECTIONALCHECK_H
+
+#include "../ClangTidyCheck.h"
+
+namespace clang {
+namespace tidy {
+namespace misc {
+
+class MisleadingBidirectionalCheck : public ClangTidyCheck {
+public:
+  MisleadingBidir

[PATCH] D114162: [X86][clang] Enable floating-point type for -mno-x87 option on 32-bits

2021-11-19 Thread Andrew Savonichev via Phabricator via cfe-commits
asavonic added inline comments.



Comment at: clang/lib/Basic/Targets/X86.cpp:385
 
-  if (!HasX87) {
-if (LongDoubleFormat == &llvm::APFloat::x87DoubleExtended())
-  HasLongDouble = false;
-if (getTriple().getArch() == llvm::Triple::x86)
-  HasFPReturn = false;
-  }
+  if (!HasX87 && getTriple().getArch() == llvm::Triple::x86_64 &&
+  LongDoubleFormat == &llvm::APFloat::x87DoubleExtended())

pengfei wrote:
> asavonic wrote:
> > I see that D112143 changed the ABI so that FP return values do not use x87 
> > registers on i386. Therefore HasFPReturn flag can be removed.
> > 
> > However, operations with long double (x87 80-bit) should still be 
> > unsupported on both targets, because IIRC there is no SSE equivalent for 
> > them. GCC compiles them as soft-fp when -mno-x87 is set, but I haven't 
> > found 80-bit soft-fp implementation in LLVM.
> > ```
> > long double baz(long double a, long double b) {
> > return a + b;
> > }
> > ```
> > 
> > ```
> > baz:
> >[...]
> >call  __addxf3
> > ```
> > For some reason GCC only does this for for i386 target, for x86_64 it just 
> > emits the diagnostic about disabled x87.
> Thanks for looking at this patch.
> I don't think we need to exclude f80 particularly. IIUC, backend tries all 
> possible ways to lower a given operation. Lowering to library is always the 
> last choice. So the behavior is not confined to soft-fp.
> It's true LLVM has problems with f80 lowering without x87. I commented it in 
> D112143 and hope D100091 will fix them. We don't need to bother to change it 
> again in future.
> 
> > For some reason GCC only does this for for i386 target, for x86_64 it just 
> > emits the diagnostic about disabled x87.
> I think the root reason is the difference in ABI. 32-bits ABI allows passing 
> and returning f80 without x87 registers while 64-bits doesn't. So we have to 
> and only need to disable it for x86_64.
> I don't think we need to exclude f80 particularly. IIUC, backend tries all 
> possible ways to lower a given operation. Lowering to library is always the 
> last choice. So the behavior is not confined to soft-fp.
> It's true LLVM has problems with f80 lowering without x87. I commented it in 
> D112143 and hope D100091 will fix them. We don't need to bother to change it 
> again in future.

Right, but can LLVM lower any x87 80-bit fp operations other than return values?
If it cannot, then I think a source level diagnostic is a good thing to have. 
Otherwise the only handling we have is the codegen crash with "x87 register 
return with x87 disabled" and no source-level context.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114162

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


[PATCH] D114229: [clang][driver] Always add LTO options when using GNU toolchain

2021-11-19 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder created this revision.
tbaeder added reviewers: MaskRay, fhahn, tejohnson.
Herald added subscribers: ormris, steven_wu, hiraditya, inglorion.
tbaeder requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This is what the GCC driver does as well.

This way, ld.bfd can properly handle inputs from a clang LTO build,
without `-flto` being specified at link time explicitly.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D114229

Files:
  clang/lib/Driver/ToolChains/Gnu.cpp
  clang/test/Driver/lto.c


Index: clang/test/Driver/lto.c
===
--- clang/test/Driver/lto.c
+++ clang/test/Driver/lto.c
@@ -104,4 +104,19 @@
 // FLTO-THIN-NOT: "-flto"
 // FLTO-THIN: -flto=thin
 // FLTO-THIN-NOT: "-flto"
-// FLTO-THIN-NOT: -flto=full
\ No newline at end of file
+// FLTO-THIN-NOT: -flto=full
+
+// When ld.bfd is being used and no lto option has been specified, the driver
+// should pass the lto plugin options to the linker anyway, so LTO
+// input files can be linked.
+// RUN: %clang -target x86_64-unknown-linux -fuse-ld=bfd -### %s 2>&1 | \
+// RUN: FileCheck --check-prefix=FLTO-NOT-SPECIFIED-BFD %s
+//
+// FLTO-NOT-SPECIFIED-BFD: "-plugin" "{{.*}}{{[/\\]}}LLVMgold.{{dll|dylib|so}}"
+//
+//
+// But not when LLD is used:
+// RUN: %clang -target x86_64-unknown-linux -fuse-ld=lld -### %s 2>&1 | \
+// RUN: FileCheck --check-prefix=FLTO-NOT-SPECIFIED-LLD %s
+//
+// FLTO-NOT-SPECIFIED-LLD-NOT: "-plugin" 
"{{.*}}{{[/\\]}}LLVMgold.{{dll|dylib|so}}"
Index: clang/lib/Driver/ToolChains/Gnu.cpp
===
--- clang/lib/Driver/ToolChains/Gnu.cpp
+++ clang/lib/Driver/ToolChains/Gnu.cpp
@@ -546,7 +546,14 @@
 
   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
 
-  if (D.isUsingLTO()) {
+  // If no LTO option has been specified, add the LTO options anyway.
+  // This has the upside of making the linking automatically work with
+  // LLVM bitcode files created from an LTO compile. If the input is not
+  // an LTO file, the LTO plugin will not be invoked.
+  // This is the same behavior the GCC driver uses.
+  if ((!Args.hasArg(options::OPT_flto_EQ) &&
+   !Args.hasArg(options::OPT_fno_lto)) ||
+  D.isUsingLTO()) {
 assert(!Inputs.empty() && "Must have at least one input.");
 addLTOOptions(ToolChain, Args, CmdArgs, Output, Inputs[0],
   D.getLTOMode() == LTOK_Thin);


Index: clang/test/Driver/lto.c
===
--- clang/test/Driver/lto.c
+++ clang/test/Driver/lto.c
@@ -104,4 +104,19 @@
 // FLTO-THIN-NOT: "-flto"
 // FLTO-THIN: -flto=thin
 // FLTO-THIN-NOT: "-flto"
-// FLTO-THIN-NOT: -flto=full
\ No newline at end of file
+// FLTO-THIN-NOT: -flto=full
+
+// When ld.bfd is being used and no lto option has been specified, the driver
+// should pass the lto plugin options to the linker anyway, so LTO
+// input files can be linked.
+// RUN: %clang -target x86_64-unknown-linux -fuse-ld=bfd -### %s 2>&1 | \
+// RUN: FileCheck --check-prefix=FLTO-NOT-SPECIFIED-BFD %s
+//
+// FLTO-NOT-SPECIFIED-BFD: "-plugin" "{{.*}}{{[/\\]}}LLVMgold.{{dll|dylib|so}}"
+//
+//
+// But not when LLD is used:
+// RUN: %clang -target x86_64-unknown-linux -fuse-ld=lld -### %s 2>&1 | \
+// RUN: FileCheck --check-prefix=FLTO-NOT-SPECIFIED-LLD %s
+//
+// FLTO-NOT-SPECIFIED-LLD-NOT: "-plugin" "{{.*}}{{[/\\]}}LLVMgold.{{dll|dylib|so}}"
Index: clang/lib/Driver/ToolChains/Gnu.cpp
===
--- clang/lib/Driver/ToolChains/Gnu.cpp
+++ clang/lib/Driver/ToolChains/Gnu.cpp
@@ -546,7 +546,14 @@
 
   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
 
-  if (D.isUsingLTO()) {
+  // If no LTO option has been specified, add the LTO options anyway.
+  // This has the upside of making the linking automatically work with
+  // LLVM bitcode files created from an LTO compile. If the input is not
+  // an LTO file, the LTO plugin will not be invoked.
+  // This is the same behavior the GCC driver uses.
+  if ((!Args.hasArg(options::OPT_flto_EQ) &&
+   !Args.hasArg(options::OPT_fno_lto)) ||
+  D.isUsingLTO()) {
 assert(!Inputs.empty() && "Must have at least one input.");
 addLTOOptions(ToolChain, Args, CmdArgs, Output, Inputs[0],
   D.getLTOMode() == LTOK_Thin);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D114006: [analyzer][NFC] Enable access to CodeGenOptions from analyzer's instances

2021-11-19 Thread Gabor Marton via Phabricator via cfe-commits
martong accepted this revision.
martong added a comment.

LGTM!


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

https://reviews.llvm.org/D114006

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


[PATCH] D113118: [clang][AST] Check context of record in structural equivalence.

2021-11-19 Thread Gabor Marton via Phabricator via cfe-commits
martong accepted this revision.
martong added a comment.
This revision is now accepted and ready to land.

Thanks @balazske for updating the tests, I think this addresses @shafik 's 
questions. LGTM! Ping @shafik


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113118

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


[PATCH] D113558: [clang-tidy] Fix cppcoreguidelines-virtual-base-class-destructor in macros

2021-11-19 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

ping




Comment at: 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-virtual-class-destructor.cpp:288
+protected:
+  virtual CONCAT(~Foo, Bar2()); // no-fixit
+};

whisperity wrote:
> whisperity wrote:
> > It is strange that there is no fix-it here even though the keyword appears 
> > as a single token ...[1]
> Maybe a FIXME could be added for this case, just to register that we indeed 
> realised something is //strange// here, but I'm not convinced neither for nor 
> against. The purpose of the patch is to get rid of the crash, after all.
Definitely deserves a FIXME. Yes.


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

https://reviews.llvm.org/D113558

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


[clang] f3753ad - [ASTImporter][NFC] Dump decl name at assertion violation

2021-11-19 Thread Balazs Benics via cfe-commits

Author: Balazs Benics
Date: 2021-11-19T11:31:01+01:00
New Revision: f3753ad774506804ef5df065b48268712bdaa554

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

LOG: [ASTImporter][NFC] Dump decl name at assertion violation

Sometimes it would be useful to see which Decl kind caused some issue,
along with the name of the concrete instance of the Decl in the source
code.

Reviewed By: martong

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

Added: 


Modified: 
clang/lib/AST/ASTImporterLookupTable.cpp

Removed: 




diff  --git a/clang/lib/AST/ASTImporterLookupTable.cpp 
b/clang/lib/AST/ASTImporterLookupTable.cpp
index bf772c20d32ee..ef42561c6f941 100644
--- a/clang/lib/AST/ASTImporterLookupTable.cpp
+++ b/clang/lib/AST/ASTImporterLookupTable.cpp
@@ -14,6 +14,7 @@
 #include "clang/AST/ASTImporterLookupTable.h"
 #include "clang/AST/Decl.h"
 #include "clang/AST/RecursiveASTVisitor.h"
+#include "llvm/Support/FormatVariadic.h"
 
 namespace clang {
 
@@ -93,10 +94,19 @@ void ASTImporterLookupTable::add(DeclContext *DC, NamedDecl 
*ND) {
 }
 
 void ASTImporterLookupTable::remove(DeclContext *DC, NamedDecl *ND) {
-  DeclList &Decls = LookupTable[DC][ND->getDeclName()];
+  const DeclarationName Name = ND->getDeclName();
+  DeclList &Decls = LookupTable[DC][Name];
   bool EraseResult = Decls.remove(ND);
   (void)EraseResult;
-  assert(EraseResult == true && "Trying to remove not contained Decl");
+#ifndef NDEBUG
+  if (!EraseResult) {
+std::string Message =
+llvm::formatv("Trying to remove not contained Decl '{0}' of type {1}",
+  Name.getAsString(), DC->getDeclKindName())
+.str();
+llvm_unreachable(Message.c_str());
+  }
+#endif
 }
 
 void ASTImporterLookupTable::add(NamedDecl *ND) {



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


[PATCH] D113668: [ASTImporter][NFC] Dump decl name at assertion violation

2021-11-19 Thread Balázs Benics via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGf3753ad77450: [ASTImporter][NFC] Dump decl name at assertion 
violation (authored by steakhal).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113668

Files:
  clang/lib/AST/ASTImporterLookupTable.cpp


Index: clang/lib/AST/ASTImporterLookupTable.cpp
===
--- clang/lib/AST/ASTImporterLookupTable.cpp
+++ clang/lib/AST/ASTImporterLookupTable.cpp
@@ -14,6 +14,7 @@
 #include "clang/AST/ASTImporterLookupTable.h"
 #include "clang/AST/Decl.h"
 #include "clang/AST/RecursiveASTVisitor.h"
+#include "llvm/Support/FormatVariadic.h"
 
 namespace clang {
 
@@ -93,10 +94,19 @@
 }
 
 void ASTImporterLookupTable::remove(DeclContext *DC, NamedDecl *ND) {
-  DeclList &Decls = LookupTable[DC][ND->getDeclName()];
+  const DeclarationName Name = ND->getDeclName();
+  DeclList &Decls = LookupTable[DC][Name];
   bool EraseResult = Decls.remove(ND);
   (void)EraseResult;
-  assert(EraseResult == true && "Trying to remove not contained Decl");
+#ifndef NDEBUG
+  if (!EraseResult) {
+std::string Message =
+llvm::formatv("Trying to remove not contained Decl '{0}' of type {1}",
+  Name.getAsString(), DC->getDeclKindName())
+.str();
+llvm_unreachable(Message.c_str());
+  }
+#endif
 }
 
 void ASTImporterLookupTable::add(NamedDecl *ND) {


Index: clang/lib/AST/ASTImporterLookupTable.cpp
===
--- clang/lib/AST/ASTImporterLookupTable.cpp
+++ clang/lib/AST/ASTImporterLookupTable.cpp
@@ -14,6 +14,7 @@
 #include "clang/AST/ASTImporterLookupTable.h"
 #include "clang/AST/Decl.h"
 #include "clang/AST/RecursiveASTVisitor.h"
+#include "llvm/Support/FormatVariadic.h"
 
 namespace clang {
 
@@ -93,10 +94,19 @@
 }
 
 void ASTImporterLookupTable::remove(DeclContext *DC, NamedDecl *ND) {
-  DeclList &Decls = LookupTable[DC][ND->getDeclName()];
+  const DeclarationName Name = ND->getDeclName();
+  DeclList &Decls = LookupTable[DC][Name];
   bool EraseResult = Decls.remove(ND);
   (void)EraseResult;
-  assert(EraseResult == true && "Trying to remove not contained Decl");
+#ifndef NDEBUG
+  if (!EraseResult) {
+std::string Message =
+llvm::formatv("Trying to remove not contained Decl '{0}' of type {1}",
+  Name.getAsString(), DC->getDeclKindName())
+.str();
+llvm_unreachable(Message.c_str());
+  }
+#endif
 }
 
 void ASTImporterLookupTable::add(NamedDecl *ND) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D46081: [analyzer] Expand conversion check to check more expressions for overflow and underflow

2021-11-19 Thread Gabor Marton via Phabricator via cfe-commits
martong added a comment.

@whisperity Thank you for pinging! This seems still feasible. Besides, this is 
valuable for us, as it could pass some SEI CERT test cases, notably from INT31 
-C.


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

https://reviews.llvm.org/D46081

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


[PATCH] D46081: [analyzer] Expand conversion check to check more expressions for overflow and underflow

2021-11-19 Thread Gabor Marton via Phabricator via cfe-commits
martong added inline comments.



Comment at: lib/StaticAnalyzer/Checkers/ConversionChecker.cpp:102
 }
-  } else if (isa(Parent)) {
+  } else if (isa(Parent) || isa(Parent)) {
+if (!Cast->IgnoreParenImpCasts()->isEvaluatable(C.getASTContext())) {




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

https://reviews.llvm.org/D46081

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


[clang] bf55b9f - [analyzer][docs] Ellaborate the docs of cplusplus.StringChecker

2021-11-19 Thread Balazs Benics via cfe-commits

Author: Balazs Benics
Date: 2021-11-19T11:59:46+01:00
New Revision: bf55b9f0d0e938def5d24629325b271cbfc3b04a

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

LOG: [analyzer][docs] Ellaborate the docs of cplusplus.StringChecker

Let's describe accurately what the users can expect from the checker in
a direct way.
Also, add an example warning message.

Reviewed By: martong, Szelethus

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

Added: 


Modified: 
clang/docs/analyzer/checkers.rst

Removed: 




diff  --git a/clang/docs/analyzer/checkers.rst 
b/clang/docs/analyzer/checkers.rst
index 80cf3bc7c313..df62fb0643f8 100644
--- a/clang/docs/analyzer/checkers.rst
+++ b/clang/docs/analyzer/checkers.rst
@@ -319,13 +319,22 @@ cplusplus.StringChecker (C++)
 "
 Checks std::string operations.
 
+Checks if the cstring pointer from which the ``std::string`` object is
+constructed is ``NULL`` or not.
+If the checker cannot reason about the nullness of the pointer it will assume
+that it was non-null to satisfy the precondition of the constructor.
+
+This checker is capable of checking the `SEI CERT C++ coding rule STR51-CPP.
+Do not attempt to create a std::string from a null pointer
+`__.
+
 .. code-block:: cpp
 
  #include 
 
  void f(const char *p) {
if (!p) {
- std::string msg(p); // warn: p is NULL
+ std::string msg(p); // warn: The parameter must not be null
}
  }
 



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


[PATCH] D113401: [analyzer][docs] Ellaborate the docs of cplusplus.StringChecker

2021-11-19 Thread Balázs Benics via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGbf55b9f0d0e9: [analyzer][docs] Ellaborate the docs of 
cplusplus.StringChecker (authored by steakhal).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113401

Files:
  clang/docs/analyzer/checkers.rst


Index: clang/docs/analyzer/checkers.rst
===
--- clang/docs/analyzer/checkers.rst
+++ clang/docs/analyzer/checkers.rst
@@ -319,13 +319,22 @@
 "
 Checks std::string operations.
 
+Checks if the cstring pointer from which the ``std::string`` object is
+constructed is ``NULL`` or not.
+If the checker cannot reason about the nullness of the pointer it will assume
+that it was non-null to satisfy the precondition of the constructor.
+
+This checker is capable of checking the `SEI CERT C++ coding rule STR51-CPP.
+Do not attempt to create a std::string from a null pointer
+`__.
+
 .. code-block:: cpp
 
  #include 
 
  void f(const char *p) {
if (!p) {
- std::string msg(p); // warn: p is NULL
+ std::string msg(p); // warn: The parameter must not be null
}
  }
 


Index: clang/docs/analyzer/checkers.rst
===
--- clang/docs/analyzer/checkers.rst
+++ clang/docs/analyzer/checkers.rst
@@ -319,13 +319,22 @@
 "
 Checks std::string operations.
 
+Checks if the cstring pointer from which the ``std::string`` object is
+constructed is ``NULL`` or not.
+If the checker cannot reason about the nullness of the pointer it will assume
+that it was non-null to satisfy the precondition of the constructor.
+
+This checker is capable of checking the `SEI CERT C++ coding rule STR51-CPP.
+Do not attempt to create a std::string from a null pointer
+`__.
+
 .. code-block:: cpp
 
  #include 
 
  void f(const char *p) {
if (!p) {
- std::string msg(p); // warn: p is NULL
+ std::string msg(p); // warn: The parameter must not be null
}
  }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D107450: [clang-tidy] Fix wrong FixIt in performance-move-const-arg

2021-11-19 Thread gehry via Phabricator via cfe-commits
Sockke added a comment.

Kindly ping. @whisperity


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

https://reviews.llvm.org/D107450

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


[PATCH] D114234: [clang][dataflow] Add base types for building dataflow analyses

2021-11-19 Thread Stanislav Gatev via Phabricator via cfe-commits
sgatev created this revision.
sgatev added reviewers: ymandel, NoQ, xazax.hun, gribozavr.
Herald added subscribers: rnkovacs, mgorny.
sgatev requested review of this revision.
Herald added a project: clang.

This is part of the implementation of the dataflow analysis framework.
See "[RFC] A dataflow analysis framework for Clang AST" on cfe-dev.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D114234

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
  clang/include/clang/Analysis/FlowSensitive/Environment.h
  clang/lib/Analysis/CMakeLists.txt
  clang/lib/Analysis/FlowSensitive/CMakeLists.txt
  clang/lib/Analysis/FlowSensitive/DataflowAnalysis.cpp

Index: clang/lib/Analysis/FlowSensitive/DataflowAnalysis.cpp
===
--- /dev/null
+++ clang/lib/Analysis/FlowSensitive/DataflowAnalysis.cpp
@@ -0,0 +1,33 @@
+//===- DataflowAnalysis.cpp ---===//
+//
+// 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
+//
+//===--===//
+//
+//  This file defines base types for building dataflow analyses that run over
+//  Control-Flow Graphs (CFGs).
+//
+//===--===//
+
+#include 
+
+#include "clang/Analysis/CFG.h"
+#include "clang/Analysis/FlowSensitive/DataflowAnalysis.h"
+#include "clang/Analysis/FlowSensitive/Environment.h"
+#include "llvm/ADT/Optional.h"
+
+namespace clang {
+namespace dataflow {
+
+std::vector>
+runDataflowAnalysis(const CFG &Cfg, DataflowAnalysisDynamic &Analysis,
+const Environment &InitEnv) {
+  // FIXME: Implement work list-based algorithm to compute the fixed
+  // point of `Analysis::transform` for every basic block in `Cfg`.
+  return {};
+}
+
+} // namespace dataflow
+} // namespace clang
Index: clang/lib/Analysis/FlowSensitive/CMakeLists.txt
===
--- /dev/null
+++ clang/lib/Analysis/FlowSensitive/CMakeLists.txt
@@ -0,0 +1,7 @@
+add_clang_library(clangAnalysisFlowSensitive
+  DataflowAnalysis.cpp
+
+  LINK_LIBS
+  clangAnalysis
+  clangAST
+  )
Index: clang/lib/Analysis/CMakeLists.txt
===
--- clang/lib/Analysis/CMakeLists.txt
+++ clang/lib/Analysis/CMakeLists.txt
@@ -44,3 +44,4 @@
   )
 
 add_subdirectory(plugins)
+add_subdirectory(FlowSensitive)
Index: clang/include/clang/Analysis/FlowSensitive/Environment.h
===
--- /dev/null
+++ clang/include/clang/Analysis/FlowSensitive/Environment.h
@@ -0,0 +1,27 @@
+//===-- Environment.h ---*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file defines an Environment class that is used by dataflow analyses
+//  that run over Control-Flow Graphs (CFGs) to keep track of the state of the
+//  program at given program points.
+//
+//===--===//
+
+#ifndef LOCAL_GOOGLE_HOME_SGATEV_LLVM_PROJECT_DATAFLOW_CLANG_INCLUDE_CLANG_ANALYSIS_FLOWSENSITIVE_ENVIRONMENT_H_
+#define LOCAL_GOOGLE_HOME_SGATEV_LLVM_PROJECT_DATAFLOW_CLANG_INCLUDE_CLANG_ANALYSIS_FLOWSENSITIVE_ENVIRONMENT_H_
+
+namespace clang {
+namespace dataflow {
+
+// Holds the state of the program (store and heap) at a given program point.
+class Environment {};
+
+} // namespace dataflow
+} // namespace clang
+
+#endif // LOCAL_GOOGLE_HOME_SGATEV_LLVM_PROJECT_DATAFLOW_CLANG_INCLUDE_CLANG_ANALYSIS_FLOWSENSITIVE_ENVIRONMENT_H_
Index: clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
===
--- /dev/null
+++ clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
@@ -0,0 +1,162 @@
+//===- DataflowAnalysis.h ---*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file defines base types for building dataflow analyses that run over
+//  Control-Flow Graphs (CFGs).
+//
+//===--===//
+
+#ifndef LOCAL_GOOGLE_HOME_SGATEV_LLVM_PROJECT_DATAFLOW_CLANG_INCLUDE_CLANG_ANALYSIS_FLO

[PATCH] D113995: [clangd] Dex Trigrams: Improve query trigram generation

2021-11-19 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev updated this revision to Diff 388461.
kbobyrev added a comment.

Add improvements for identifier trigram generation and make query & id
generators consistent with each other.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113995

Files:
  clang-tools-extra/clangd/index/dex/Trigram.cpp
  clang-tools-extra/clangd/unittests/DexTests.cpp

Index: clang-tools-extra/clangd/unittests/DexTests.cpp
===
--- clang-tools-extra/clangd/unittests/DexTests.cpp
+++ clang-tools-extra/clangd/unittests/DexTests.cpp
@@ -386,30 +386,35 @@
   trigramsAre({"c", "cl", "cla", "lan", "ang", "ngd"}));
 
   EXPECT_THAT(identifierTrigramTokens("abc_def"),
-  trigramsAre({"a", "ab", "ad", "abc", "abd", "ade", "bcd", "bde",
-   "cde", "def"}));
+  trigramsAre({"a", "d", "ab", "ad", "de", "abc", "abd", "ade",
+   "bcd", "bde", "cde", "def"}));
 
   EXPECT_THAT(identifierTrigramTokens("a_b_c_d_e_"),
-  trigramsAre({"a", "a_", "ab", "abc", "bcd", "cde"}));
+  trigramsAre({"a", "b", "ab", "abc", "bcd", "cde"}));
 
   EXPECT_THAT(identifierTrigramTokens("unique_ptr"),
-  trigramsAre({"u", "un", "up", "uni", "unp", "upt", "niq", "nip",
-   "npt", "iqu", "iqp", "ipt", "que", "qup", "qpt",
-   "uep", "ept", "ptr"}));
+  trigramsAre({"u",   "p",   "un",  "up",  "pt",  "uni", "unp",
+   "upt", "niq", "nip", "npt", "iqu", "iqp", "ipt",
+   "que", "qup", "qpt", "uep", "ept", "ptr"}));
 
-  EXPECT_THAT(
-  identifierTrigramTokens("TUDecl"),
-  trigramsAre({"t", "tu", "td", "tud", "tde", "ude", "dec", "ecl"}));
+  EXPECT_THAT(identifierTrigramTokens("TUDecl"),
+  trigramsAre({"t", "d", "tu", "td", "de", "tud", "tde", "ude",
+   "dec", "ecl"}));
 
   EXPECT_THAT(identifierTrigramTokens("IsOK"),
-  trigramsAre({"i", "is", "io", "iso", "iok", "sok"}));
+  trigramsAre({"i", "o", "is", "ok", "io", "iso", "iok", "sok"}));
 
-  EXPECT_THAT(
-  identifierTrigramTokens("abc_defGhij__klm"),
-  trigramsAre({"a",   "ab",  "ad",  "abc", "abd", "ade", "adg", "bcd",
-   "bde", "bdg", "cde", "cdg", "def", "deg", "dgh", "dgk",
-   "efg", "egh", "egk", "fgh", "fgk", "ghi", "ghk", "gkl",
-   "hij", "hik", "hkl", "ijk", "ikl", "jkl", "klm"}));
+  EXPECT_THAT(identifierTrigramTokens("_pb"),
+  trigramsAre({"_", "_p", "p", "pb"}));
+  EXPECT_THAT(identifierTrigramTokens("__pb"),
+  trigramsAre({"_", "_p", "p", "pb"}));
+
+  EXPECT_THAT(identifierTrigramTokens("abc_defGhij__klm"),
+  trigramsAre({"a",   "d",   "ab",  "ad",  "de",  "abc", "abd",
+   "ade", "adg", "bcd", "bde", "bdg", "cde", "cdg",
+   "def", "deg", "dgh", "dgk", "efg", "egh", "egk",
+   "fgh", "fgk", "ghi", "ghk", "gkl", "hij", "hik",
+   "hkl", "ijk", "ikl", "jkl", "klm"}));
 }
 
 TEST(DexTrigrams, QueryTrigrams) {
@@ -419,8 +424,16 @@
 
   EXPECT_THAT(generateQueryTrigrams(""), trigramsAre({}));
   EXPECT_THAT(generateQueryTrigrams("_"), trigramsAre({"_"}));
-  EXPECT_THAT(generateQueryTrigrams("__"), trigramsAre({"__"}));
-  EXPECT_THAT(generateQueryTrigrams("___"), trigramsAre({}));
+  EXPECT_THAT(generateQueryTrigrams("__"), trigramsAre({"_"}));
+  EXPECT_THAT(generateQueryTrigrams("___"), trigramsAre({"_"}));
+
+  EXPECT_THAT(generateQueryTrigrams("m_"), trigramsAre({"m"}));
+
+  EXPECT_THAT(generateQueryTrigrams("p_b"), trigramsAre({"pb"}));
+  EXPECT_THAT(generateQueryTrigrams("pb_"), trigramsAre({"pb"}));
+  EXPECT_THAT(generateQueryTrigrams("_p"), trigramsAre({"_p"}));
+  EXPECT_THAT(generateQueryTrigrams("_pb_"), trigramsAre({"pb"}));
+  EXPECT_THAT(generateQueryTrigrams("__pb"), trigramsAre({"pb"}));
 
   EXPECT_THAT(generateQueryTrigrams("X86"), trigramsAre({"x86"}));
 
@@ -525,25 +538,45 @@
 }
 
 TEST(DexTest, ShortQuery) {
-  auto I = Dex::build(generateSymbols({"OneTwoThreeFour"}), RefSlab(),
+  auto I = Dex::build(generateSymbols({"_OneTwoFourSix"}), RefSlab(),
   RelationSlab());
   FuzzyFindRequest Req;
   Req.AnyScope = true;
   bool Incomplete;
 
-  EXPECT_THAT(match(*I, Req, &Incomplete), ElementsAre("OneTwoThreeFour"));
+  EXPECT_THAT(match(*I, Req, &Incomplete), ElementsAre("_OneTwoFourSix"));
   EXPECT_FALSE(Incomplete) << "Empty string is not a short query";
 
-  Req.Query = "t";
+  Req.Query = "o";
+  EXPECT_THAT(match(*I, Req, &Incomplete), ElementsAre("_OneTwoFourSix"));
+  EXPECT_TRUE(Incomplete) << "Using first head as unigram";
+
+  Req.Query = "_o";
+  EXPECT_THAT(match(*I, Req, &Incomplete), ElementsAre("_OneTwoFourSix"));
+

[PATCH] D114235: [clang] Extend ParsedAttr to allow custom handling for type attributes

2021-11-19 Thread Martin Böhme via Phabricator via cfe-commits
mboehme created this revision.
mboehme added a reviewer: aaron.ballman.
mboehme added a project: clang.
mboehme requested review of this revision.
Herald added a subscriber: cfe-commits.

A typical use case would be to allow custom attributes for pointer types. See 
examples/Attribute/Attribute.cpp for an example.

Unfortuantely, it is hard to provide meaningful test coverage for this change.  
The existing handleDeclAttribute() covered by lit tests for
attributes because multiple declaration attributes are marked 'SimpleHandler', 
which causes ClangAttrEmitter.cpp to generate a
handleDeclAttribute() handler for them.  However, all of the existing type 
attributes need custom semantic handling, so it is not possible to simply 
implement them with 'SimpleHandler'.

The modified Attribute.cpp example does at least demonstrate that it is 
possible to use the new API without any build errors, but this is all that it 
does.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D114235

Files:
  clang/docs/ClangPlugins.rst
  clang/examples/Attribute/Attribute.cpp
  clang/include/clang/Sema/ParsedAttr.h
  clang/lib/Sema/SemaType.cpp

Index: clang/lib/Sema/SemaType.cpp
===
--- clang/lib/Sema/SemaType.cpp
+++ clang/lib/Sema/SemaType.cpp
@@ -27,6 +27,7 @@
 #include "clang/Sema/DeclSpec.h"
 #include "clang/Sema/DelayedDiagnostic.h"
 #include "clang/Sema/Lookup.h"
+#include "clang/Sema/ParsedAttr.h"
 #include "clang/Sema/ParsedTemplate.h"
 #include "clang/Sema/ScopeInfo.h"
 #include "clang/Sema/SemaInternal.h"
@@ -350,16 +351,6 @@
   toList.addAtEnd(&attr);
 }
 
-/// The location of a type attribute.
-enum TypeAttrLocation {
-  /// The attribute is in the decl-specifier-seq.
-  TAL_DeclSpec,
-  /// The attribute is part of a DeclaratorChunk.
-  TAL_DeclChunk,
-  /// The attribute is immediately after the declaration's name.
-  TAL_DeclName
-};
-
 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
  TypeAttrLocation TAL, ParsedAttributesView &attrs);
 
@@ -8141,14 +8132,34 @@
 // If this is an attribute we can handle, do so now,
 // otherwise, add it to the FnAttrs list for rechaining.
 switch (attr.getKind()) {
-default:
-  // A [[]] attribute on a declarator chunk must appertain to a type.
-  if (attr.isStandardAttributeSyntax() && TAL == TAL_DeclChunk) {
-state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
-<< attr;
+default: {
+  Attr *outAttr = nullptr;
+  unsigned chunkIndex = 0;
+  if (TAL == TAL_DeclChunk) {
+chunkIndex = state.getCurrentChunkIndex();
+  }
+  switch (attr.getInfo().handleTypeAttribute(state.getSema(), type, TAL,
+ state.getDeclarator(),
+ chunkIndex, attr, &outAttr)) {
+  case ParsedAttrInfo::AttributeApplied:
+assert(outAttr != nullptr);
+type = state.getAttributedType(outAttr, type, type);
 attr.setUsedAsTypeAttr();
+break;
+  case ParsedAttrInfo::AttributeNotApplied:
+// Do nothing.
+break;
+  case ParsedAttrInfo::NotHandled:
+// A [[]] attribute on a declarator chunk must appertain to a type.
+if (attr.isStandardAttributeSyntax() && TAL == TAL_DeclChunk) {
+  state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
+  << attr;
+  attr.setUsedAsTypeAttr();
+}
+break;
   }
   break;
+}
 
 case ParsedAttr::UnknownAttribute:
   if (attr.isStandardAttributeSyntax() && TAL == TAL_DeclChunk)
Index: clang/include/clang/Sema/ParsedAttr.h
===
--- clang/include/clang/Sema/ParsedAttr.h
+++ clang/include/clang/Sema/ParsedAttr.h
@@ -34,6 +34,7 @@
 
 class ASTContext;
 class Decl;
+class Declarator;
 class Expr;
 class IdentifierInfo;
 class LangOptions;
@@ -42,6 +43,16 @@
 class Stmt;
 class TargetInfo;
 
+/// The location of a type attribute.
+enum TypeAttrLocation {
+  /// The attribute is in the decl-specifier-seq.
+  TAL_DeclSpec,
+  /// The attribute is part of a DeclaratorChunk.
+  TAL_DeclChunk,
+  /// The attribute is immediately after the declaration's name.
+  TAL_DeclName
+};
+
 struct ParsedAttrInfo {
   /// Corresponds to the Kind enum.
   unsigned AttrKind : 16;
@@ -123,6 +134,19 @@
const ParsedAttr &Attr) const {
 return NotHandled;
   }
+  /// If this ParsedAttrInfo knows how to handle this ParsedAttr applied to this
+  /// Type then do so and return either AttributeApplied if it was applied or
+  /// AttributeNotApplied if it wasn't. Otherwise return NotHandled.
+  /// If AttributeApplied is returned, *OutAttr should be set to point to a
+  /// corresponding Attr.
+  /// If TAL is TAL_DeclChunk, ChunkIndex contains 

[PATCH] D114234: [clang][dataflow] Add base types for building dataflow analyses

2021-11-19 Thread Stanislav Gatev via Phabricator via cfe-commits
sgatev updated this revision to Diff 388465.
sgatev added a comment.

Fix ifndefs.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114234

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
  clang/include/clang/Analysis/FlowSensitive/Environment.h
  clang/lib/Analysis/CMakeLists.txt
  clang/lib/Analysis/FlowSensitive/CMakeLists.txt
  clang/lib/Analysis/FlowSensitive/DataflowAnalysis.cpp

Index: clang/lib/Analysis/FlowSensitive/DataflowAnalysis.cpp
===
--- /dev/null
+++ clang/lib/Analysis/FlowSensitive/DataflowAnalysis.cpp
@@ -0,0 +1,33 @@
+//===- DataflowAnalysis.cpp ---===//
+//
+// 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
+//
+//===--===//
+//
+//  This file defines base types for building dataflow analyses that run over
+//  Control-Flow Graphs (CFGs).
+//
+//===--===//
+
+#include 
+
+#include "clang/Analysis/CFG.h"
+#include "clang/Analysis/FlowSensitive/DataflowAnalysis.h"
+#include "clang/Analysis/FlowSensitive/Environment.h"
+#include "llvm/ADT/Optional.h"
+
+namespace clang {
+namespace dataflow {
+
+std::vector>
+runDataflowAnalysis(const CFG &Cfg, DataflowAnalysisDynamic &Analysis,
+const Environment &InitEnv) {
+  // FIXME: Implement work list-based algorithm to compute the fixed
+  // point of `Analysis::transform` for every basic block in `Cfg`.
+  return {};
+}
+
+} // namespace dataflow
+} // namespace clang
Index: clang/lib/Analysis/FlowSensitive/CMakeLists.txt
===
--- /dev/null
+++ clang/lib/Analysis/FlowSensitive/CMakeLists.txt
@@ -0,0 +1,7 @@
+add_clang_library(clangAnalysisFlowSensitive
+  DataflowAnalysis.cpp
+
+  LINK_LIBS
+  clangAnalysis
+  clangAST
+  )
Index: clang/lib/Analysis/CMakeLists.txt
===
--- clang/lib/Analysis/CMakeLists.txt
+++ clang/lib/Analysis/CMakeLists.txt
@@ -44,3 +44,4 @@
   )
 
 add_subdirectory(plugins)
+add_subdirectory(FlowSensitive)
Index: clang/include/clang/Analysis/FlowSensitive/Environment.h
===
--- /dev/null
+++ clang/include/clang/Analysis/FlowSensitive/Environment.h
@@ -0,0 +1,27 @@
+//===-- Environment.h ---*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file defines an Environment class that is used by dataflow analyses
+//  that run over Control-Flow Graphs (CFGs) to keep track of the state of the
+//  program at given program points.
+//
+//===--===//
+
+#ifndef LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_ENVIRONMENT_H
+#define LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_ENVIRONMENT_H
+
+namespace clang {
+namespace dataflow {
+
+// Holds the state of the program (store and heap) at a given program point.
+class Environment {};
+
+} // namespace dataflow
+} // namespace clang
+
+#endif // LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_ENVIRONMENT_H
Index: clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
===
--- /dev/null
+++ clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
@@ -0,0 +1,162 @@
+//===- DataflowAnalysis.h ---*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file defines base types for building dataflow analyses that run over
+//  Control-Flow Graphs (CFGs).
+//
+//===--===//
+
+#ifndef LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_DATAFLOWANALYSIS_H
+#define LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_DATAFLOWANALYSIS_H
+
+#include 
+#include 
+#include 
+
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Stmt.h"
+#include "clang/Analysis/CFG.h"
+#include "clang/Analysis/FlowSensitive/Environment.h"
+#include "llvm/ADT/Any.h"
+#include "llvm/ADT/Optional.h"
+
+namespace clang {
+namespace dataflow {
+
+// Type-erased lattice element contain

[PATCH] D114234: [clang][dataflow] Add base types for building dataflow analyses

2021-11-19 Thread Stanislav Gatev via Phabricator via cfe-commits
sgatev updated this revision to Diff 388469.
sgatev added a comment.

Use triple slash at the start of declaration comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114234

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
  clang/include/clang/Analysis/FlowSensitive/Environment.h
  clang/lib/Analysis/CMakeLists.txt
  clang/lib/Analysis/FlowSensitive/CMakeLists.txt
  clang/lib/Analysis/FlowSensitive/DataflowAnalysis.cpp

Index: clang/lib/Analysis/FlowSensitive/DataflowAnalysis.cpp
===
--- /dev/null
+++ clang/lib/Analysis/FlowSensitive/DataflowAnalysis.cpp
@@ -0,0 +1,33 @@
+//===- DataflowAnalysis.cpp ---===//
+//
+// 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
+//
+//===--===//
+//
+//  This file defines base types for building dataflow analyses that run over
+//  Control-Flow Graphs (CFGs).
+//
+//===--===//
+
+#include 
+
+#include "clang/Analysis/CFG.h"
+#include "clang/Analysis/FlowSensitive/DataflowAnalysis.h"
+#include "clang/Analysis/FlowSensitive/Environment.h"
+#include "llvm/ADT/Optional.h"
+
+namespace clang {
+namespace dataflow {
+
+std::vector>
+runDataflowAnalysis(const CFG &Cfg, DataflowAnalysisDynamic &Analysis,
+const Environment &InitEnv) {
+  // FIXME: Implement work list-based algorithm to compute the fixed
+  // point of `Analysis::transform` for every basic block in `Cfg`.
+  return {};
+}
+
+} // namespace dataflow
+} // namespace clang
Index: clang/lib/Analysis/FlowSensitive/CMakeLists.txt
===
--- /dev/null
+++ clang/lib/Analysis/FlowSensitive/CMakeLists.txt
@@ -0,0 +1,7 @@
+add_clang_library(clangAnalysisFlowSensitive
+  DataflowAnalysis.cpp
+
+  LINK_LIBS
+  clangAnalysis
+  clangAST
+  )
Index: clang/lib/Analysis/CMakeLists.txt
===
--- clang/lib/Analysis/CMakeLists.txt
+++ clang/lib/Analysis/CMakeLists.txt
@@ -44,3 +44,4 @@
   )
 
 add_subdirectory(plugins)
+add_subdirectory(FlowSensitive)
Index: clang/include/clang/Analysis/FlowSensitive/Environment.h
===
--- /dev/null
+++ clang/include/clang/Analysis/FlowSensitive/Environment.h
@@ -0,0 +1,27 @@
+//===-- Environment.h ---*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file defines an Environment class that is used by dataflow analyses
+//  that run over Control-Flow Graphs (CFGs) to keep track of the state of the
+//  program at given program points.
+//
+//===--===//
+
+#ifndef LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_ENVIRONMENT_H
+#define LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_ENVIRONMENT_H
+
+namespace clang {
+namespace dataflow {
+
+/// Holds the state of the program (store and heap) at a given program point.
+class Environment {};
+
+} // namespace dataflow
+} // namespace clang
+
+#endif // LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_ENVIRONMENT_H
Index: clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
===
--- /dev/null
+++ clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
@@ -0,0 +1,164 @@
+//===- DataflowAnalysis.h ---*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file defines base types for building dataflow analyses that run over
+//  Control-Flow Graphs (CFGs).
+//
+//===--===//
+
+#ifndef LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_DATAFLOWANALYSIS_H
+#define LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_DATAFLOWANALYSIS_H
+
+#include 
+#include 
+#include 
+
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Stmt.h"
+#include "clang/Analysis/CFG.h"
+#include "clang/Analysis/FlowSensitive/Environment.h"
+#include "llvm/ADT/Any.h"
+#include "llvm/ADT/Optional.h"
+
+namespace clang {
+namespace dataflow 

[PATCH] D114025: [clang][NFC] Inclusive terms: replace some uses of sanity in clang

2021-11-19 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.

In D114025#3141414 , @keryell wrote:

> In D114025#3140192 , @Quuxplusone 
> wrote:
>
>> I think "sanity-check" could be reasonably replaced with "smoke-test," but 
>> (1) this PR doesn't do that, and (2) the phrase "smoke-test" is probably 
>> //harder// to understand,
>
> It seems difficult considering the potential atmospheric pollution, carbon 
> footprint, health issues, lung cancer, drug abuse, etc. implied.

This is not a constructive comment either, please stop.

In D114025#3141358 , @ZarkoCA wrote:

> @Quuxplusone Thanks for thorough review.

+1, you caught some stuff I was glossing over, but this is much improved. I 
made a few tiny suggestions (take them or leave them). Continues to LGTM




Comment at: clang/include/clang/AST/Redeclarable.h:261
   assert(Current && "Advancing while iterator has reached end");
-  // Sanity check to avoid infinite loop on invalid redecl chain.
+  // Validation check to avoid infinite loop on invalid redecl chain.
   if (Current->isFirstDecl()) {

Quuxplusone wrote:
> `// Make sure we don't infinite-loop on an invalid redecl chain. This should 
> never happen.`
Alternatively, "Make sure we don't infinitely loop..."



Comment at: clang/lib/Sema/SemaChecking.cpp:5536
+// GCC does not enforce these rules for GNU atomics, but we do, because if
+// we didn't it would be very confusing [For whom? How so?]
 auto IsAllowedValueType = [&](QualType ValType) {





Comment at: clang/lib/Sema/SemaChecking.cpp:5578
+// the GNU atomics specification, but we enforce it, because if we didn't 
it
+// would be very confusing [For whom? How so?]
 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114025

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


[clang] c227192 - Make clang-format fuzz through Lexing with asserts enabled.

2021-11-19 Thread Manuel Klimek via cfe-commits

Author: Manuel Klimek
Date: 2021-11-19T14:44:06+01:00
New Revision: c2271926a4fc395e05cf75a8e57c2dfab1f02d3d

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

LOG: Make clang-format fuzz through Lexing with asserts enabled.

Makes clang-format bail out if an in-memory source file with an
unsupported BOM is handed in instead of creating source locations that
are violating clang's assumptions.

In the future, we should add support to better transport error messages
like this through clang-format instead of printing to stderr and not
creating any changes.

Added: 


Modified: 
clang/lib/Format/Format.cpp
clang/lib/Format/QualifierAlignmentFixer.cpp
clang/lib/Format/SortJavaScriptImports.cpp
clang/lib/Format/TokenAnalyzer.cpp
clang/lib/Format/TokenAnalyzer.h

Removed: 




diff  --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 1d60f2b3a321b..085cca8853e62 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -2989,8 +2989,10 @@ reformat(const FormatStyle &Style, StringRef Code,
   if (Style.isJson()) {
 std::vector Ranges(1, tooling::Range(0, Code.size()));
 auto Env =
-std::make_unique(Code, FileName, Ranges, FirstStartColumn,
+Environment::make(Code, FileName, Ranges, FirstStartColumn,
   NextStartColumn, LastStartColumn);
+if (!Env)
+  return {};
 // Perform the actual formatting pass.
 tooling::Replacements Replaces =
 Formatter(*Env, Style, Status).process().first;
@@ -3046,9 +3048,10 @@ reformat(const FormatStyle &Style, StringRef Code,
   return TrailingCommaInserter(Env, Expanded).process();
 });
 
-  auto Env =
-  std::make_unique(Code, FileName, Ranges, FirstStartColumn,
-NextStartColumn, LastStartColumn);
+  auto Env = Environment::make(Code, FileName, Ranges, FirstStartColumn,
+   NextStartColumn, LastStartColumn);
+  if (!Env)
+return {};
   llvm::Optional CurrentCode = None;
   tooling::Replacements Fixes;
   unsigned Penalty = 0;
@@ -3061,10 +3064,12 @@ reformat(const FormatStyle &Style, StringRef Code,
   Penalty += PassFixes.second;
   if (I + 1 < E) {
 CurrentCode = std::move(*NewCode);
-Env = std::make_unique(
+Env = Environment::make(
 *CurrentCode, FileName,
 tooling::calculateRangesAfterReplacements(Fixes, Ranges),
 FirstStartColumn, NextStartColumn, LastStartColumn);
+if (!Env)
+  return {};
   }
 }
   }
@@ -3090,7 +3095,10 @@ tooling::Replacements cleanup(const FormatStyle &Style, 
StringRef Code,
   // cleanups only apply to C++ (they mostly concern ctor commas etc.)
   if (Style.Language != FormatStyle::LK_Cpp)
 return tooling::Replacements();
-  return Cleaner(Environment(Code, FileName, Ranges), Style).process().first;
+  auto Env = Environment::make(Code, FileName, Ranges);
+  if (!Env)
+return {};
+  return Cleaner(*Env, Style).process().first;
 }
 
 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
@@ -3107,7 +3115,10 @@ tooling::Replacements fixNamespaceEndComments(const 
FormatStyle &Style,
   StringRef Code,
   ArrayRef Ranges,
   StringRef FileName) {
-  return NamespaceEndCommentsFixer(Environment(Code, FileName, Ranges), Style)
+  auto Env = Environment::make(Code, FileName, Ranges);
+  if (!Env)
+return {};
+  return NamespaceEndCommentsFixer(*Env, Style)
   .process()
   .first;
 }
@@ -3116,7 +3127,10 @@ tooling::Replacements sortUsingDeclarations(const 
FormatStyle &Style,
 StringRef Code,
 ArrayRef Ranges,
 StringRef FileName) {
-  return UsingDeclarationsSorter(Environment(Code, FileName, Ranges), Style)
+  auto Env = Environment::make(Code, FileName, Ranges);
+  if (!Env)
+return {};
+  return UsingDeclarationsSorter(*Env, Style)
   .process()
   .first;
 }

diff  --git a/clang/lib/Format/QualifierAlignmentFixer.cpp 
b/clang/lib/Format/QualifierAlignmentFixer.cpp
index c70705a1cd7ff..5a89225c7fc86 100644
--- a/clang/lib/Format/QualifierAlignmentFixer.cpp
+++ b/clang/lib/Format/QualifierAlignmentFixer.cpp
@@ -61,10 +61,10 @@ QualifierAlignmentFixer::QualifierAlignmentFixer(
 std::pair QualifierAlignmentFixer::analyze(
 TokenAnnotator &Annotator, SmallVectorImpl 
&AnnotatedLines,
 FormatTokenLexer &Tokens) {
-
-  auto Env =
-  std::make_unique(Code, FileName, Ranges, FirstStartColumn,
-  

[clang] 6623c02 - The _Float16 type is supported on x86 systems with SSE2 enabled.

2021-11-19 Thread Zahira Ammarguellat via cfe-commits

Author: Zahira Ammarguellat
Date: 2021-11-19T08:59:50-05:00
New Revision: 6623c02d70c3732dbea59c6d79c69501baf9627b

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

LOG: The _Float16 type is supported on x86 systems with SSE2 enabled.
Operations are emulated by software emulation and “float” instructions.
This patch is allowing the support of _Float16 type without the use of
-max512fp16 flag. The final goal being, perform _Float16 emulation for
all arithmetic expressions.

Added: 
clang/test/CodeGen/X86/Float16-arithmetic.c
clang/test/CodeGen/X86/fp16-abi.c
clang/test/CodeGen/X86/fp16-complex.c

Modified: 
clang/docs/LanguageExtensions.rst
clang/docs/ReleaseNotes.rst
clang/lib/Basic/Targets/X86.cpp
clang/test/Sema/Float16.c
clang/test/Sema/conversion-target-dep.c
clang/test/SemaCXX/Float16.cpp

Removed: 
clang/test/CodeGen/X86/avx512fp16-abi.c
clang/test/CodeGen/X86/avx512fp16-complex.c



diff  --git a/clang/docs/LanguageExtensions.rst 
b/clang/docs/LanguageExtensions.rst
index 60b1ed383a1ff..dfdb01b8ff542 100644
--- a/clang/docs/LanguageExtensions.rst
+++ b/clang/docs/LanguageExtensions.rst
@@ -673,7 +673,7 @@ targets pending ABI standardization:
 * 64-bit ARM (AArch64)
 * AMDGPU
 * SPIR
-* X86 (Only available under feature AVX512-FP16)
+* X86 (Available with feature SSE2 and up enabled)
 
 ``_Float16`` will be supported on more targets as they define ABIs for it.
 

diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 104d2e908d809..d2fa7ff05a160 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -187,6 +187,7 @@ X86 Support in Clang
 
 
 - Support for ``AVX512-FP16`` instructions has been added.
+- Support for ``_Float16`` type has been added.
 
 Arm and AArch64 Support in Clang
 

diff  --git a/clang/lib/Basic/Targets/X86.cpp b/clang/lib/Basic/Targets/X86.cpp
index 454a7743dded3..5e36868937194 100644
--- a/clang/lib/Basic/Targets/X86.cpp
+++ b/clang/lib/Basic/Targets/X86.cpp
@@ -239,9 +239,9 @@ bool 
X86TargetInfo::handleTargetFeatures(std::vector &Features,
   HasAVX512ER = true;
 } else if (Feature == "+avx512fp16") {
   HasAVX512FP16 = true;
-  HasFloat16 = true;
 } else if (Feature == "+avx512pf") {
   HasAVX512PF = true;
+  HasLegalHalfType = true;
 } else if (Feature == "+avx512dq") {
   HasAVX512DQ = true;
 } else if (Feature == "+avx512bitalg") {
@@ -369,6 +369,8 @@ bool 
X86TargetInfo::handleTargetFeatures(std::vector &Features,
  .Default(NoXOP);
 XOPLevel = std::max(XOPLevel, XLevel);
   }
+  // Turn on _float16 for x86 (feature sse2)
+  HasFloat16 = SSELevel >= SSE2;
 
   // LLVM doesn't have a separate switch for fpmath, so only accept it if it
   // matches the selected sse level.

diff  --git a/clang/test/CodeGen/X86/Float16-arithmetic.c 
b/clang/test/CodeGen/X86/Float16-arithmetic.c
new file mode 100644
index 0..7f7b3ff594424
--- /dev/null
+++ b/clang/test/CodeGen/X86/Float16-arithmetic.c
@@ -0,0 +1,73 @@
+// RUN: %clang_cc1 -triple  x86_64-unknown-unknown -emit-llvm  \
+// RUN: < %s  | FileCheck %s --check-prefixes=CHECK
+
+_Float16 add1(_Float16 a, _Float16 b) {
+  // CHECK-LABEL: define{{.*}} half @add1
+  // CHECK: alloca half
+  // CHECK: alloca half
+  // CHECK: store half {{.*}}, half*
+  // CHECK: store half {{.*}}, half*
+  // CHECK: load half, half*
+  // CHECK: load half, half* {{.*}}
+  // CHECK: fadd half {{.*}}, {{.*}}
+  // CHECK: ret half
+  return a + b;
+}
+
+_Float16 add2(_Float16 a, _Float16 b, _Float16 c) {
+  // CHECK-LABEL: define{{.*}} half @add2
+  // CHECK: alloca half
+  // CHECK: alloca half
+  // CHECK: alloca half
+  // CHECK: store half {{.*}}, half*
+  // CHECK: store half {{.*}}, half*
+  // CHECK: store half {{.*}}, half*
+  // CHECK: load half, half* {{.*}}
+  // CHECK: load half, half* {{.*}}
+  // CHECK: fadd half {{.*}}, {{.*}}
+  // CHECK: load half, half* {{.*}}
+  // CHECK: fadd half {{.*}}, {{.*}}
+  // CHECK: ret half
+return a + b + c;
+}
+
+_Float16 sub(_Float16 a, _Float16 b) {
+  // CHECK-LABEL: define{{.*}} half @sub
+  // CHECK: alloca half
+  // CHECK: alloca half
+  // CHECK: store half {{.*}}, half*
+  // CHECK: store half {{.*}}, half*
+  // CHECK: load half, half*
+  // CHECK: load half, half* {{.*}}
+  // CHECK: fsub half {{.*}}, {{.*}}
+  // CHECK: ret half
+  return a - b;
+}
+
+_Float16 div(_Float16 a, _Float16 b) {
+  // CHECK-LABEL: define{{.*}} half @div
+  // CHECK: alloca half
+  // CHECK: alloca half
+  // CHECK: store half {{.*}}, half*
+  // CHECK: store half {{.*}}, half*
+  // CHECK: load half, half* {{.*}}
+  // CHECK: load half, half* {{.*}}
+  // CHECK: fdiv half {{.*}}, 

[PATCH] D103094: [analyzer] Implemented RangeSet::Factory::castTo function to perform promotions, truncations and conversions

2021-11-19 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov updated this revision to Diff 388481.
ASDenysPetrov added a comment.

Rebased.


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

https://reviews.llvm.org/D103094

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h
  
clang/include/clang/StaticAnalyzer/Core/PathSensitive/RangedConstraintManager.h
  clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
  clang/unittests/StaticAnalyzer/RangeSetTest.cpp

Index: clang/unittests/StaticAnalyzer/RangeSetTest.cpp
===
--- clang/unittests/StaticAnalyzer/RangeSetTest.cpp
+++ clang/unittests/StaticAnalyzer/RangeSetTest.cpp
@@ -40,12 +40,18 @@
   const Range &R) {
   return OS << toString(R);
 }
+LLVM_ATTRIBUTE_UNUSED static std::ostream &operator<<(std::ostream &OS,
+  APSIntType Ty) {
+  return OS << (Ty.isUnsigned() ? "u" : "s") << Ty.getBitWidth();
+}
 
 } // namespace ento
 } // namespace clang
 
 namespace {
 
+template  constexpr bool is_signed_v = std::is_signed::value;
+
 template  struct TestValues {
   static constexpr T MIN = std::numeric_limits::min();
   static constexpr T MAX = std::numeric_limits::max();
@@ -53,7 +59,7 @@
   // which unary minus does not affect on,
   // e.g. int8/int32(0), uint8(128), uint32(2147483648).
   static constexpr T MID =
-  std::is_signed::value ? 0 : ~(static_cast(-1) / static_cast(2));
+  is_signed_v ? 0 : ~(static_cast(-1) / static_cast(2));
   static constexpr T A = MID - (MAX - MID) / 3 * 2;
   static constexpr T B = MID - (MAX - MID) / 3;
   static constexpr T C = -B;
@@ -61,8 +67,40 @@
 
   static_assert(MIN < A && A < B && B < MID && MID < C && C < D && D < MAX,
 "Values shall be in an ascending order");
+  // Clear bits in low bytes by the given amount.
+  template 
+  static const T ClearLowBytes = static_cast(static_cast(Value)
+<< ((Bytes >= 8) ? 0 : Bytes) *
+   8);
+
+  template 
+  static constexpr T TruncZeroOf = ClearLowBytes;
+
+  // Random number with active bits in every byte. 0x'
+  static constexpr T XAAA = static_cast(
+  0b10101010'10101010'10101010'10101010'10101010'10101010'10101010'10101010);
+  template 
+  static constexpr T XAAATruncZeroOf = TruncZeroOf; // 0x'AB00
+
+  // Random number with active bits in every byte. 0x'
+  static constexpr T X555 = static_cast(
+  0b01010101'01010101'01010101'01010101'01010101'01010101'01010101'01010101);
+  template 
+  static constexpr T X555TruncZeroOf = TruncZeroOf; // 0x'5600
+
+  // Numbers for ranges with the same bits in the lowest byte.
+  // 0x'AA2A
+  static constexpr T FromA = ClearLowBytes + 42;
+  static constexpr T ToA = FromA + 2; // 0x'AA2C
+  // 0x'552A
+  static constexpr T FromB = ClearLowBytes + 42;
+  static constexpr T ToB = FromB + 2; // 0x'552C
 };
 
+template 
+static constexpr APSIntType APSIntTy = APSIntType(sizeof(T) * 8,
+  !is_signed_v);
+
 template  class RangeSetTest : public testing::Test {
 public:
   // Init block
@@ -74,8 +112,11 @@
   // End init block
 
   using Self = RangeSetTest;
-  using RawRange = std::pair;
-  using RawRangeSet = std::initializer_list;
+  template  using RawRangeT = std::pair;
+  template 
+  using RawRangeSetT = std::initializer_list>;
+  using RawRange = RawRangeT;
+  using RawRangeSet = RawRangeSetT;
 
   const llvm::APSInt &from(BaseType X) {
 static llvm::APSInt Base{sizeof(BaseType) * CHAR_BIT,
@@ -84,11 +125,12 @@
 return BVF.getValue(Base);
   }
 
-  Range from(const RawRange &Init) {
+  template  Range from(const RawRangeT &Init) {
 return Range(from(Init.first), from(Init.second));
   }
 
-  RangeSet from(const RawRangeSet &Init) {
+  template 
+  RangeSet from(RawRangeSetT Init, APSIntType Ty = APSIntTy) {
 RangeSet RangeSet = F.getEmptySet();
 for (const auto &Raw : Init) {
   RangeSet = F.add(RangeSet, from(Raw));
@@ -211,9 +253,20 @@
RawRangeSet RawExpected) {
 wrap(&Self::checkDeleteImpl, Point, RawFrom, RawExpected);
   }
-};
 
-} // namespace
+  void checkCastToImpl(RangeSet What, APSIntType Ty, RangeSet Expected) {
+RangeSet Result = F.castTo(What, Ty);
+EXPECT_EQ(Result, Expected)
+<< "while casting " << toString(What) << " to " << Ty;
+  }
+
+  template 
+  void checkCastTo(RawRangeSetT What, RawRangeSetT Expected) {
+static constexpr APSIntType FromTy = APSIntTy;
+static constexpr APSIntType ToTy = APSIntTy;
+this->checkCastToImpl(from(What, FromTy), ToTy, from(Expected, ToTy));
+  }
+};
 
 using IntTypes = ::testing::Types;
@@ -591,3 +644,425 @@
{{MIN, MIN}, {B, MID}, {MID + 1, C}, {C + 4, D - 1}},
{{MIN, MIN}, {A, C}, {C + 

[PATCH] D114206: [Clang][ScanDeps] Use the virtual path for module maps

2021-11-19 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 accepted this revision.
jansvoboda11 added a comment.
This revision is now accepted and ready to land.

LGTM provided the Windows crash gets resolved.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114206

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


[PATCH] D114099: Enable `_Float16` type support on X86 without the avx512fp16 flag

2021-11-19 Thread Zahira Ammarguellat via Phabricator via cfe-commits
zahiraam added a comment.

rG6623c02d70c3 



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

https://reviews.llvm.org/D114099

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


[PATCH] D114234: [clang][dataflow] Add base types for building dataflow analyses

2021-11-19 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel added inline comments.



Comment at: clang/lib/Analysis/FlowSensitive/DataflowAnalysis.cpp:21-22
+
+namespace clang {
+namespace dataflow {
+

It's more common in .cpp files to use using declarations instead:
```
using clang;
using dataflow;
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114234

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


[PATCH] D114229: [clang][driver] Always add LTO options when using GNU toolchain

2021-11-19 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder added a comment.

The test failures are pretty obvious about when this fails. All affected builds 
have an implicit dependency on the `LLVMgold.so` like this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114229

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


[clang] 8025660 - [OpenMP] support depend clause for taskwait directive, by Deepak

2021-11-19 Thread Alexey Bataev via cfe-commits

Author: Alexey Bataev
Date: 2021-11-19T06:30:17-08:00
New Revision: 80256605f8c6aab8cb33ac3a3784aacd005087a3

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

LOG: [OpenMP] support depend clause for taskwait directive, by Deepak
Eachempati.

This patch adds clang (parsing, sema, serialization, codegen) support for the 
'depend' clause on the 'taskwait' directive.

Reviewed By: ABataev

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

Added: 
clang/test/OpenMP/taskwait_depend_codegen.cpp
clang/test/OpenMP/taskwait_depend_messages.cpp

Modified: 
clang/docs/OpenMPSupport.rst
clang/include/clang/AST/StmtOpenMP.h
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/include/clang/Sema/Sema.h
clang/lib/AST/StmtOpenMP.cpp
clang/lib/CodeGen/CGOpenMPRuntime.cpp
clang/lib/CodeGen/CGOpenMPRuntime.h
clang/lib/CodeGen/CGStmtOpenMP.cpp
clang/lib/Sema/SemaOpenMP.cpp
clang/lib/Serialization/ASTReaderStmt.cpp
clang/lib/Serialization/ASTWriterStmt.cpp
clang/test/OpenMP/taskwait_ast_print.cpp
clang/test/OpenMP/taskwait_messages.cpp
openmp/runtime/test/ompt/tasks/taskwait-depend.c
openmp/runtime/test/tasking/omp50_taskwait_depend.c

Removed: 




diff  --git a/clang/docs/OpenMPSupport.rst b/clang/docs/OpenMPSupport.rst
index 0e3cd25e59e3c..8b530b9febef6 100644
--- a/clang/docs/OpenMPSupport.rst
+++ b/clang/docs/OpenMPSupport.rst
@@ -147,7 +147,7 @@ implementation.
 
+--+--+--+---+
 | task extension   | task affinity 
   | :part:`not upstream` | 
https://github.com/jklinkenberg/openmp/tree/task-affinity |
 
+--+--+--+---+
-| task extension   | clause: depend on the taskwait construct  
   | :part:`worked on`| 
  |
+| task extension   | clause: depend on the taskwait construct  
   | :part:`mostly done`  | D113540 (regular codegen only)  
  |
 
+--+--+--+---+
 | task extension   | depend objects and detachable tasks   
   | :good:`done` | 
  |
 
+--+--+--+---+

diff  --git a/clang/include/clang/AST/StmtOpenMP.h 
b/clang/include/clang/AST/StmtOpenMP.h
index 48b2dce152a64..d5b5c9580da9e 100644
--- a/clang/include/clang/AST/StmtOpenMP.h
+++ b/clang/include/clang/AST/StmtOpenMP.h
@@ -2569,15 +2569,20 @@ class OMPTaskwaitDirective : public 
OMPExecutableDirective {
   /// \param C AST context.
   /// \param StartLoc Starting location of the directive kind.
   /// \param EndLoc Ending Location of the directive.
+  /// \param Clauses List of clauses.
   ///
-  static OMPTaskwaitDirective *
-  Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc);
+  static OMPTaskwaitDirective *Create(const ASTContext &C,
+  SourceLocation StartLoc,
+  SourceLocation EndLoc,
+  ArrayRef Clauses);
 
   /// Creates an empty directive.
   ///
   /// \param C AST context.
+  /// \param NumClauses Number of clauses.
   ///
-  static OMPTaskwaitDirective *CreateEmpty(const ASTContext &C, EmptyShell);
+  static OMPTaskwaitDirective *CreateEmpty(const ASTContext &C,
+   unsigned NumClauses, EmptyShell);
 
   static bool classof(const Stmt *T) {
 return T->getStmtClass() == OMPTaskwaitDirectiveClass;

diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 50c1e0a1746bc..dc67f86f25cab 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -10599,6 +10599,8 @@ def err_omp_depend_sink_unexpected_expr : Error<
   "unexpected expression: number of expressions is larger than the number of 
associated loops">;
 def 

[PATCH] D113540: [OpenMP] support depend clause for taskwait directive

2021-11-19 Thread Alexey Bataev 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 rG80256605f8c6: [OpenMP] support depend clause for taskwait 
directive, by Deepak (authored by ABataev).
Herald added projects: clang, OpenMP.
Herald added subscribers: openmp-commits, cfe-commits.

Changed prior to commit:
  https://reviews.llvm.org/D113540?vs=386345&id=388488#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113540

Files:
  clang/docs/OpenMPSupport.rst
  clang/include/clang/AST/StmtOpenMP.h
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/StmtOpenMP.cpp
  clang/lib/CodeGen/CGOpenMPRuntime.cpp
  clang/lib/CodeGen/CGOpenMPRuntime.h
  clang/lib/CodeGen/CGStmtOpenMP.cpp
  clang/lib/Sema/SemaOpenMP.cpp
  clang/lib/Serialization/ASTReaderStmt.cpp
  clang/lib/Serialization/ASTWriterStmt.cpp
  clang/test/OpenMP/taskwait_ast_print.cpp
  clang/test/OpenMP/taskwait_depend_codegen.cpp
  clang/test/OpenMP/taskwait_depend_messages.cpp
  clang/test/OpenMP/taskwait_messages.cpp
  openmp/runtime/test/ompt/tasks/taskwait-depend.c
  openmp/runtime/test/tasking/omp50_taskwait_depend.c

Index: openmp/runtime/test/tasking/omp50_taskwait_depend.c
===
--- openmp/runtime/test/tasking/omp50_taskwait_depend.c
+++ openmp/runtime/test/tasking/omp50_taskwait_depend.c
@@ -1,11 +1,12 @@
 // RUN: %libomp-compile-and-run
 // UNSUPPORTED: gcc-4, gcc-5, gcc-6, gcc-7, gcc-8
-// clang does not yet support taskwait with depend clause
-// clang-12 introduced parsing, but no codegen
-// TODO: update expected result when codegen in clang is added
+
+// support for taskwait with depend clause introduced in clang-14
+// UNSUPPORTED: clang-5, clang-6, clang-6, clang-8, clang-9, clang-10, clang-11,
+// clang-12, clang-13
+
 // icc does not yet support taskwait with depend clause
-// TODO: update expected result when support for icc is added
-// XFAIL: clang, icc
+// XFAIL: icc
 
 #include 
 #include 
Index: openmp/runtime/test/ompt/tasks/taskwait-depend.c
===
--- openmp/runtime/test/ompt/tasks/taskwait-depend.c
+++ openmp/runtime/test/ompt/tasks/taskwait-depend.c
@@ -7,10 +7,9 @@
 // icc does not yet support taskwait with depend clause
 // XFAIL: icc
 
-// clang does not yet support taskwait with depend clause
-// clang-12 introduced parsing, but no codegen
-// update expected result when codegen in clang was added
-// XFAIL: clang
+// support for taskwait with depend clause introduced in clang-14
+// UNSUPPORTED: clang-5, clang-6, clang-6, clang-8, clang-9, clang-10, clang-11,
+// clang-12, clang-13
 
 #include "callback.h"
 #include 
Index: clang/test/OpenMP/taskwait_messages.cpp
===
--- clang/test/OpenMP/taskwait_messages.cpp
+++ clang/test/OpenMP/taskwait_messages.cpp
@@ -1,10 +1,11 @@
-// RUN: %clang_cc1 -verify -fopenmp -ferror-limit 100 %s -Wuninitialized
+// RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=45 -ferror-limit 100 %s -Wuninitialized
 
-// RUN: %clang_cc1 -verify -fopenmp-simd -ferror-limit 100 %s -Wuninitialized
+// RUN: %clang_cc1 -verify -fopenmp-simd -fopenmp-version=45 -ferror-limit 100 %s -Wuninitialized
 
 template 
 T tmain(T argc) {
 #pragma omp taskwait allocate(argc) // expected-error {{unexpected OpenMP clause 'allocate' in directive '#pragma omp taskwait'}}
+#pragma omp taskwait depend(in:argc) // expected-error {{unexpected OpenMP clause 'depend' in directive '#pragma omp taskwait'}}
   ;
 #pragma omp taskwait untied  // expected-error {{unexpected OpenMP clause 'untied' in directive '#pragma omp taskwait'}}
 #pragma omp taskwait unknown // expected-warning {{extra tokens at the end of '#pragma omp taskwait' are ignored}}
Index: clang/test/OpenMP/taskwait_depend_messages.cpp
===
--- /dev/null
+++ clang/test/OpenMP/taskwait_depend_messages.cpp
@@ -0,0 +1,62 @@
+// RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=50 -ferror-limit 100 -o - -std=c++11 %s -Wuninitialized
+
+// RUN: %clang_cc1 -verify -fopenmp-simd -fopenmp-version=50 -ferror-limit 100 -o - -std=c++11 %s -Wuninitialized
+
+void foo() {
+}
+
+bool foobool(int argc) {
+  return argc;
+}
+
+struct S1; // expected-note {{declared here}}
+
+class vector {
+  public:
+int operator[](int index) { return 0; }
+};
+
+int main(int argc, char **argv, char *env[]) {
+  vector vec;
+  typedef float V __attribute__((vector_size(16)));
+  V a;
+  auto arr = x; // expected-error {{use of undeclared identifier 'x'}}
+
+  #pragma omp taskwait depend // expected-error {{expected '(' after 'depend'}}
+  #pragma omp taskwait depend ( // expected-error {{expected depend modifier(iterator) or 'in', 'out', 'inout', 'mutexin

[PATCH] D114234: [clang][dataflow] Add base types for building dataflow analyses

2021-11-19 Thread Stanislav Gatev via Phabricator via cfe-commits
sgatev updated this revision to Diff 388490.
sgatev added a comment.

Add using namespace declarations in the cpp file.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114234

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
  clang/include/clang/Analysis/FlowSensitive/Environment.h
  clang/lib/Analysis/CMakeLists.txt
  clang/lib/Analysis/FlowSensitive/CMakeLists.txt
  clang/lib/Analysis/FlowSensitive/DataflowAnalysis.cpp

Index: clang/lib/Analysis/FlowSensitive/DataflowAnalysis.cpp
===
--- /dev/null
+++ clang/lib/Analysis/FlowSensitive/DataflowAnalysis.cpp
@@ -0,0 +1,30 @@
+//===- DataflowAnalysis.cpp ---===//
+//
+// 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
+//
+//===--===//
+//
+//  This file defines base types for building dataflow analyses that run over
+//  Control-Flow Graphs (CFGs).
+//
+//===--===//
+
+#include 
+
+#include "clang/Analysis/CFG.h"
+#include "clang/Analysis/FlowSensitive/DataflowAnalysis.h"
+#include "clang/Analysis/FlowSensitive/Environment.h"
+#include "llvm/ADT/Optional.h"
+
+using namespace clang;
+using namespace dataflow;
+
+std::vector>
+runDataflowAnalysis(const CFG &Cfg, DataflowAnalysisDynamic &Analysis,
+const Environment &InitEnv) {
+  // FIXME: Implement work list-based algorithm to compute the fixed
+  // point of `Analysis::transform` for every basic block in `Cfg`.
+  return {};
+}
Index: clang/lib/Analysis/FlowSensitive/CMakeLists.txt
===
--- /dev/null
+++ clang/lib/Analysis/FlowSensitive/CMakeLists.txt
@@ -0,0 +1,7 @@
+add_clang_library(clangAnalysisFlowSensitive
+  DataflowAnalysis.cpp
+
+  LINK_LIBS
+  clangAnalysis
+  clangAST
+  )
Index: clang/lib/Analysis/CMakeLists.txt
===
--- clang/lib/Analysis/CMakeLists.txt
+++ clang/lib/Analysis/CMakeLists.txt
@@ -44,3 +44,4 @@
   )
 
 add_subdirectory(plugins)
+add_subdirectory(FlowSensitive)
Index: clang/include/clang/Analysis/FlowSensitive/Environment.h
===
--- /dev/null
+++ clang/include/clang/Analysis/FlowSensitive/Environment.h
@@ -0,0 +1,27 @@
+//===-- Environment.h ---*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file defines an Environment class that is used by dataflow analyses
+//  that run over Control-Flow Graphs (CFGs) to keep track of the state of the
+//  program at given program points.
+//
+//===--===//
+
+#ifndef LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_ENVIRONMENT_H
+#define LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_ENVIRONMENT_H
+
+namespace clang {
+namespace dataflow {
+
+/// Holds the state of the program (store and heap) at a given program point.
+class Environment {};
+
+} // namespace dataflow
+} // namespace clang
+
+#endif // LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_ENVIRONMENT_H
Index: clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
===
--- /dev/null
+++ clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
@@ -0,0 +1,164 @@
+//===- DataflowAnalysis.h ---*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file defines base types for building dataflow analyses that run over
+//  Control-Flow Graphs (CFGs).
+//
+//===--===//
+
+#ifndef LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_DATAFLOWANALYSIS_H
+#define LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_DATAFLOWANALYSIS_H
+
+#include 
+#include 
+#include 
+
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Stmt.h"
+#include "clang/Analysis/CFG.h"
+#include "clang/Analysis/FlowSensitive/Environment.h"
+#include "llvm/ADT/Any.h"
+#include "llvm/ADT/Optional.h"
+
+namespace clang {
+namespace dataflow {
+
+/// Type-erased lattice element contain

[PATCH] D114025: [clang][NFC] Inclusive terms: replace some uses of sanity in clang

2021-11-19 Thread Zarko Todorovski via Phabricator via cfe-commits
ZarkoCA marked 3 inline comments as done.
ZarkoCA added a comment.

In D114025#3142565 , @aaron.ballman 
wrote:

> In D114025#3141414 , @keryell wrote:
>
>> In D114025#3140192 , @Quuxplusone 
>> wrote:
>>
>>> I think "sanity-check" could be reasonably replaced with "smoke-test," but 
>>> (1) this PR doesn't do that, and (2) the phrase "smoke-test" is probably 
>>> //harder// to understand,
>>
>> It seems difficult considering the potential atmospheric pollution, carbon 
>> footprint, health issues, lung cancer, drug abuse, etc. implied.
>
> This is not a constructive comment either, please stop.
>
> In D114025#3141358 , @ZarkoCA wrote:
>
>> @Quuxplusone Thanks for thorough review.
>
> +1, you caught some stuff I was glossing over, but this is much improved. I 
> made a few tiny suggestions (take them or leave them). Continues to LGTM

Yes, agreed, the suggestions made this much better. Thanks.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114025

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


[PATCH] D114025: [clang][NFC] Inclusive terms: replace some uses of sanity in clang

2021-11-19 Thread Zarko Todorovski via Phabricator via cfe-commits
ZarkoCA updated this revision to Diff 388494.
ZarkoCA added a comment.

- Add FIXME to comments and fix grammar on one comment


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114025

Files:
  clang/include/clang/AST/Redeclarable.h
  clang/include/clang/Analysis/CFG.h
  clang/include/clang/CodeGen/CGFunctionInfo.h
  clang/include/clang/Sema/Lookup.h
  clang/lib/Analysis/BodyFarm.cpp
  clang/lib/Analysis/RetainSummaryManager.cpp
  clang/lib/Basic/DiagnosticIDs.cpp
  clang/lib/Basic/SourceManager.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Format/Format.cpp
  clang/lib/Frontend/FrontendActions.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaExprCXX.cpp
  clang/lib/Sema/SemaLookup.cpp
  clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/MIGChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
  clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
  clang/lib/StaticAnalyzer/Core/Store.cpp
  clang/lib/Tooling/Syntax/Tree.cpp

Index: clang/lib/Tooling/Syntax/Tree.cpp
===
--- clang/lib/Tooling/Syntax/Tree.cpp
+++ clang/lib/Tooling/Syntax/Tree.cpp
@@ -126,7 +126,7 @@
   for (auto *N = New; N; N = N->NextSibling) {
 assert(N->Parent == nullptr);
 assert(N->getRole() != NodeRole::Detached && "Roles must be set");
-// FIXME: sanity-check the role.
+// FIXME: validate the role.
   }
 
   auto Reachable = [](Node *From, Node *N) {
Index: clang/lib/StaticAnalyzer/Core/Store.cpp
===
--- clang/lib/StaticAnalyzer/Core/Store.cpp
+++ clang/lib/StaticAnalyzer/Core/Store.cpp
@@ -249,7 +249,7 @@
 }
 
 SVal StoreManager::evalDerivedToBase(SVal Derived, const CastExpr *Cast) {
-  // Sanity check to avoid doing the wrong thing in the face of
+  // Early return to avoid doing the wrong thing in the face of
   // reinterpret_cast.
   if (!regionMatchesCXXRecordType(Derived, Cast->getSubExpr()->getType()))
 return UnknownVal();
Index: clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
===
--- clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -326,8 +326,8 @@
 }
 Result = InitWithAdjustments;
   } else {
-// We need to create a region no matter what. For sanity, make sure we don't
-// try to stuff a Loc into a non-pointer temporary region.
+// We need to create a region no matter what. Make sure we don't try to
+// stuff a Loc into a non-pointer temporary region.
 assert(!InitValWithAdjustments.getAs() ||
Loc::isLocType(Result->getType()) ||
Result->getType()->isMemberPointerType());
Index: clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
===
--- clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -1670,9 +1670,10 @@
   if (isUnderconstrained(PrevN)) {
 IsSatisfied = true;
 
-// As a sanity check, make sure that the negation of the constraint
-// was infeasible in the current state.  If it is feasible, we somehow
-// missed the transition point.
+// At this point, the negation of the constraint should be infeasible. If it
+// is feasible, make sure that the negation of the constrainti was
+// infeasible in the current state.  If it is feasible, we somehow missed
+// the transition point.
 assert(!isUnderconstrained(N));
 
 // We found the transition point for the constraint.  We now need to
Index: clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
@@ -182,8 +182,7 @@
   ProgramStateRef state = C.getState();
 
   if (CE->getNumArgs() < MinArgCount) {
-// The frontend should issue a warning for this case, so this is a sanity
-// check.
+// The frontend should issue a warning for this case. Just return.
 return;
   } else if (CE->getNumArgs() == MaxArgCount) {
 const Expr *Arg = CE->getArg(CreateModeArgIndex);
@@ -366,7 +365,7 @@
  const unsigned numArgs,
  const unsigned sizeArg,
  const char *fn) const {
-  // Sanity check for the correct number of arguments
+  // Check for the correct number of arguments.
   if (CE->getNumArgs() != numArgs)
 return;

[PATCH] D113754: [Analyzer][Core] Simplify IntSym in SValBuilder

2021-11-19 Thread Gabor Marton via Phabricator via cfe-commits
martong added a comment.

In D113754#3127245 , @steakhal wrote:

> Great stuff. Have you checked the coverage?

Thanks for the review! So, here are the coverage results for the new test file:

  1186   2 : SVal VisitIntSymExpr(const IntSymExpr *S) {
  1187   2 :   auto I = Cached.find(S);
  1188   2 :   if (I != Cached.end())
  1189   0 : return I->second;
  1190 :
  1191   2 :   SVal RHS = Visit(S->getRHS());
  1192   2 :   if (isUnchanged(S->getRHS(), RHS))
  1193   0 : return skip(S);
  1194   2 :   SVal LHS = SVB.makeIntVal(S->getLHS());
  1195 :   return cache(
  1196   2 :   S, SVB.evalBinOp(State, S->getOpcode(), LHS, 
RHS, S->getType()));
  1197 : }

L1189 is not covered, but that is related to the caching mechanism, which is 
already existing and this patch is independent from that. We have the very same 
caching implementation in all the other `Visit` functions.
L1193 There is an existing test case in `find-binop-constraints.cpp` which 
covers this line. :

  int test_lhs_and_rhs_further_constrained(int x, int y) {
if (x % y != 1)
  return 0;
if (x != 1)
  return 0;
if (y != 2)
  return 0;
clang_analyzer_eval(x % y == 1); // expected-warning{{TRUE}}
clang_analyzer_eval(y == 2); // expected-warning{{TRUE}}
return 0;
  }

I could have replicated this test case here, but hadn't been able to formulate 
any new expectations with a `clang_analyzer_` function. So there is no visible 
functional change in this case with this patch concerning this line. Besides, 
all other existing `Visit` functions have the same optimization and they do an 
early return with `skip` if the symbol is unchanged.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113754

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


[PATCH] D114151: [clang-format] [C++20] [Module] clang-format couldn't recognize partitions

2021-11-19 Thread Owen Pan via Phabricator via cfe-commits
owenpan added inline comments.



Comment at: clang/lib/Format/TokenAnnotator.cpp:3226
+// No space between module :.
+if (Left.isOneOf(Keywords.kw_module, tok::kw_export, Keywords.kw_import) &&
+Right.is(TT_ModulePartitionColon))

You can remove `kw_export` as it must be followed by `import` or `module`, 
based on how `TT_ModulePartitionColon` is set on Line 908.



Comment at: clang/lib/Format/TokenAnnotator.cpp:3230-3231
+// No space between import foo:bar but keep a space between import :bar;
+if (Left.isOneOf(tok::identifier, tok::kw_public, tok::kw_private) &&
+!Left.is(Keywords.kw_import) && Right.is(TT_ModulePartitionColon))
+  return false;

You can drop `!Left.is(Keywords.kw_import)` as `import :bar` is already covered 
by Line 3226. Also, I would remove `kw_public` and `kw_private` as they are not 
special WRT other keywords when followed by `TT_ModulePartitionColon`.



Comment at: clang/lib/Format/TokenAnnotator.cpp:3235
+if (Left.is(TT_ModulePartitionColon) &&
+Right.isOneOf(tok::identifier, tok::kw_public, tok::kw_private))
+  return false;

Is `module :public` a thing in C++20? If not, I would remove `kw_public`.



Comment at: clang/lib/Format/TokenAnnotator.cpp:3238
+// import .;
+if (Left.is(Keywords.kw_import) && Right.is(tok::ellipsis))
+  return true;

You can fold this line into Line 3223 above.



Comment at: clang/lib/Format/UnwrappedLineParser.cpp:1253
   }
+  if (Style.isCpp()) {
+nextToken();

Maybe move this entire block into a function?



Comment at: clang/lib/Format/UnwrappedLineParser.cpp:1260
+  // Handle import  as we would an include statement
+  if (FormatTok && FormatTok->is(tok::less)) {
+nextToken();

You can change this line to `else if (FormatTok->is(tok::less)) {` as 
`FormatTok` can't be null.



Comment at: clang/lib/Format/UnwrappedLineParser.cpp:1262-1264
+while (FormatTok) {
+  if (FormatTok->is(tok::semi))
+break;

You can combine these three lines into one: `while (FormatTok && 
FormatTok->isNot(tok::semi)) {`



Comment at: clang/lib/Format/UnwrappedLineParser.cpp:1267-1268
+  // literals.
+  if (FormatTok->isNot(tok::comment) &&
+  !FormatTok->TokenText.startswith("//"))
+FormatTok->setType(TT_ImplicitStringLiteral);

Don't you want to mark up to the matching `>`?


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

https://reviews.llvm.org/D114151

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


[PATCH] D114151: [clang-format] [C++20] [Module] clang-format couldn't recognize partitions

2021-11-19 Thread Arthur O'Dwyer via Phabricator via cfe-commits
Quuxplusone added inline comments.



Comment at: clang/lib/Format/TokenAnnotator.cpp:3235
+if (Left.is(TT_ModulePartitionColon) &&
+Right.isOneOf(tok::identifier, tok::kw_public, tok::kw_private))
+  return false;

owenpan wrote:
> Is `module :public` a thing in C++20? If not, I would remove `kw_public`.
For the record, my understanding is that `module :public` is not a thing, and 
neither is `module public:while` or any other combination of keywords 
//except// for `module :private`. (I don't even think `module foo:private` is a 
thing; is it?)
So +1 to removing `kw_public`. However, if the codebase happens to already have 
a function for `isIdentifierOrKeyword`, I think this would be a perfect place 
to use it. Consider an autoformatter-as-you-type dealing with `module 
foo:public[X]_methods` or `module :if[X]stream`.


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

https://reviews.llvm.org/D114151

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


[PATCH] D114229: [clang][driver] Always add LTO options when using GNU toolchain

2021-11-19 Thread Teresa Johnson via Phabricator via cfe-commits
tejohnson added inline comments.



Comment at: clang/lib/Driver/ToolChains/Gnu.cpp:558
 assert(!Inputs.empty() && "Must have at least one input.");
 addLTOOptions(ToolChain, Args, CmdArgs, Output, Inputs[0],
   D.getLTOMode() == LTOK_Thin);

This will add a whole lot of options besides -plugin, which is the only thing 
guarded against for lld. But in general I'm not in favor of adding a dependence 
on having the LTO plugin available to all non-lld links by default.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114229

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


[PATCH] D114249: [clang-tidy] performance-unnecessary-copy-initialization: Fix false negative.

2021-11-19 Thread Clement Courbet via Phabricator via cfe-commits
courbet created this revision.
courbet added reviewers: flx, aaron.ballman.
Herald added subscribers: carlosgalvezp, xazax.hun.
courbet requested review of this revision.
Herald added a project: clang-tools-extra.

`isConstRefReturningMethodCall` should be considering
`CXXOperatorCallExpr` in addition to `CXXMemberCallExpr`. Clang considers
these to be distinct (`CXXOperatorCallExpr` derives from `CallExpr`, not
`CXXMemberCallExpr`), but we don't care in the context of this
check.

This is important because of
`std::vector::operator[](size_t) const`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D114249

Files:
  clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.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
@@ -24,6 +24,11 @@
   operator int() const; // Implicit conversion to int.
 };
 
+struct ExpensiveToCopyContainer {
+  const ExpensiveToCopyType &operator[](int) const;
+  const ExpensiveToCopyType &operator[](int);
+};
+
 struct TrivialToCopyType {
   const TrivialToCopyType &reference() const;
 };
@@ -138,6 +143,50 @@
   VarCopyConstructed.constMethod();
 }
 
+void PositiveOperatorCallConstReferenceParam(const ExpensiveToCopyContainer 
&C) {
+  const auto AutoAssigned = C[42];
+  // CHECK-MESSAGES: [[@LINE-1]]:14: warning: the const qualified variable 
'AutoAssigned'
+  // CHECK-FIXES: const auto& AutoAssigned = C[42];
+  AutoAssigned.constMethod();
+
+  const auto AutoCopyConstructed(C[42]);
+  // CHECK-MESSAGES: [[@LINE-1]]:14: warning: the const qualified variable 
'AutoCopyConstructed'
+  // CHECK-FIXES: const auto& AutoCopyConstructed(C[42]);
+  AutoCopyConstructed.constMethod();
+
+  const ExpensiveToCopyType VarAssigned = C[42];
+  // CHECK-MESSAGES: [[@LINE-1]]:29: warning: the const qualified variable 
'VarAssigned'
+  // CHECK-FIXES: const ExpensiveToCopyType& VarAssigned = C[42];
+  VarAssigned.constMethod();
+
+  const ExpensiveToCopyType VarCopyConstructed(C[42]);
+  // CHECK-MESSAGES: [[@LINE-1]]:29: warning: the const qualified variable 
'VarCopyConstructed'
+  // CHECK-FIXES: const ExpensiveToCopyType& VarCopyConstructed(C[42]);
+  VarCopyConstructed.constMethod();
+}
+
+void PositiveOperatorCallConstValueParam(const ExpensiveToCopyContainer C) {
+  const auto AutoAssigned = C[42];
+  // CHECK-MESSAGES: [[@LINE-1]]:14: warning: the const qualified variable 
'AutoAssigned'
+  // CHECK-FIXES: const auto& AutoAssigned = C[42];
+  AutoAssigned.constMethod();
+
+  const auto AutoCopyConstructed(C[42]);
+  // CHECK-MESSAGES: [[@LINE-1]]:14: warning: the const qualified variable 
'AutoCopyConstructed'
+  // CHECK-FIXES: const auto& AutoCopyConstructed(C[42]);
+  AutoCopyConstructed.constMethod();
+
+  const ExpensiveToCopyType VarAssigned = C[42];
+  // CHECK-MESSAGES: [[@LINE-1]]:29: warning: the const qualified variable 
'VarAssigned'
+  // CHECK-FIXES: const ExpensiveToCopyType& VarAssigned = C[42];
+  VarAssigned.constMethod();
+
+  const ExpensiveToCopyType VarCopyConstructed(C[42]);
+  // CHECK-MESSAGES: [[@LINE-1]]:29: warning: the const qualified variable 
'VarCopyConstructed'
+  // CHECK-FIXES: const ExpensiveToCopyType& VarCopyConstructed(C[42]);
+  VarCopyConstructed.constMethod();
+}
+
 void PositiveLocalConstValue() {
   const ExpensiveToCopyType Obj;
   const auto UnnecessaryCopy = Obj.reference();
Index: 
clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp
===
--- clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp
+++ clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp
@@ -83,15 +83,19 @@
   // variable being declared. The assumption is that the const reference being
   // returned either points to a global static variable or to a member of the
   // called object.
-  return cxxMemberCallExpr(
-  callee(cxxMethodDecl(
- returns(hasCanonicalType(matchers::isReferenceToConst(
- .bind(MethodDeclId)),
-  on(declRefExpr(to(
-  varDecl(
-  
unless(hasType(qualType(hasCanonicalType(hasDeclaration(namedDecl(
-  matchers::matchesAnyListedName(ExcludedContainerTypes
-  .bind(ObjectArgId);
+  const auto MethodDecl =
+  cxxMethodDecl(returns(hasCanonicalType(matchers::isReferenceToConst(
+  .bind(MethodDeclId);
+  const auto ReceiverExpr = declRefExpr(to(varDecl().bind(ObjectArgId)));
+  const auto ReceiverTypeDecl =
+  
namedDecl(unless(matchers::matchesAnyListedName(ExcludedContainerTypes)

[PATCH] D113754: [Analyzer][Core] Simplify IntSym in SValBuilder

2021-11-19 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

Great news, thanks.




Comment at: clang/test/Analysis/svalbuilder-simplify-intsym.cpp:18
+return;
+  clang_analyzer_eval(x == 77); // expected-warning{{TRUE}}
+  (void)(x * y);

extra spaces?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113754

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


[PATCH] D114025: [clang][NFC] Inclusive terms: replace some uses of sanity in clang

2021-11-19 Thread Arthur O'Dwyer via Phabricator via cfe-commits
Quuxplusone added a comment.

(Re repeated thanks: You're welcome. :) For the record, I personally see 
nothing wrong with the phrase "sanity-check" either; but given that it's gonna 
happen, and we're re-wording comments on by definition the subtlest and most 
confusing parts of the code, I'm trying to help us not to lose/distort the 
semantics of those comments. Some of these comments are even //improving// 
through this exercise.)




Comment at: clang/include/clang/AST/Redeclarable.h:261
   assert(Current && "Advancing while iterator has reached end");
-  // Sanity check to avoid infinite loop on invalid redecl chain.
+  // Validation check to avoid infinite loop on invalid redecl chain.
   if (Current->isFirstDecl()) {

aaron.ballman wrote:
> Quuxplusone wrote:
> > `// Make sure we don't infinite-loop on an invalid redecl chain. This 
> > should never happen.`
> Alternatively, "Make sure we don't infinitely loop..."
s/on on/on an/
Also, I think comments should always end with a period `.`, or is it the other 
way around? :)



Comment at: clang/include/clang/Sema/Lookup.h:709-710
 
-  // Sanity checks.
+  // Validation checks.
   bool sanity() const;
 

Quuxplusone wrote:
> The original comment strikes me as pretty useless, except that it's kind of 
> obliquely explaining the meaning of the ungrammatical `bool sanity() const`. 
> It could have been fixed better, pre-PC, by just removing the comment and 
> changing the function to `bool isSane() const`. I have no particular 
> suggestion for this one, other than "you'll have to look at how it's used" 
> and/or "just leave the comment alone, until you're ready to rename the actual 
> identifiers too" and/or "just delete the comment because it's useless."
The new version has the problem that `check()` is really vague, which again 
means that in order to explain what it does, you have to use the term 
"sanity-check". ;)  Perhaps change the identifier to `checkAssumptions()` or 
even `checkDebugAssumptions()`?
(Pre-existing problem: the name of the function still doesn't describe what it 
does, because it doesn't //check// or //assert// anything; it simply returns 
true or false, and it's up to the caller to `assert` on the return value. But 
`conformsToAssumptions()` is a silly name.)



Comment at: clang/lib/Basic/DiagnosticIDs.cpp:695
   StringRef Best;
-  unsigned BestDistance = Group.size() + 1; // Sanity threshold.
+  unsigned BestDistance = Group.size() + 1; // Minumum threshold.
   for (const WarningOption &O : OptionTable) {

`Minimum`, and also, I think it's a maximum? :P



Comment at: clang/lib/Sema/SemaDeclCXX.cpp:9176
   // Don't check the implicit member of the anonymous union type.
-  // This is technically non-conformant, but sanity demands it.
+  // This is technically non-conformant, but validation tests demand it.
   return false;

Quuxplusone wrote:
> Quuxplusone wrote:
> > This comment seems incorrectly translated.
> This comment //still// seems incorrectly translated.
> Things we do "for sanity's sake" aren't necessarily //required//, 
> technically; but we're doing them anyway, for sanity.
"Don't check ... but check it anyway"?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114025

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


[PATCH] D114251: [AST] Add a sugar type for types found via UsingDecl

2021-11-19 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
Herald added subscribers: dexonsmith, usaxena95, kadircet, arphaman, martong.
sammccall requested review of this revision.
Herald added projects: clang, clang-tools-extra.
Herald added a subscriber: cfe-commits.

WIP:

- needs tests of new functionality
- doesn't handle template names/instantiations (unsure if same mechanism)
- maybe we should unify with UnresolvedUsingType
- maybe we should unify with TypedefType


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D114251

Files:
  clang-tools-extra/clangd/FindTarget.cpp
  clang-tools-extra/clangd/IncludeCleaner.cpp
  clang-tools-extra/clangd/Selection.cpp
  clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
  clang-tools-extra/clangd/unittests/XRefsTests.cpp
  clang/include/clang/AST/ASTContext.h
  clang/include/clang/AST/RecursiveASTVisitor.h
  clang/include/clang/AST/Type.h
  clang/include/clang/AST/TypeLoc.h
  clang/include/clang/AST/TypeProperties.td
  clang/include/clang/Basic/TypeNodes.td
  clang/include/clang/Serialization/TypeBitCodes.def
  clang/lib/AST/ASTContext.cpp
  clang/lib/AST/ASTDiagnostic.cpp
  clang/lib/AST/ASTStructuralEquivalence.cpp
  clang/lib/AST/ItaniumMangle.cpp
  clang/lib/AST/Type.cpp
  clang/lib/AST/TypePrinter.cpp
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaTemplate.cpp
  clang/lib/Sema/TreeTransform.h
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/test/CXX/stmt.stmt/stmt.iter/stmt.ranged/p1.cpp
  clang/test/SemaCXX/warn-enum-compare.cpp
  clang/tools/libclang/CIndex.cpp
  clang/unittests/Tooling/StencilTest.cpp

Index: clang/unittests/Tooling/StencilTest.cpp
===
--- clang/unittests/Tooling/StencilTest.cpp
+++ clang/unittests/Tooling/StencilTest.cpp
@@ -559,7 +559,7 @@
 
 TEST_F(StencilTest, DescribeUnqualifiedType) {
   std::string Snippet = "using N::C; C c; c;";
-  std::string Expected = "N::C";
+  std::string Expected = "C";
   auto StmtMatch =
   matchStmt(Snippet, declRefExpr(hasType(qualType().bind("type";
   ASSERT_TRUE(StmtMatch);
Index: clang/tools/libclang/CIndex.cpp
===
--- clang/tools/libclang/CIndex.cpp
+++ clang/tools/libclang/CIndex.cpp
@@ -1666,6 +1666,10 @@
   return Visit(TL.getPointeeLoc());
 }
 
+bool CursorVisitor::VisitUsingTypeLoc(UsingTypeLoc TL) {
+  return Visit(TL.getUnderlyingLoc());
+}
+
 bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
   return Visit(TL.getModifiedLoc());
 }
Index: clang/test/SemaCXX/warn-enum-compare.cpp
===
--- clang/test/SemaCXX/warn-enum-compare.cpp
+++ clang/test/SemaCXX/warn-enum-compare.cpp
@@ -78,15 +78,15 @@
 
   while (B1 == B2); // expected-warning  {{comparison of different enumeration types ('name1::Baz' and 'name2::Baz')}}
   while (name1::B2 == name2::B3); // expected-warning  {{comparison of different enumeration types ('name1::Baz' and 'name2::Baz')}}
-  while (z == name2::B2); // expected-warning  {{comparison of different enumeration types ('name1::Baz' and 'name2::Baz')}}
+  while (z == name2::B2); // expected-warning  {{comparison of different enumeration types ('Baz' and 'name2::Baz')}}
 
   while (B1 == B2); // expected-warning  {{comparison of different enumeration types ('name1::Baz' and 'name2::Baz')}}
   while (name1::B2 == (name2::B3)); // expected-warning  {{comparison of different enumeration types ('name1::Baz' and 'name2::Baz')}}
-  while (z == name2::B2); // expected-warning  {{comparison of different enumeration types ('name1::Baz' and 'name2::Baz')}}
+  while (z == name2::B2); // expected-warning  {{comparison of different enumeration types ('Baz' and 'name2::Baz')}}
 
   while B1))) == (((B2; // expected-warning  {{comparison of different enumeration types ('name1::Baz' and 'name2::Baz')}}
   while ((name1::B2) == (((name2::B3; // expected-warning  {{comparison of different enumeration types ('name1::Baz' and 'name2::Baz')}}
-  while z))) == (name2::B2)); // expected-warning  {{comparison of different enumeration types ('name1::Baz' and 'name2::Baz')}}
+  while z))) == (name2::B2)); // expected-warning  {{comparison of different enumeration types ('Baz' and 'name2::Baz')}}
 
   while (x == a); // expected-warning  {{comparison of different enumeration types ('Foo' and 'name1::Foo')}}
   while (x == b); // expected-warning  {{comparison of different enumeration types ('Foo' and 'oneFoo' (aka 'name1::Foo'))}}
@@ -229,14 +229,14 @@
   while (td == c); // expected-warning  {{comparison of different enumeration types ('TD' and 'twoFoo' (aka 'name1::Foo'))}}
   while (td == x); // expected-warning  {{comparison of different enumeration types ('TD' and 'Foo')}}
   while (td == y); // ex

[PATCH] D114108: [NFC][clang] Inclusive language: rename master variable to controller in debug-info-block-helper.m

2021-11-19 Thread Quinn Pham via Phabricator via cfe-commits
quinnp updated this revision to Diff 388511.
quinnp added a comment.

Changing master to controller in another testcase.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114108

Files:
  clang/test/CodeGenObjC/debug-info-block-helper.m
  cross-project-tests/debuginfo-tests/llgdb-tests/blocks.m


Index: cross-project-tests/debuginfo-tests/llgdb-tests/blocks.m
===
--- cross-project-tests/debuginfo-tests/llgdb-tests/blocks.m
+++ cross-project-tests/debuginfo-tests/llgdb-tests/blocks.m
@@ -11,7 +11,7 @@
 // CHECK: ${{[0-9]}} = 1
 // DEBUGGER: p dbTransaction
 // CHECK: ${{[0-9]}} = 0
-// DEBUGGER: p master
+// DEBUGGER: p controller
 // CHECK: ${{[0-9]}} = 0
 
 #include 
@@ -21,16 +21,16 @@
 @interface A:NSObject @end
 @implementation A
 - (void) helper {
- int master = 0;
+ int controller = 0;
  __block int m2 = 0;
  __block int dbTransaction = 0;
  int (^x)(void) = ^(void) { (void) self; 
-   (void) master; 
+   (void) controller; 
(void) dbTransaction; 
m2++;
return m2;
};
-  master = x();
+  controller = x();
 }
 @end
 
Index: clang/test/CodeGenObjC/debug-info-block-helper.m
===
--- clang/test/CodeGenObjC/debug-info-block-helper.m
+++ clang/test/CodeGenObjC/debug-info-block-helper.m
@@ -12,17 +12,17 @@
 @interface A:NSObject @end
 @implementation A
 - (void) helper {
- int master = 0;
+ int controller = 0;
  __block int m2 = 0;
  __block int dbTransaction = 0;
  int (^x)(void) = ^(void) { (void) self; 
-   (void) master; 
+   (void) controller; 
(void) dbTransaction; 
m2++;
return m2;
 
};
-  master = x();
+  controller = x();
 }
 @end
 


Index: cross-project-tests/debuginfo-tests/llgdb-tests/blocks.m
===
--- cross-project-tests/debuginfo-tests/llgdb-tests/blocks.m
+++ cross-project-tests/debuginfo-tests/llgdb-tests/blocks.m
@@ -11,7 +11,7 @@
 // CHECK: ${{[0-9]}} = 1
 // DEBUGGER: p dbTransaction
 // CHECK: ${{[0-9]}} = 0
-// DEBUGGER: p master
+// DEBUGGER: p controller
 // CHECK: ${{[0-9]}} = 0
 
 #include 
@@ -21,16 +21,16 @@
 @interface A:NSObject @end
 @implementation A
 - (void) helper {
- int master = 0;
+ int controller = 0;
  __block int m2 = 0;
  __block int dbTransaction = 0;
  int (^x)(void) = ^(void) { (void) self; 
-	(void) master; 
+	(void) controller; 
 	(void) dbTransaction; 
 	m2++;
 	return m2;
 	};
-  master = x();
+  controller = x();
 }
 @end
 
Index: clang/test/CodeGenObjC/debug-info-block-helper.m
===
--- clang/test/CodeGenObjC/debug-info-block-helper.m
+++ clang/test/CodeGenObjC/debug-info-block-helper.m
@@ -12,17 +12,17 @@
 @interface A:NSObject @end
 @implementation A
 - (void) helper {
- int master = 0;
+ int controller = 0;
  __block int m2 = 0;
  __block int dbTransaction = 0;
  int (^x)(void) = ^(void) { (void) self; 
-	(void) master; 
+	(void) controller; 
 	(void) dbTransaction; 
 	m2++;
 	return m2;
 
 	};
-  master = x();
+  controller = x();
 }
 @end
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D114116: [clang][ARM] relax -mtp=cp15 for ARMv6 non-thumb cases

2021-11-19 Thread Peter Smith via Phabricator via cfe-commits
peter.smith added inline comments.



Comment at: clang/lib/Driver/ToolChains/Arch/ARM.cpp:155
+  llvm::ARM::ArchKind AK = llvm::ARM::parseArch(Triple.getArchName());
+  return Ver >= 7 || AK == llvm::ARM::ArchKind::ARMV6T2 ||
+ (Ver == 6 && Triple.isARM());

nickdesaulniers wrote:
> ardb wrote:
> > peter.smith wrote:
> > > Are we restricting based on whether the threadid register is present or 
> > > whether the instructions are available to access the cp15 registers?
> > > 
> > > If we're going by whether the CPU has the register present then it will be
> > > * A and R profile (not M profile, even the ones that have Thumb2)
> > > * V6K (includes ARM1176 but not ARM1156t2-s which has Thumb-2!) and V7+ 
> > > (A and R profile)
> > > 
> > > If we're going by the instructions to write to CP15 then it is:
> > > * Arm state (everything)
> > > * Thumb2 (v7 + v6t2)
> > > 
> > > The above seems to be a blend of the two. Is it worth choosing one form 
> > > or the other? GCC seems to use the latter. I guess using this option 
> > > falls into the I know what I'm doing area that accessing named system 
> > > registers comes into. If the kernel supports it the stricter version may 
> > > help catch more mistakes though.
> > > 
> > > The v7 A/R Arm ARM https://developer.arm.com/documentation/ddi0403/ed
> > > has in `D12.7.21 CP15 c13, Context ID support`
> > > ``` An ARMv6K implementation requires the Software Thread ID registers 
> > > described in VMSA CP15 c13
> > > register summary, Process, context and thread ID registers on page 
> > > B3-1474. ```
> > > 
> > > The Arm 1156-s (the only v6t2 processor) TRM 
> > > https://developer.arm.com/documentation/ddi0338/g/system-control-coprocessor/system-control-processor-registers/c13--process-id-register?lang=en
> > >  which shows only one process ID register under opcode 1 accessed via:
> > > ```
> > > MRC p15, 0, , c13, c0, 1 ;Read Process ID Register
> > > ```
> > > Whereas the ThreadID register is opcode 3 on CPUs that are v6k and v7.
> > The primary reason for tightening these checks was to avoid an assert in 
> > the backend when using -mtp=cp15 with a Thumb1 target, so I'd say this is 
> > more about whether the ISA has the opcode to begin with, rather than 
> > whether CPU x implements it or not.
> > Arm state (everything)
> 
> 
> Does that mean that `-march=armv5 -marm` has access/support for "CP15 C13 
> ThreadID" access?
The co-processor instructions are the same, but the effect of the instructions 
will depend on the CPU. For example on armv5 we can write the instruction to 
read/write to CP15 C13 with the ThreadID opcode. However on no armv5 
implementation will the CP15 C13 have a Thread ID register. 

The more complex stricter check will make sure that the implementations have 
the ThreadID register. As Ard mentions, the GCC intent seems to be whether the 
instruction is encodable rather than check what the CPU supports. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114116

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


[PATCH] D103094: [analyzer] Implemented RangeSet::Factory::castTo function to perform promotions, truncations and conversions

2021-11-19 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov updated this revision to Diff 388512.
ASDenysPetrov added a comment.

Fixed missed part during rebasing in the unit test.


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

https://reviews.llvm.org/D103094

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h
  
clang/include/clang/StaticAnalyzer/Core/PathSensitive/RangedConstraintManager.h
  clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
  clang/unittests/StaticAnalyzer/RangeSetTest.cpp

Index: clang/unittests/StaticAnalyzer/RangeSetTest.cpp
===
--- clang/unittests/StaticAnalyzer/RangeSetTest.cpp
+++ clang/unittests/StaticAnalyzer/RangeSetTest.cpp
@@ -40,12 +40,18 @@
   const Range &R) {
   return OS << toString(R);
 }
+LLVM_ATTRIBUTE_UNUSED static std::ostream &operator<<(std::ostream &OS,
+  APSIntType Ty) {
+  return OS << (Ty.isUnsigned() ? "u" : "s") << Ty.getBitWidth();
+}
 
 } // namespace ento
 } // namespace clang
 
 namespace {
 
+template  constexpr bool is_signed_v = std::is_signed::value;
+
 template  struct TestValues {
   static constexpr T MIN = std::numeric_limits::min();
   static constexpr T MAX = std::numeric_limits::max();
@@ -53,7 +59,7 @@
   // which unary minus does not affect on,
   // e.g. int8/int32(0), uint8(128), uint32(2147483648).
   static constexpr T MID =
-  std::is_signed::value ? 0 : ~(static_cast(-1) / static_cast(2));
+  is_signed_v ? 0 : ~(static_cast(-1) / static_cast(2));
   static constexpr T A = MID - (MAX - MID) / 3 * 2;
   static constexpr T B = MID - (MAX - MID) / 3;
   static constexpr T C = -B;
@@ -61,8 +67,40 @@
 
   static_assert(MIN < A && A < B && B < MID && MID < C && C < D && D < MAX,
 "Values shall be in an ascending order");
+  // Clear bits in low bytes by the given amount.
+  template 
+  static constexpr T ClearLowBytes =
+  static_cast(static_cast(Value)
+ << ((Bytes >= CHAR_BIT) ? 0 : Bytes) * CHAR_BIT);
+
+  template 
+  static constexpr T TruncZeroOf = ClearLowBytes;
+
+  // Random number with active bits in every byte. 0x'
+  static constexpr T XAAA = static_cast(
+  0b10101010'10101010'10101010'10101010'10101010'10101010'10101010'10101010);
+  template 
+  static constexpr T XAAATruncZeroOf = TruncZeroOf; // 0x'AB00
+
+  // Random number with active bits in every byte. 0x'
+  static constexpr T X555 = static_cast(
+  0b01010101'01010101'01010101'01010101'01010101'01010101'01010101'01010101);
+  template 
+  static constexpr T X555TruncZeroOf = TruncZeroOf; // 0x'5600
+
+  // Numbers for ranges with the same bits in the lowest byte.
+  // 0x'AA2A
+  static constexpr T FromA = ClearLowBytes + 42;
+  static constexpr T ToA = FromA + 2; // 0x'AA2C
+  // 0x'552A
+  static constexpr T FromB = ClearLowBytes + 42;
+  static constexpr T ToB = FromB + 2; // 0x'552C
 };
 
+template 
+static constexpr APSIntType APSIntTy = APSIntType(sizeof(T) * CHAR_BIT,
+  !is_signed_v);
+
 template  class RangeSetTest : public testing::Test {
 public:
   // Init block
@@ -74,21 +112,24 @@
   // End init block
 
   using Self = RangeSetTest;
-  using RawRange = std::pair;
-  using RawRangeSet = std::initializer_list;
-
-  const llvm::APSInt &from(BaseType X) {
-static llvm::APSInt Base{sizeof(BaseType) * CHAR_BIT,
- std::is_unsigned::value};
-Base = X;
-return BVF.getValue(Base);
+  template  using RawRangeT = std::pair;
+  template 
+  using RawRangeSetT = std::initializer_list>;
+  using RawRange = RawRangeT;
+  using RawRangeSet = RawRangeSetT;
+
+  template  const llvm::APSInt &from(T X) {
+static llvm::APSInt Int = APSIntTy.getZeroValue();
+Int = X;
+return BVF.getValue(Int);
   }
 
-  Range from(const RawRange &Init) {
+  template  Range from(const RawRangeT &Init) {
 return Range(from(Init.first), from(Init.second));
   }
 
-  RangeSet from(const RawRangeSet &Init) {
+  template 
+  RangeSet from(RawRangeSetT Init, APSIntType Ty = APSIntTy) {
 RangeSet RangeSet = F.getEmptySet();
 for (const auto &Raw : Init) {
   RangeSet = F.add(RangeSet, from(Raw));
@@ -211,9 +252,20 @@
RawRangeSet RawExpected) {
 wrap(&Self::checkDeleteImpl, Point, RawFrom, RawExpected);
   }
-};
 
-} // namespace
+  void checkCastToImpl(RangeSet What, APSIntType Ty, RangeSet Expected) {
+RangeSet Result = F.castTo(What, Ty);
+EXPECT_EQ(Result, Expected)
+<< "while casting " << toString(What) << " to " << Ty;
+  }
+
+  template 
+  void checkCastTo(RawRangeSetT What, RawRangeSetT Expected) {
+static constexpr APSIntType FromTy = APSIntTy;
+static constexpr APSIntType ToTy = APSIntTy;
+this->checkCastToImpl(from(What, FromTy), ToTy, from(Expected, ToTy))

[Diffusion] rGc93f93b2e3f2: Revert "Revert "Recommit "Revert "[CVP] processSwitch: Remove default case when…

2021-11-19 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh added subscribers: cfe-commits, alexfh, bgraur.

BRANCHES
  main

Users:
  junparser (Author)

https://reviews.llvm.org/rGc93f93b2e3f2

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


[PATCH] D114254: [libtooling][clang-tidy] Fix crashing on rendering invalid SourceRanges

2021-11-19 Thread Balázs Benics via Phabricator via cfe-commits
steakhal created this revision.
steakhal added reviewers: aaron.ballman, njames93, klimek, alexfh.
Herald added subscribers: carlosgalvezp, martong, xazax.hun.
steakhal requested review of this revision.
Herald added a project: clang-tools-extra.
Herald added a subscriber: cfe-commits.

Invalid SourceRanges can occur generally if the code does not compile,
thus we expect clang error diagnostics.
Unlike `clang`, `clang-tidy` did not swallow invalid source ranges, but
tried to highlight them, and blow various assertions.

The following two examples produce invalid source ranges, but this is
not a complete list:

  void test(x); // error: unknown type name 'x'
  struct Foo {
member; // error: C++ requires a type specifier for all declarations
  };

Thanks @Whisperity helping me fix this.


https://reviews.llvm.org/D114254

Files:
  clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
  clang-tools-extra/test/clang-tidy/infrastructure/export-diagnostics.cpp
  clang-tools-extra/unittests/clang-tidy/ClangTidyDiagnosticConsumerTest.cpp

Index: clang-tools-extra/unittests/clang-tidy/ClangTidyDiagnosticConsumerTest.cpp
===
--- clang-tools-extra/unittests/clang-tidy/ClangTidyDiagnosticConsumerTest.cpp
+++ clang-tools-extra/unittests/clang-tidy/ClangTidyDiagnosticConsumerTest.cpp
@@ -37,6 +37,33 @@
   }
 };
 
+class InvalidRangeTestCheck : public ClangTidyCheck {
+public:
+  InvalidRangeTestCheck(StringRef Name, ClangTidyContext *Context)
+  : ClangTidyCheck(Name, Context) {}
+  void registerMatchers(ast_matchers::MatchFinder *Finder) override {
+Finder->addMatcher(ast_matchers::varDecl().bind("var"), this);
+  }
+  void check(const ast_matchers::MatchFinder::MatchResult &Result) override {
+const auto *Var = Result.Nodes.getNodeAs("var");
+SourceLocation ValidBeginLoc = Var->getBeginLoc();
+SourceLocation ValidEndLoc = Var->getEndLoc();
+SourceLocation InvalidLoc;
+ASSERT_TRUE(ValidBeginLoc.isValid());
+ASSERT_TRUE(ValidEndLoc.isValid());
+ASSERT_TRUE(InvalidLoc.isInvalid());
+
+diag(ValidBeginLoc, "valid->valid")
+<< SourceRange(ValidBeginLoc, ValidEndLoc);
+diag(ValidBeginLoc, "valid->invalid")
+<< SourceRange(ValidBeginLoc, InvalidLoc);
+diag(ValidBeginLoc, "invalid->valid")
+<< SourceRange(InvalidLoc, ValidEndLoc);
+diag(ValidBeginLoc, "invalid->invalid")
+<< SourceRange(InvalidLoc, InvalidLoc);
+  }
+};
+
 } // namespace
 
 TEST(ClangTidyDiagnosticConsumer, SortsErrors) {
@@ -66,6 +93,24 @@
   EXPECT_EQ(7ul, Errors[0].Message.Ranges[0].Length);
 }
 
+TEST(ClangTidyDiagnosticConsumer, InvalidSourceLocationRangesIgnored) {
+  std::vector Errors;
+  runCheckOnCode("int x;", &Errors);
+  EXPECT_EQ(4ul, Errors.size());
+
+  EXPECT_EQ("invalid->invalid", Errors[0].Message.Message);
+  EXPECT_EQ(0ul, Errors[0].Message.Ranges.size());
+
+  EXPECT_EQ("invalid->valid", Errors[1].Message.Message);
+  EXPECT_EQ(0ul, Errors[1].Message.Ranges.size());
+
+  EXPECT_EQ("valid->invalid", Errors[2].Message.Message);
+  EXPECT_EQ(0ul, Errors[2].Message.Ranges.size());
+
+  EXPECT_EQ("valid->valid", Errors[3].Message.Message);
+  EXPECT_EQ(1ul, Errors[3].Message.Ranges.size());
+}
+
 } // namespace test
 } // namespace tidy
 } // namespace clang
Index: clang-tools-extra/test/clang-tidy/infrastructure/export-diagnostics.cpp
===
--- clang-tools-extra/test/clang-tidy/infrastructure/export-diagnostics.cpp
+++ clang-tools-extra/test/clang-tidy/infrastructure/export-diagnostics.cpp
@@ -7,6 +7,11 @@
 int a[-1];
 int b[0];
 
+void test(x);
+struct Foo {
+  member;
+};
+
 // CHECK-MESSAGES: -input.cpp:2:1: warning: no previous prototype for function 'ff' [clang-diagnostic-missing-prototypes]
 // CHECK-MESSAGES: -input.cpp:1:19: note: expanded from macro 'X'
 // CHECK-MESSAGES: {{^}}note: expanded from here{{$}}
@@ -14,6 +19,8 @@
 // CHECK-MESSAGES: -input.cpp:1:14: note: expanded from macro 'X'
 // CHECK-MESSAGES: -input.cpp:3:7: error: 'a' declared as an array with a negative size [clang-diagnostic-error]
 // CHECK-MESSAGES: -input.cpp:4:7: warning: zero size arrays are an extension [clang-diagnostic-zero-length-array]
+// CHECK-MESSAGES: -input.cpp:6:11: error: unknown type name 'x' [clang-diagnostic-error]
+// CHECK-MESSAGES: -input.cpp:8:3: error: C++ requires a type specifier for all declarations [clang-diagnostic-error]
 
 // CHECK-YAML: ---
 // CHECK-YAML-NEXT: MainSourceFile:  '{{.*}}-input.cpp'
@@ -71,4 +78,20 @@
 // CHECK-YAML-NEXT:  Length:  1
 // CHECK-YAML-NEXT: Level:   Warning
 // CHECK-YAML-NEXT: BuildDirectory:  '{{.*}}'
+// CHECK-YAML-NEXT:   - DiagnosticName:  clang-diagnostic-error
+// CHECK-YAML-NEXT: DiagnosticMessage:
+// CHECK-YAML-NEXT:   Message: 'unknown type name ''x'''
+// CHECK-YAML-NEXT:   FilePath:'{{.*}}-input.cpp'
+// CHECK-YAML

[PATCH] D114256: [clang-tidy] Fix crashing altera-struct-pack-align on invalid RecordDecls

2021-11-19 Thread Balázs Benics via Phabricator via cfe-commits
steakhal created this revision.
steakhal added reviewers: ffrankies, aaron.ballman, alexfh, njames93.
Herald added subscribers: carlosgalvezp, martong, xazax.hun.
steakhal requested review of this revision.
Herald added a project: clang-tools-extra.
Herald added a subscriber: cfe-commits.

https://reviews.llvm.org/D114256

Files:
  clang-tools-extra/clang-tidy/altera/StructPackAlignCheck.cpp
  
clang-tools-extra/test/clang-tidy/checkers/altera-struct-pack-align-invalid-decl-no-crash.cpp


Index: 
clang-tools-extra/test/clang-tidy/checkers/altera-struct-pack-align-invalid-decl-no-crash.cpp
===
--- /dev/null
+++ 
clang-tools-extra/test/clang-tidy/checkers/altera-struct-pack-align-invalid-decl-no-crash.cpp
@@ -0,0 +1,8 @@
+// RUN: %check_clang_tidy -expect-clang-tidy-error %s altera-struct-pack-align 
%t -- -header-filter=.*
+
+// This should not crash.
+
+struct Foo {
+  member;
+};
+// CHECK-MESSAGES: :[[@LINE-2]]:3: error: C++ requires a type specifier for 
all declarations [clang-diagnostic-error]
Index: clang-tools-extra/clang-tidy/altera/StructPackAlignCheck.cpp
===
--- clang-tools-extra/clang-tidy/altera/StructPackAlignCheck.cpp
+++ clang-tools-extra/clang-tidy/altera/StructPackAlignCheck.cpp
@@ -51,6 +51,10 @@
   if (Struct->isTemplated())
  return;
 
+  // Ignore invalid decls to prevent crashing on calling `getASTRecordLayout`.
+  if (Struct->isInvalidDecl())
+return;
+
   // Get sizing info for the struct.
   llvm::SmallVector, 10> FieldSizes;
   unsigned int TotalBitSize = 0;


Index: clang-tools-extra/test/clang-tidy/checkers/altera-struct-pack-align-invalid-decl-no-crash.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/altera-struct-pack-align-invalid-decl-no-crash.cpp
@@ -0,0 +1,8 @@
+// RUN: %check_clang_tidy -expect-clang-tidy-error %s altera-struct-pack-align %t -- -header-filter=.*
+
+// This should not crash.
+
+struct Foo {
+  member;
+};
+// CHECK-MESSAGES: :[[@LINE-2]]:3: error: C++ requires a type specifier for all declarations [clang-diagnostic-error]
Index: clang-tools-extra/clang-tidy/altera/StructPackAlignCheck.cpp
===
--- clang-tools-extra/clang-tidy/altera/StructPackAlignCheck.cpp
+++ clang-tools-extra/clang-tidy/altera/StructPackAlignCheck.cpp
@@ -51,6 +51,10 @@
   if (Struct->isTemplated())
  return;
 
+  // Ignore invalid decls to prevent crashing on calling `getASTRecordLayout`.
+  if (Struct->isInvalidDecl())
+return;
+
   // Get sizing info for the struct.
   llvm::SmallVector, 10> FieldSizes;
   unsigned int TotalBitSize = 0;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] d448fcd - [analyzer][NFC] Introduce CallDescriptionSets

2021-11-19 Thread Balazs Benics via cfe-commits

Author: Balazs Benics
Date: 2021-11-19T18:32:13+01:00
New Revision: d448fcd9b2238377dd8832ce9e35a37b59ef5aeb

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

LOG: [analyzer][NFC] Introduce CallDescriptionSets

Sometimes we only want to decide if some function is called, and we
don't care which of the set.
This `CallDescriptionSet` will have the same behavior, except
instead of `lookup()` returning a pointer to the mapped value,
the `contains()` returns `bool`.
Internally, it uses the `CallDescriptionMap` for implementing the
behavior. It is preferred, to reuse the generic
`CallDescriptionMap::lookup()` logic, instead of duplicating it.
The generic version might be improved by implementing a hash lookup or
something along those lines.

Reviewed By: martong, Szelethus

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

Added: 


Modified: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
clang/lib/StaticAnalyzer/Core/CallDescription.cpp

Removed: 




diff  --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
index bbf58d753b1f6..b34e1c82eb7d6 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
@@ -88,6 +88,8 @@ class CallDescription {
 /// An immutable map from CallDescriptions to arbitrary data. Provides a 
unified
 /// way for checkers to react on function calls.
 template  class CallDescriptionMap {
+  friend class CallDescriptionSet;
+
   // Some call descriptions aren't easily hashable (eg., the ones with 
qualified
   // names in which some sections are omitted), so let's put them
   // in a simple vector and use linear lookup.
@@ -118,6 +120,21 @@ template  class CallDescriptionMap {
   }
 };
 
+/// An immutable set of CallDescriptions.
+/// Checkers can efficiently decide if a given CallEvent matches any
+/// CallDescription in the set.
+class CallDescriptionSet {
+  CallDescriptionMap Impl = {};
+
+public:
+  CallDescriptionSet(std::initializer_list &&List);
+
+  CallDescriptionSet(const CallDescriptionSet &) = delete;
+  CallDescriptionSet &operator=(const CallDescription &) = delete;
+
+  LLVM_NODISCARD bool contains(const CallEvent &Call) const;
+};
+
 } // namespace ento
 } // namespace clang
 

diff  --git a/clang/lib/StaticAnalyzer/Core/CallDescription.cpp 
b/clang/lib/StaticAnalyzer/Core/CallDescription.cpp
index 0589a2c2cb980..097cbf68f0660 100644
--- a/clang/lib/StaticAnalyzer/Core/CallDescription.cpp
+++ b/clang/lib/StaticAnalyzer/Core/CallDescription.cpp
@@ -46,3 +46,14 @@ ento::CallDescription::CallDescription(
 Optional RequiredArgs /*= None*/,
 Optional RequiredParams /*= None*/)
 : CallDescription(0, QualifiedName, RequiredArgs, RequiredParams) {}
+
+ento::CallDescriptionSet::CallDescriptionSet(
+std::initializer_list &&List) {
+  Impl.LinearMap.reserve(List.size());
+  for (const CallDescription &CD : List)
+Impl.LinearMap.push_back({CD, /*unused*/ true});
+}
+
+bool ento::CallDescriptionSet::contains(const CallEvent &Call) const {
+  return static_cast(Impl.lookup(Call));
+}



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


[clang] 6c51270 - [analyzer][NFC] Introduce CallDescription::matches() in addition to isCalled()

2021-11-19 Thread Balazs Benics via cfe-commits

Author: Balazs Benics
Date: 2021-11-19T18:32:13+01:00
New Revision: 6c512703a9e6e495afa0f44528821c27f28db795

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

LOG: [analyzer][NFC] Introduce CallDescription::matches() in addition to 
isCalled()

This patch introduces `CallDescription::matches()` member function,
accepting a `CallEvent`.
Semantically, `Call.isCalled(CD)` is the same as `CD.matches(Call)`.

The patch also introduces the `matchesAny()` variadic free function template.
It accepts a `CallEvent` and at least one `CallDescription` to match
against.

Reviewed By: martong

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

Added: 


Modified: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
clang/lib/StaticAnalyzer/Core/CallDescription.cpp
clang/lib/StaticAnalyzer/Core/CallEvent.cpp

Removed: 




diff  --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
index b34e1c82eb7d..a35a5fb912eb 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
@@ -83,6 +83,33 @@ class CallDescription {
   /// It's false, if and only if we expect a single identifier, such as
   /// `getenv`. It's true for `std::swap`, or `my::detail::container::data`.
   bool hasQualifiedNameParts() const { return QualifiedName.size() > 1; }
+
+  /// @name Matching CallDescriptions against a CallEvent
+  /// @{
+
+  /// Returns true if the CallEvent is a call to a function that matches
+  /// the CallDescription.
+  ///
+  /// \note This function is not intended to be used to match Obj-C method
+  /// calls.
+  bool matches(const CallEvent &Call) const;
+
+  /// Returns true whether the CallEvent matches on any of the CallDescriptions
+  /// supplied.
+  ///
+  /// \note This function is not intended to be used to match Obj-C method
+  /// calls.
+  friend bool matchesAny(const CallEvent &Call, const CallDescription &CD1) {
+return CD1.matches(Call);
+  }
+
+  /// \copydoc clang::ento::matchesAny(const CallEvent &, const 
CallDescription &)
+  template 
+  friend bool matchesAny(const CallEvent &Call, const CallDescription &CD1,
+ const Ts &...CDs) {
+return CD1.matches(Call) || matchesAny(Call, CDs...);
+  }
+  /// @}
 };
 
 /// An immutable map from CallDescriptions to arbitrary data. Provides a 
unified
@@ -113,7 +140,7 @@ template  class CallDescriptionMap {
 // Slow path: linear lookup.
 // TODO: Implement some sort of fast path.
 for (const std::pair &I : LinearMap)
-  if (Call.isCalled(I.first))
+  if (I.first.matches(Call))
 return &I.second;
 
 return nullptr;

diff  --git a/clang/lib/StaticAnalyzer/Core/CallDescription.cpp 
b/clang/lib/StaticAnalyzer/Core/CallDescription.cpp
index 097cbf68f066..3ab54de96f3f 100644
--- a/clang/lib/StaticAnalyzer/Core/CallDescription.cpp
+++ b/clang/lib/StaticAnalyzer/Core/CallDescription.cpp
@@ -14,6 +14,7 @@
 
 #include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/Optional.h"
 
@@ -47,6 +48,88 @@ ento::CallDescription::CallDescription(
 Optional RequiredParams /*= None*/)
 : CallDescription(0, QualifiedName, RequiredArgs, RequiredParams) {}
 
+bool ento::CallDescription::matches(const CallEvent &Call) const {
+  // FIXME: Add ObjC Message support.
+  if (Call.getKind() == CE_ObjCMessage)
+return false;
+
+  const auto *FD = dyn_cast_or_null(Call.getDecl());
+  if (!FD)
+return false;
+
+  if (Flags & CDF_MaybeBuiltin) {
+return CheckerContext::isCLibraryFunction(FD, getFunctionName()) &&
+   (!RequiredArgs || RequiredArgs <= Call.getNumArgs()) &&
+   (!RequiredParams || RequiredParams <= Call.parameters().size());
+  }
+
+  if (!II.hasValue()) {
+II = &Call.getState()->getStateManager().getContext().Idents.get(
+getFunctionName());
+  }
+
+  const auto MatchNameOnly = [](const CallDescription &CD,
+const NamedDecl *ND) -> bool {
+DeclarationName Name = ND->getDeclName();
+if (const auto *II = Name.getAsIdentifierInfo())
+  return II == CD.II.getValue(); // Fast case.
+
+// Fallback to the slow stringification and comparison for:
+// C++ overloaded operators, constructors, destructors, etc.
+// FIXME This comparison is way SLOWER than comparing pointers.
+// At some point in the future, we should compare FunctionDecl pointers.
+return Name.getAsString(

[clang] f18da19 - [analyzer][NFC] Switch to using CallDescription::matches() instead of isCalled()

2021-11-19 Thread Balazs Benics via cfe-commits

Author: Balazs Benics
Date: 2021-11-19T18:32:13+01:00
New Revision: f18da190b0dba817d33ccd7727537f12304d8125

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

LOG: [analyzer][NFC] Switch to using CallDescription::matches() instead of 
isCalled()

This patch replaces each use of the previous API with the new one.
In variadic cases, it will use the ADL `matchesAny(Call, CDs...)`
variadic function.
Also simplifies some code involving such operations.

Reviewed By: martong, xazax.hun

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

Added: 


Modified: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp
clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
clang/lib/StaticAnalyzer/Checkers/ChrootChecker.cpp
clang/lib/StaticAnalyzer/Checkers/InnerPointerChecker.cpp
clang/lib/StaticAnalyzer/Checkers/MIGChecker.cpp
clang/lib/StaticAnalyzer/Checkers/MmapWriteExecChecker.cpp
clang/lib/StaticAnalyzer/Checkers/SimpleStreamChecker.cpp
clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
clang/lib/StaticAnalyzer/Checkers/StringChecker.cpp
clang/lib/StaticAnalyzer/Checkers/ValistChecker.cpp
clang/lib/StaticAnalyzer/Checkers/cert/PutenvWithAutoChecker.cpp
clang/lib/StaticAnalyzer/Core/CallEvent.cpp
clang/unittests/StaticAnalyzer/ConflictingEvalCallsTest.cpp
clang/unittests/StaticAnalyzer/NoStateChangeFuncVisitorTest.cpp

Removed: 




diff  --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
index 1e6b2457c706d..d135e70dd75dc 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
@@ -257,20 +257,6 @@ class CallEvent {
 return false;
   }
 
-  /// Returns true if the CallEvent is a call to a function that matches
-  /// the CallDescription.
-  ///
-  /// Note that this function is not intended to be used to match Obj-C method
-  /// calls.
-  bool isCalled(const CallDescription &CD) const;
-
-  /// Returns true whether the CallEvent is any of the CallDescriptions 
supplied
-  /// as a parameter.
-  template 
-  bool isCalled(const FirstCallDesc &First, const CallDescs &... Rest) const {
-return isCalled(First) || isCalled(Rest...);
-  }
-
   /// Returns a source range for the entire call, suitable for
   /// outputting in diagnostics.
   virtual SourceRange getSourceRange() const {

diff  --git a/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp 
b/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp
index 655facfed7d2e..ebd384a5a5b4c 100644
--- a/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp
@@ -551,8 +551,8 @@ void CFRetainReleaseChecker::checkPreCall(const CallEvent 
&Call,
 return;
 
   // Check if we called CFRetain/CFRelease/CFMakeCollectable/CFAutorelease.
-  if (!(Call.isCalled(CFRetain) || Call.isCalled(CFRelease) ||
-Call.isCalled(CFMakeCollectable) || Call.isCalled(CFAutorelease)))
+
+  if (!matchesAny(Call, CFRetain, CFRelease, CFMakeCollectable, CFAutorelease))
 return;
 
   // Get the argument's value.

diff  --git 
a/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
index 86f3d0ff0fea1..8416ab39e1943 100644
--- a/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
@@ -97,14 +97,7 @@ void 
BlockInCriticalSectionChecker::initIdentifierInfo(ASTContext &Ctx) const {
 }
 
 bool BlockInCriticalSectionChecker::isBlockingFunction(const CallEvent &Call) 
const {
-  if (Call.isCalled(SleepFn)
-  || Call.isCalled(GetcFn)
-  || Call.isCalled(FgetsFn)
-  || Call.isCalled(ReadFn)
-  || Call.isCalled(RecvFn)) {
-return true;
-  }
-  return false;
+  return matchesAny(Call, SleepFn, GetcFn, FgetsFn, ReadFn, RecvFn);
 }
 
 bool BlockInCriticalSectionChecker::isLockFunction(const CallEvent &Call) 
const {
@@ -114,15 +107,8 @@ bool BlockInCriticalSectionChecker::isLockFunction(const 
CallEvent &Call) const
   return true;
   }
 
-  if (Call.isCalled(LockFn)
-  || Call.isCalled(PthreadLockFn)
-  || Call.isCalled(PthreadTryLockFn)
-  || Call.isCalled(MtxLock)
-  || Call.isCalled(MtxTimedLock)
-  || Call.isCalled(MtxTryLock)) {
-return true;
-  }
-  return false;
+  return matchesAny(Call, LockFn, PthreadLockFn, PthreadTryLockFn, MtxLock,
+

[clang] 9ad0a90 - [analyzer][NFC] Demonstrate the use of CallDescriptionSet

2021-11-19 Thread Balazs Benics via cfe-commits

Author: Balazs Benics
Date: 2021-11-19T18:32:13+01:00
New Revision: 9ad0a90baa8ca8067fe65086056fffd083c86796

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

LOG: [analyzer][NFC] Demonstrate the use of CallDescriptionSet

Reviewed By: martong, xazax.hun

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

Added: 


Modified: 
clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp 
b/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp
index ebd384a5a5b4..2c210fb6cdb9 100644
--- a/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp
@@ -534,10 +534,12 @@ void CFNumberChecker::checkPreStmt(const CallExpr *CE,
 namespace {
 class CFRetainReleaseChecker : public Checker {
   mutable APIMisuse BT{this, "null passed to CF memory management function"};
-  CallDescription CFRetain{"CFRetain", 1},
-  CFRelease{"CFRelease", 1},
-  CFMakeCollectable{"CFMakeCollectable", 1},
-  CFAutorelease{"CFAutorelease", 1};
+  const CallDescriptionSet ModelledCalls = {
+  {"CFRetain", 1},
+  {"CFRelease", 1},
+  {"CFMakeCollectable", 1},
+  {"CFAutorelease", 1},
+  };
 
 public:
   void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
@@ -551,8 +553,7 @@ void CFRetainReleaseChecker::checkPreCall(const CallEvent 
&Call,
 return;
 
   // Check if we called CFRetain/CFRelease/CFMakeCollectable/CFAutorelease.
-
-  if (!matchesAny(Call, CFRetain, CFRelease, CFMakeCollectable, CFAutorelease))
+  if (!ModelledCalls.contains(Call))
 return;
 
   // Get the argument's value.



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


[clang] de9d7e4 - [analyzer][NFC] CallDescription should own the qualified name parts

2021-11-19 Thread Balazs Benics via cfe-commits

Author: Balazs Benics
Date: 2021-11-19T18:32:13+01:00
New Revision: de9d7e42aca29920e9918ecaed4ad9c45fa673f1

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

LOG: [analyzer][NFC] CallDescription should own the qualified name parts

Previously, CallDescription simply referred to the qualified name parts
by `const char*` pointers.
In the future we might want to dynamically load and populate
`CallDescriptionMaps`, hence we will need the `CallDescriptions` to
actually **own** their qualified name parts.

Reviewed By: martong, xazax.hun

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

Added: 


Modified: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
clang/lib/StaticAnalyzer/Core/CallDescription.cpp

Removed: 




diff  --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
index a35a5fb912eb..abc2b93e32fe 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
@@ -43,7 +43,7 @@ class CallDescription {
   mutable Optional II;
   // The list of the qualified names used to identify the specified CallEvent,
   // e.g. "{a, b}" represent the qualified names, like "a::b".
-  std::vector QualifiedName;
+  std::vector QualifiedName;
   Optional RequiredArgs;
   Optional RequiredParams;
   int Flags;

diff  --git a/clang/lib/StaticAnalyzer/Core/CallDescription.cpp 
b/clang/lib/StaticAnalyzer/Core/CallDescription.cpp
index 3ab54de96f3f..af541bdcfd59 100644
--- a/clang/lib/StaticAnalyzer/Core/CallDescription.cpp
+++ b/clang/lib/StaticAnalyzer/Core/CallDescription.cpp
@@ -17,6 +17,7 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/Optional.h"
+#include 
 
 using namespace llvm;
 using namespace clang;
@@ -35,10 +36,12 @@ ento::CallDescription::CallDescription(
 int Flags, ArrayRef QualifiedName,
 Optional RequiredArgs /*= None*/,
 Optional RequiredParams /*= None*/)
-: QualifiedName(QualifiedName), RequiredArgs(RequiredArgs),
+: RequiredArgs(RequiredArgs),
   RequiredParams(readRequiredParams(RequiredArgs, RequiredParams)),
   Flags(Flags) {
   assert(!QualifiedName.empty());
+  this->QualifiedName.reserve(QualifiedName.size());
+  llvm::copy(QualifiedName, std::back_inserter(this->QualifiedName));
 }
 
 /// Construct a CallDescription with default flags.



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


[clang] 97f1bf1 - [analyzer][NFC] Consolidate the inner representation of CallDescriptions

2021-11-19 Thread Balazs Benics via cfe-commits

Author: Balazs Benics
Date: 2021-11-19T18:32:13+01:00
New Revision: 97f1bf15b154ef32608fe17b82f2f312401d150c

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

LOG: [analyzer][NFC] Consolidate the inner representation of CallDescriptions

`CallDescriptions` have a `RequiredArgs` and `RequiredParams` members,
but they are of different types, `unsigned` and `size_t` respectively.
In the patch I use only `unsigned` for both, that should be large enough
anyway.
I also introduce the `MaybeUInt` type alias for `Optional`.

Additionally, I also avoid the use of the //smart// less-than operator.

  template 
  constexpr bool operator<=(const Optional &X, const T &Y);

Which would check if the optional **has** a value and compare the data
only after. I found it surprising, thus I think we are better off
without it.

Reviewed By: martong, xazax.hun

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

Added: 


Modified: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
clang/lib/StaticAnalyzer/Core/CallDescription.cpp

Removed: 




diff  --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
index abc2b93e32fe..88f67a03acfe 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
@@ -40,12 +40,14 @@ enum CallDescriptionFlags : int {
 /// arguments and the name of the function.
 class CallDescription {
   friend class CallEvent;
+  using MaybeUInt = Optional;
+
   mutable Optional II;
   // The list of the qualified names used to identify the specified CallEvent,
   // e.g. "{a, b}" represent the qualified names, like "a::b".
   std::vector QualifiedName;
-  Optional RequiredArgs;
-  Optional RequiredParams;
+  MaybeUInt RequiredArgs;
+  MaybeUInt RequiredParams;
   int Flags;
 
 public:
@@ -60,13 +62,13 @@ class CallDescription {
   /// call. Omit this parameter to match every occurrence of call with a given
   /// name regardless the number of arguments.
   CallDescription(int Flags, ArrayRef QualifiedName,
-  Optional RequiredArgs = None,
-  Optional RequiredParams = None);
+  MaybeUInt RequiredArgs = None,
+  MaybeUInt RequiredParams = None);
 
   /// Construct a CallDescription with default flags.
   CallDescription(ArrayRef QualifiedName,
-  Optional RequiredArgs = None,
-  Optional RequiredParams = None);
+  MaybeUInt RequiredArgs = None,
+  MaybeUInt RequiredParams = None);
 
   CallDescription(std::nullptr_t) = delete;
 

diff  --git a/clang/lib/StaticAnalyzer/Core/CallDescription.cpp 
b/clang/lib/StaticAnalyzer/Core/CallDescription.cpp
index af541bdcfd59..9274f8a41165 100644
--- a/clang/lib/StaticAnalyzer/Core/CallDescription.cpp
+++ b/clang/lib/StaticAnalyzer/Core/CallDescription.cpp
@@ -22,20 +22,22 @@
 using namespace llvm;
 using namespace clang;
 
+using MaybeUInt = Optional;
+
 // A constructor helper.
-static Optional readRequiredParams(Optional RequiredArgs,
-   Optional RequiredParams) {
+static MaybeUInt readRequiredParams(MaybeUInt RequiredArgs,
+MaybeUInt RequiredParams) {
   if (RequiredParams)
 return RequiredParams;
   if (RequiredArgs)
-return static_cast(*RequiredArgs);
+return RequiredArgs;
   return None;
 }
 
-ento::CallDescription::CallDescription(
-int Flags, ArrayRef QualifiedName,
-Optional RequiredArgs /*= None*/,
-Optional RequiredParams /*= None*/)
+ento::CallDescription::CallDescription(int Flags,
+   ArrayRef QualifiedName,
+   MaybeUInt RequiredArgs /*= None*/,
+   MaybeUInt RequiredParams /*= None*/)
 : RequiredArgs(RequiredArgs),
   RequiredParams(readRequiredParams(RequiredArgs, RequiredParams)),
   Flags(Flags) {
@@ -45,10 +47,9 @@ ento::CallDescription::CallDescription(
 }
 
 /// Construct a CallDescription with default flags.
-ento::CallDescription::CallDescription(
-ArrayRef QualifiedName,
-Optional RequiredArgs /*= None*/,
-Optional RequiredParams /*= None*/)
+ento::CallDescription::CallDescription(ArrayRef QualifiedName,
+   MaybeUInt RequiredArgs /*= None*/,
+   MaybeUInt RequiredParams /*= None*/)
 : CallDescription(0, QualifiedName, RequiredArgs, RequiredParams) {}
 
 bool ento::CallDescription::matches(const CallEvent &Call) const {
@@ -62,8 +63,8 @@ bool ento::CallDescripti

[clang] e6ef134 - [analyzer][NFC] Use enum for CallDescription flags

2021-11-19 Thread Balazs Benics via cfe-commits

Author: Balazs Benics
Date: 2021-11-19T18:32:13+01:00
New Revision: e6ef134f3c77005438f9fb7c1d17d3c30747844e

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

LOG: [analyzer][NFC] Use enum for CallDescription flags

Yeah, let's prefer a slightly stronger type representing this.

Reviewed By: martong, xazax.hun

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

Added: 


Modified: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
clang/lib/StaticAnalyzer/Checkers/ContainerModeling.cpp
clang/lib/StaticAnalyzer/Checkers/DebugContainerModeling.cpp
clang/lib/StaticAnalyzer/Checkers/DebugIteratorModeling.cpp
clang/lib/StaticAnalyzer/Core/CallDescription.cpp

Removed: 




diff  --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
index 88f67a03acfe..67db652a1e52 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
@@ -28,7 +28,9 @@ class IdentifierInfo;
 namespace clang {
 namespace ento {
 
-enum CallDescriptionFlags : int {
+enum CallDescriptionFlags : unsigned {
+  CDF_None = 0,
+
   /// Describes a C standard function that is sometimes implemented as a macro
   /// that expands to a compiler builtin with some __builtin prefix.
   /// The builtin may as well have a few extra arguments on top of the 
requested
@@ -61,7 +63,8 @@ class CallDescription {
   /// @param RequiredArgs The number of arguments that is expected to match a
   /// call. Omit this parameter to match every occurrence of call with a given
   /// name regardless the number of arguments.
-  CallDescription(int Flags, ArrayRef QualifiedName,
+  CallDescription(CallDescriptionFlags Flags,
+  ArrayRef QualifiedName,
   MaybeUInt RequiredArgs = None,
   MaybeUInt RequiredParams = None);
 

diff  --git a/clang/lib/StaticAnalyzer/Checkers/ContainerModeling.cpp 
b/clang/lib/StaticAnalyzer/Checkers/ContainerModeling.cpp
index c46a564f50b4..77a3218f55fb 100644
--- a/clang/lib/StaticAnalyzer/Checkers/ContainerModeling.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/ContainerModeling.cpp
@@ -72,42 +72,27 @@ class ContainerModeling
SVal) const;
 
   CallDescriptionMap NoIterParamFunctions = {
-{{0, "clear", 0},
- &ContainerModeling::handleClear},
-{{0, "assign", 2},
- &ContainerModeling::handleAssign},
-{{0, "push_back", 1},
- &ContainerModeling::handlePushBack},
-{{0, "emplace_back", 1},
- &ContainerModeling::handlePushBack},
-{{0, "pop_back", 0},
- &ContainerModeling::handlePopBack},
-{{0, "push_front", 1},
- &ContainerModeling::handlePushFront},
-{{0, "emplace_front", 1},
- &ContainerModeling::handlePushFront},
-{{0, "pop_front", 0},
- &ContainerModeling::handlePopFront},
+  {{"clear", 0}, &ContainerModeling::handleClear},
+  {{"assign", 2}, &ContainerModeling::handleAssign},
+  {{"push_back", 1}, &ContainerModeling::handlePushBack},
+  {{"emplace_back", 1}, &ContainerModeling::handlePushBack},
+  {{"pop_back", 0}, &ContainerModeling::handlePopBack},
+  {{"push_front", 1}, &ContainerModeling::handlePushFront},
+  {{"emplace_front", 1}, &ContainerModeling::handlePushFront},
+  {{"pop_front", 0}, &ContainerModeling::handlePopFront},
   };
-  
+
   CallDescriptionMap OneIterParamFunctions = {
-{{0, "insert", 2},
- &ContainerModeling::handleInsert},
-{{0, "emplace", 2},
- &ContainerModeling::handleInsert},
-{{0, "erase", 1},
- &ContainerModeling::handleErase},
-{{0, "erase_after", 1},
- &ContainerModeling::handleEraseAfter},
+  {{"insert", 2}, &ContainerModeling::handleInsert},
+  {{"emplace", 2}, &ContainerModeling::handleInsert},
+  {{"erase", 1}, &ContainerModeling::handleErase},
+  {{"erase_after", 1}, &ContainerModeling::handleEraseAfter},
   };
-  
+
   CallDescriptionMap TwoIterParamFunctions = {
-{{0, "erase", 2},
- &ContainerModeling::handleErase},
-{{0, "erase_after", 2},
- &ContainerModeling::handleEraseAfter},
+  {{"erase", 2}, &ContainerModeling::handleErase},
+  {{"erase_after", 2}, &ContainerModeling::handleEraseAfter},
   };
-  
 };
 
 bool isBeginCall(const FunctionDecl *Func);

diff  --git a/clang/lib/StaticAnalyzer/Checkers/DebugContainerModeling.cpp 
b/clang/lib/StaticAnalyzer/Checkers/DebugContainerModeling.cpp
index b49027783a90

[PATCH] D113589: [analyzer][NFC] Introduce CallDescriptionSets

2021-11-19 Thread Balázs Benics 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 rGd448fcd9b223: [analyzer][NFC] Introduce CallDescriptionSets 
(authored by steakhal).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113589

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
  clang/lib/StaticAnalyzer/Core/CallDescription.cpp


Index: clang/lib/StaticAnalyzer/Core/CallDescription.cpp
===
--- clang/lib/StaticAnalyzer/Core/CallDescription.cpp
+++ clang/lib/StaticAnalyzer/Core/CallDescription.cpp
@@ -46,3 +46,14 @@
 Optional RequiredArgs /*= None*/,
 Optional RequiredParams /*= None*/)
 : CallDescription(0, QualifiedName, RequiredArgs, RequiredParams) {}
+
+ento::CallDescriptionSet::CallDescriptionSet(
+std::initializer_list &&List) {
+  Impl.LinearMap.reserve(List.size());
+  for (const CallDescription &CD : List)
+Impl.LinearMap.push_back({CD, /*unused*/ true});
+}
+
+bool ento::CallDescriptionSet::contains(const CallEvent &Call) const {
+  return static_cast(Impl.lookup(Call));
+}
Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
===
--- clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
+++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
@@ -88,6 +88,8 @@
 /// An immutable map from CallDescriptions to arbitrary data. Provides a 
unified
 /// way for checkers to react on function calls.
 template  class CallDescriptionMap {
+  friend class CallDescriptionSet;
+
   // Some call descriptions aren't easily hashable (eg., the ones with 
qualified
   // names in which some sections are omitted), so let's put them
   // in a simple vector and use linear lookup.
@@ -118,6 +120,21 @@
   }
 };
 
+/// An immutable set of CallDescriptions.
+/// Checkers can efficiently decide if a given CallEvent matches any
+/// CallDescription in the set.
+class CallDescriptionSet {
+  CallDescriptionMap Impl = {};
+
+public:
+  CallDescriptionSet(std::initializer_list &&List);
+
+  CallDescriptionSet(const CallDescriptionSet &) = delete;
+  CallDescriptionSet &operator=(const CallDescription &) = delete;
+
+  LLVM_NODISCARD bool contains(const CallEvent &Call) const;
+};
+
 } // namespace ento
 } // namespace clang
 


Index: clang/lib/StaticAnalyzer/Core/CallDescription.cpp
===
--- clang/lib/StaticAnalyzer/Core/CallDescription.cpp
+++ clang/lib/StaticAnalyzer/Core/CallDescription.cpp
@@ -46,3 +46,14 @@
 Optional RequiredArgs /*= None*/,
 Optional RequiredParams /*= None*/)
 : CallDescription(0, QualifiedName, RequiredArgs, RequiredParams) {}
+
+ento::CallDescriptionSet::CallDescriptionSet(
+std::initializer_list &&List) {
+  Impl.LinearMap.reserve(List.size());
+  for (const CallDescription &CD : List)
+Impl.LinearMap.push_back({CD, /*unused*/ true});
+}
+
+bool ento::CallDescriptionSet::contains(const CallEvent &Call) const {
+  return static_cast(Impl.lookup(Call));
+}
Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
===
--- clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
+++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
@@ -88,6 +88,8 @@
 /// An immutable map from CallDescriptions to arbitrary data. Provides a unified
 /// way for checkers to react on function calls.
 template  class CallDescriptionMap {
+  friend class CallDescriptionSet;
+
   // Some call descriptions aren't easily hashable (eg., the ones with qualified
   // names in which some sections are omitted), so let's put them
   // in a simple vector and use linear lookup.
@@ -118,6 +120,21 @@
   }
 };
 
+/// An immutable set of CallDescriptions.
+/// Checkers can efficiently decide if a given CallEvent matches any
+/// CallDescription in the set.
+class CallDescriptionSet {
+  CallDescriptionMap Impl = {};
+
+public:
+  CallDescriptionSet(std::initializer_list &&List);
+
+  CallDescriptionSet(const CallDescriptionSet &) = delete;
+  CallDescriptionSet &operator=(const CallDescription &) = delete;
+
+  LLVM_NODISCARD bool contains(const CallEvent &Call) const;
+};
+
 } // namespace ento
 } // namespace clang
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D113590: [analyzer][NFC] Introduce CallDescription::matches() in addition to isCalled()

2021-11-19 Thread Balázs Benics 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 rG6c512703a9e6: [analyzer][NFC] Introduce 
CallDescription::matches() in addition to isCalled() (authored by steakhal).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113590

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
  clang/lib/StaticAnalyzer/Core/CallDescription.cpp
  clang/lib/StaticAnalyzer/Core/CallEvent.cpp

Index: clang/lib/StaticAnalyzer/Core/CallEvent.cpp
===
--- clang/lib/StaticAnalyzer/Core/CallEvent.cpp
+++ clang/lib/StaticAnalyzer/Core/CallEvent.cpp
@@ -304,85 +304,7 @@
 }
 
 bool CallEvent::isCalled(const CallDescription &CD) const {
-  // FIXME: Add ObjC Message support.
-  if (getKind() == CE_ObjCMessage)
-return false;
-
-  const auto *FD = dyn_cast_or_null(getDecl());
-  if (!FD)
-return false;
-
-  if (CD.Flags & CDF_MaybeBuiltin) {
-return CheckerContext::isCLibraryFunction(FD, CD.getFunctionName()) &&
-   (!CD.RequiredArgs || CD.RequiredArgs <= getNumArgs()) &&
-   (!CD.RequiredParams || CD.RequiredParams <= parameters().size());
-  }
-
-  if (!CD.II.hasValue()) {
-CD.II = &getState()->getStateManager().getContext().Idents.get(
-CD.getFunctionName());
-  }
-
-  const auto MatchNameOnly = [](const CallDescription &CD,
-const NamedDecl *ND) -> bool {
-DeclarationName Name = ND->getDeclName();
-if (const auto *II = Name.getAsIdentifierInfo())
-  return II == CD.II.getValue(); // Fast case.
-
-// Fallback to the slow stringification and comparison for:
-// C++ overloaded operators, constructors, destructors, etc.
-// FIXME This comparison is way SLOWER than comparing pointers.
-// At some point in the future, we should compare FunctionDecl pointers.
-return Name.getAsString() == CD.getFunctionName();
-  };
-
-  const auto ExactMatchArgAndParamCounts =
-  [](const CallEvent &Call, const CallDescription &CD) -> bool {
-const bool ArgsMatch =
-!CD.RequiredArgs || CD.RequiredArgs == Call.getNumArgs();
-const bool ParamsMatch =
-!CD.RequiredParams || CD.RequiredParams == Call.parameters().size();
-return ArgsMatch && ParamsMatch;
-  };
-
-  const auto MatchQualifiedNameParts = [](const CallDescription &CD,
-  const Decl *D) -> bool {
-const auto FindNextNamespaceOrRecord =
-[](const DeclContext *Ctx) -> const DeclContext * {
-  while (Ctx && !isa(Ctx))
-Ctx = Ctx->getParent();
-  return Ctx;
-};
-
-auto QualifierPartsIt = CD.begin_qualified_name_parts();
-const auto QualifierPartsEndIt = CD.end_qualified_name_parts();
-
-// Match namespace and record names. Skip unrelated names if they don't
-// match.
-const DeclContext *Ctx = FindNextNamespaceOrRecord(D->getDeclContext());
-for (; Ctx && QualifierPartsIt != QualifierPartsEndIt;
- Ctx = FindNextNamespaceOrRecord(Ctx->getParent())) {
-  // If not matched just continue and try matching for the next one.
-  if (cast(Ctx)->getName() != *QualifierPartsIt)
-continue;
-  ++QualifierPartsIt;
-}
-
-// We matched if we consumed all expected qualifier segments.
-return QualifierPartsIt == QualifierPartsEndIt;
-  };
-
-  // Let's start matching...
-  if (!ExactMatchArgAndParamCounts(*this, CD))
-return false;
-
-  if (!MatchNameOnly(CD, FD))
-return false;
-
-  if (!CD.hasQualifiedNameParts())
-return true;
-
-  return MatchQualifiedNameParts(CD, FD);
+  return CD.matches(*this);
 }
 
 SVal CallEvent::getArgSVal(unsigned Index) const {
Index: clang/lib/StaticAnalyzer/Core/CallDescription.cpp
===
--- clang/lib/StaticAnalyzer/Core/CallDescription.cpp
+++ clang/lib/StaticAnalyzer/Core/CallDescription.cpp
@@ -14,6 +14,7 @@
 
 #include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/Optional.h"
 
@@ -47,6 +48,88 @@
 Optional RequiredParams /*= None*/)
 : CallDescription(0, QualifiedName, RequiredArgs, RequiredParams) {}
 
+bool ento::CallDescription::matches(const CallEvent &Call) const {
+  // FIXME: Add ObjC Message support.
+  if (Call.getKind() == CE_ObjCMessage)
+return false;
+
+  const auto *FD = dyn_cast_or_null(Call.getDecl());
+  if (!FD)
+return false;
+
+  if (Flags & CDF_MaybeBuiltin) {
+return CheckerContext::isCLibraryFunction(FD, getFunctionName()) &&
+   (!RequiredArgs || RequiredAr

[PATCH] D113591: [analyzer][NFC] Switch to using CallDescription::matches() instead of isCalled()

2021-11-19 Thread Balázs Benics 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 rGf18da190b0db: [analyzer][NFC] Switch to using 
CallDescription::matches() instead of isCalled() (authored by steakhal).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113591

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
  clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp
  clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/ChrootChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/InnerPointerChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/MIGChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/MmapWriteExecChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/SimpleStreamChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
  clang/lib/StaticAnalyzer/Checkers/StringChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/ValistChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/cert/PutenvWithAutoChecker.cpp
  clang/lib/StaticAnalyzer/Core/CallEvent.cpp
  clang/unittests/StaticAnalyzer/ConflictingEvalCallsTest.cpp
  clang/unittests/StaticAnalyzer/NoStateChangeFuncVisitorTest.cpp

Index: clang/unittests/StaticAnalyzer/NoStateChangeFuncVisitorTest.cpp
===
--- clang/unittests/StaticAnalyzer/NoStateChangeFuncVisitorTest.cpp
+++ clang/unittests/StaticAnalyzer/NoStateChangeFuncVisitorTest.cpp
@@ -86,17 +86,17 @@
 
 public:
   void checkPreCall(const CallEvent &Call, CheckerContext &C) const {
-if (Call.isCalled(CallDescription{"preventError", 0})) {
+if (CallDescription{"preventError", 0}.matches(Call)) {
   C.addTransition(C.getState()->set(true));
   return;
 }
 
-if (Call.isCalled(CallDescription{"allowError", 0})) {
+if (CallDescription{"allowError", 0}.matches(Call)) {
   C.addTransition(C.getState()->set(false));
   return;
 }
 
-if (Call.isCalled(CallDescription{"error", 0})) {
+if (CallDescription{"error", 0}.matches(Call)) {
   if (C.getState()->get())
 return;
   const ExplodedNode *N = C.generateErrorNode();
Index: clang/unittests/StaticAnalyzer/ConflictingEvalCallsTest.cpp
===
--- clang/unittests/StaticAnalyzer/ConflictingEvalCallsTest.cpp
+++ clang/unittests/StaticAnalyzer/ConflictingEvalCallsTest.cpp
@@ -22,7 +22,7 @@
 
 public:
   bool evalCall(const CallEvent &Call, CheckerContext &C) const {
-return Call.isCalled(Foo);
+return Foo.matches(Call);
   }
 };
 
Index: clang/lib/StaticAnalyzer/Core/CallEvent.cpp
===
--- clang/lib/StaticAnalyzer/Core/CallEvent.cpp
+++ clang/lib/StaticAnalyzer/Core/CallEvent.cpp
@@ -303,10 +303,6 @@
   return PostImplicitCall(D, Loc, getLocationContext(), Tag);
 }
 
-bool CallEvent::isCalled(const CallDescription &CD) const {
-  return CD.matches(*this);
-}
-
 SVal CallEvent::getArgSVal(unsigned Index) const {
   const Expr *ArgE = getArgExpr(Index);
   if (!ArgE)
Index: clang/lib/StaticAnalyzer/Checkers/cert/PutenvWithAutoChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/cert/PutenvWithAutoChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/cert/PutenvWithAutoChecker.cpp
@@ -39,7 +39,7 @@
 
 void PutenvWithAutoChecker::checkPostCall(const CallEvent &Call,
   CheckerContext &C) const {
-  if (!Call.isCalled(Putenv))
+  if (!Putenv.matches(Call))
 return;
 
   SVal ArgV = Call.getArgSVal(0);
Index: clang/lib/StaticAnalyzer/Checkers/ValistChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/ValistChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/ValistChecker.cpp
@@ -127,15 +127,15 @@
  CheckerContext &C) const {
   if (!Call.isGlobalCFunction())
 return;
-  if (Call.isCalled(VaStart))
+  if (VaStart.matches(Call))
 checkVAListStartCall(Call, C, false);
-  else if (Call.isCalled(VaCopy))
+  else if (VaCopy.matches(Call))
 checkVAListStartCall(Call, C, true);
-  else if (Call.isCalled(VaEnd))
+  else if (VaEnd.matches(Call))
 checkVAListEndCall(Call, C);
   else {
 for (auto FuncInfo : VAListAccepters) {
-  if (!Call.isCalled(FuncInfo.Func))
+  if (!FuncInfo.Func.matches(Call))
 continue;
   bool Symbolic;
   const MemRegion *VAList =
Index: clang/lib/StaticAnalyzer/Checkers/StringChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/StringChecker.cpp
+++ clang/lib/Sta

[PATCH] D113592: [analyzer][NFC] Demonstrate the use of CallDescriptionSet

2021-11-19 Thread Balázs Benics 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 rG9ad0a90baa8c: [analyzer][NFC] Demonstrate the use of 
CallDescriptionSet (authored by steakhal).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113592

Files:
  clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp


Index: clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp
+++ clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp
@@ -534,10 +534,12 @@
 namespace {
 class CFRetainReleaseChecker : public Checker {
   mutable APIMisuse BT{this, "null passed to CF memory management function"};
-  CallDescription CFRetain{"CFRetain", 1},
-  CFRelease{"CFRelease", 1},
-  CFMakeCollectable{"CFMakeCollectable", 1},
-  CFAutorelease{"CFAutorelease", 1};
+  const CallDescriptionSet ModelledCalls = {
+  {"CFRetain", 1},
+  {"CFRelease", 1},
+  {"CFMakeCollectable", 1},
+  {"CFAutorelease", 1},
+  };
 
 public:
   void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
@@ -551,8 +553,7 @@
 return;
 
   // Check if we called CFRetain/CFRelease/CFMakeCollectable/CFAutorelease.
-
-  if (!matchesAny(Call, CFRetain, CFRelease, CFMakeCollectable, CFAutorelease))
+  if (!ModelledCalls.contains(Call))
 return;
 
   // Get the argument's value.


Index: clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp
+++ clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp
@@ -534,10 +534,12 @@
 namespace {
 class CFRetainReleaseChecker : public Checker {
   mutable APIMisuse BT{this, "null passed to CF memory management function"};
-  CallDescription CFRetain{"CFRetain", 1},
-  CFRelease{"CFRelease", 1},
-  CFMakeCollectable{"CFMakeCollectable", 1},
-  CFAutorelease{"CFAutorelease", 1};
+  const CallDescriptionSet ModelledCalls = {
+  {"CFRetain", 1},
+  {"CFRelease", 1},
+  {"CFMakeCollectable", 1},
+  {"CFAutorelease", 1},
+  };
 
 public:
   void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
@@ -551,8 +553,7 @@
 return;
 
   // Check if we called CFRetain/CFRelease/CFMakeCollectable/CFAutorelease.
-
-  if (!matchesAny(Call, CFRetain, CFRelease, CFMakeCollectable, CFAutorelease))
+  if (!ModelledCalls.contains(Call))
 return;
 
   // Get the argument's value.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D113593: [analyzer][NFC] CallDescription should own the qualified name parts

2021-11-19 Thread Balázs Benics 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 rGde9d7e42aca2: [analyzer][NFC] CallDescription should own the 
qualified name parts (authored by steakhal).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113593

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
  clang/lib/StaticAnalyzer/Core/CallDescription.cpp


Index: clang/lib/StaticAnalyzer/Core/CallDescription.cpp
===
--- clang/lib/StaticAnalyzer/Core/CallDescription.cpp
+++ clang/lib/StaticAnalyzer/Core/CallDescription.cpp
@@ -17,6 +17,7 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/Optional.h"
+#include 
 
 using namespace llvm;
 using namespace clang;
@@ -35,10 +36,12 @@
 int Flags, ArrayRef QualifiedName,
 Optional RequiredArgs /*= None*/,
 Optional RequiredParams /*= None*/)
-: QualifiedName(QualifiedName), RequiredArgs(RequiredArgs),
+: RequiredArgs(RequiredArgs),
   RequiredParams(readRequiredParams(RequiredArgs, RequiredParams)),
   Flags(Flags) {
   assert(!QualifiedName.empty());
+  this->QualifiedName.reserve(QualifiedName.size());
+  llvm::copy(QualifiedName, std::back_inserter(this->QualifiedName));
 }
 
 /// Construct a CallDescription with default flags.
Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
===
--- clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
+++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
@@ -43,7 +43,7 @@
   mutable Optional II;
   // The list of the qualified names used to identify the specified CallEvent,
   // e.g. "{a, b}" represent the qualified names, like "a::b".
-  std::vector QualifiedName;
+  std::vector QualifiedName;
   Optional RequiredArgs;
   Optional RequiredParams;
   int Flags;


Index: clang/lib/StaticAnalyzer/Core/CallDescription.cpp
===
--- clang/lib/StaticAnalyzer/Core/CallDescription.cpp
+++ clang/lib/StaticAnalyzer/Core/CallDescription.cpp
@@ -17,6 +17,7 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/Optional.h"
+#include 
 
 using namespace llvm;
 using namespace clang;
@@ -35,10 +36,12 @@
 int Flags, ArrayRef QualifiedName,
 Optional RequiredArgs /*= None*/,
 Optional RequiredParams /*= None*/)
-: QualifiedName(QualifiedName), RequiredArgs(RequiredArgs),
+: RequiredArgs(RequiredArgs),
   RequiredParams(readRequiredParams(RequiredArgs, RequiredParams)),
   Flags(Flags) {
   assert(!QualifiedName.empty());
+  this->QualifiedName.reserve(QualifiedName.size());
+  llvm::copy(QualifiedName, std::back_inserter(this->QualifiedName));
 }
 
 /// Construct a CallDescription with default flags.
Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
===
--- clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
+++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
@@ -43,7 +43,7 @@
   mutable Optional II;
   // The list of the qualified names used to identify the specified CallEvent,
   // e.g. "{a, b}" represent the qualified names, like "a::b".
-  std::vector QualifiedName;
+  std::vector QualifiedName;
   Optional RequiredArgs;
   Optional RequiredParams;
   int Flags;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D113594: [analyzer][NFC] Consolidate the inner representation of CallDescriptions

2021-11-19 Thread Balázs Benics 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 rG97f1bf15b154: [analyzer][NFC] Consolidate the inner 
representation of CallDescriptions (authored by steakhal).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113594

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
  clang/lib/StaticAnalyzer/Core/CallDescription.cpp

Index: clang/lib/StaticAnalyzer/Core/CallDescription.cpp
===
--- clang/lib/StaticAnalyzer/Core/CallDescription.cpp
+++ clang/lib/StaticAnalyzer/Core/CallDescription.cpp
@@ -22,20 +22,22 @@
 using namespace llvm;
 using namespace clang;
 
+using MaybeUInt = Optional;
+
 // A constructor helper.
-static Optional readRequiredParams(Optional RequiredArgs,
-   Optional RequiredParams) {
+static MaybeUInt readRequiredParams(MaybeUInt RequiredArgs,
+MaybeUInt RequiredParams) {
   if (RequiredParams)
 return RequiredParams;
   if (RequiredArgs)
-return static_cast(*RequiredArgs);
+return RequiredArgs;
   return None;
 }
 
-ento::CallDescription::CallDescription(
-int Flags, ArrayRef QualifiedName,
-Optional RequiredArgs /*= None*/,
-Optional RequiredParams /*= None*/)
+ento::CallDescription::CallDescription(int Flags,
+   ArrayRef QualifiedName,
+   MaybeUInt RequiredArgs /*= None*/,
+   MaybeUInt RequiredParams /*= None*/)
 : RequiredArgs(RequiredArgs),
   RequiredParams(readRequiredParams(RequiredArgs, RequiredParams)),
   Flags(Flags) {
@@ -45,10 +47,9 @@
 }
 
 /// Construct a CallDescription with default flags.
-ento::CallDescription::CallDescription(
-ArrayRef QualifiedName,
-Optional RequiredArgs /*= None*/,
-Optional RequiredParams /*= None*/)
+ento::CallDescription::CallDescription(ArrayRef QualifiedName,
+   MaybeUInt RequiredArgs /*= None*/,
+   MaybeUInt RequiredParams /*= None*/)
 : CallDescription(0, QualifiedName, RequiredArgs, RequiredParams) {}
 
 bool ento::CallDescription::matches(const CallEvent &Call) const {
@@ -62,8 +63,8 @@
 
   if (Flags & CDF_MaybeBuiltin) {
 return CheckerContext::isCLibraryFunction(FD, getFunctionName()) &&
-   (!RequiredArgs || RequiredArgs <= Call.getNumArgs()) &&
-   (!RequiredParams || RequiredParams <= Call.parameters().size());
+   (!RequiredArgs || *RequiredArgs <= Call.getNumArgs()) &&
+   (!RequiredParams || *RequiredParams <= Call.parameters().size());
   }
 
   if (!II.hasValue()) {
@@ -87,9 +88,9 @@
   const auto ExactMatchArgAndParamCounts =
   [](const CallEvent &Call, const CallDescription &CD) -> bool {
 const bool ArgsMatch =
-!CD.RequiredArgs || CD.RequiredArgs == Call.getNumArgs();
+!CD.RequiredArgs || *CD.RequiredArgs == Call.getNumArgs();
 const bool ParamsMatch =
-!CD.RequiredParams || CD.RequiredParams == Call.parameters().size();
+!CD.RequiredParams || *CD.RequiredParams == Call.parameters().size();
 return ArgsMatch && ParamsMatch;
   };
 
Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
===
--- clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
+++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
@@ -40,12 +40,14 @@
 /// arguments and the name of the function.
 class CallDescription {
   friend class CallEvent;
+  using MaybeUInt = Optional;
+
   mutable Optional II;
   // The list of the qualified names used to identify the specified CallEvent,
   // e.g. "{a, b}" represent the qualified names, like "a::b".
   std::vector QualifiedName;
-  Optional RequiredArgs;
-  Optional RequiredParams;
+  MaybeUInt RequiredArgs;
+  MaybeUInt RequiredParams;
   int Flags;
 
 public:
@@ -60,13 +62,13 @@
   /// call. Omit this parameter to match every occurrence of call with a given
   /// name regardless the number of arguments.
   CallDescription(int Flags, ArrayRef QualifiedName,
-  Optional RequiredArgs = None,
-  Optional RequiredParams = None);
+  MaybeUInt RequiredArgs = None,
+  MaybeUInt RequiredParams = None);
 
   /// Construct a CallDescription with default flags.
   CallDescription(ArrayRef QualifiedName,
-  Optional RequiredArgs = None,
-  Optional RequiredParams = None);
+  MaybeUInt RequiredArgs = None,
+  MaybeUInt RequiredParams = None);
 

[PATCH] D113595: [analyzer][NFC] Use enum for CallDescription flags

2021-11-19 Thread Balázs Benics 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 rGe6ef134f3c77: [analyzer][NFC] Use enum for CallDescription 
flags (authored by steakhal).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113595

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
  clang/lib/StaticAnalyzer/Checkers/ContainerModeling.cpp
  clang/lib/StaticAnalyzer/Checkers/DebugContainerModeling.cpp
  clang/lib/StaticAnalyzer/Checkers/DebugIteratorModeling.cpp
  clang/lib/StaticAnalyzer/Core/CallDescription.cpp

Index: clang/lib/StaticAnalyzer/Core/CallDescription.cpp
===
--- clang/lib/StaticAnalyzer/Core/CallDescription.cpp
+++ clang/lib/StaticAnalyzer/Core/CallDescription.cpp
@@ -34,7 +34,7 @@
   return None;
 }
 
-ento::CallDescription::CallDescription(int Flags,
+ento::CallDescription::CallDescription(CallDescriptionFlags Flags,
ArrayRef QualifiedName,
MaybeUInt RequiredArgs /*= None*/,
MaybeUInt RequiredParams /*= None*/)
@@ -50,7 +50,7 @@
 ento::CallDescription::CallDescription(ArrayRef QualifiedName,
MaybeUInt RequiredArgs /*= None*/,
MaybeUInt RequiredParams /*= None*/)
-: CallDescription(0, QualifiedName, RequiredArgs, RequiredParams) {}
+: CallDescription(CDF_None, QualifiedName, RequiredArgs, RequiredParams) {}
 
 bool ento::CallDescription::matches(const CallEvent &Call) const {
   // FIXME: Add ObjC Message support.
Index: clang/lib/StaticAnalyzer/Checkers/DebugIteratorModeling.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/DebugIteratorModeling.cpp
+++ clang/lib/StaticAnalyzer/Checkers/DebugIteratorModeling.cpp
@@ -42,12 +42,12 @@
  CheckerContext &) const;
 
   CallDescriptionMap Callbacks = {
-{{0, "clang_analyzer_iterator_position", 1},
- &DebugIteratorModeling::analyzerIteratorPosition},
-{{0, "clang_analyzer_iterator_container", 1},
- &DebugIteratorModeling::analyzerIteratorContainer},
-{{0, "clang_analyzer_iterator_validity", 1},
- &DebugIteratorModeling::analyzerIteratorValidity},
+  {{"clang_analyzer_iterator_position", 1},
+   &DebugIteratorModeling::analyzerIteratorPosition},
+  {{"clang_analyzer_iterator_container", 1},
+   &DebugIteratorModeling::analyzerIteratorContainer},
+  {{"clang_analyzer_iterator_validity", 1},
+   &DebugIteratorModeling::analyzerIteratorValidity},
   };
 
 public:
Index: clang/lib/StaticAnalyzer/Checkers/DebugContainerModeling.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/DebugContainerModeling.cpp
+++ clang/lib/StaticAnalyzer/Checkers/DebugContainerModeling.cpp
@@ -41,10 +41,10 @@
  CheckerContext &) const;
 
   CallDescriptionMap Callbacks = {
-{{0, "clang_analyzer_container_begin", 1},
- &DebugContainerModeling::analyzerContainerBegin},
-{{0, "clang_analyzer_container_end", 1},
- &DebugContainerModeling::analyzerContainerEnd},
+  {{"clang_analyzer_container_begin", 1},
+   &DebugContainerModeling::analyzerContainerBegin},
+  {{"clang_analyzer_container_end", 1},
+   &DebugContainerModeling::analyzerContainerEnd},
   };
 
 public:
Index: clang/lib/StaticAnalyzer/Checkers/ContainerModeling.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/ContainerModeling.cpp
+++ clang/lib/StaticAnalyzer/Checkers/ContainerModeling.cpp
@@ -72,42 +72,27 @@
SVal) const;
 
   CallDescriptionMap NoIterParamFunctions = {
-{{0, "clear", 0},
- &ContainerModeling::handleClear},
-{{0, "assign", 2},
- &ContainerModeling::handleAssign},
-{{0, "push_back", 1},
- &ContainerModeling::handlePushBack},
-{{0, "emplace_back", 1},
- &ContainerModeling::handlePushBack},
-{{0, "pop_back", 0},
- &ContainerModeling::handlePopBack},
-{{0, "push_front", 1},
- &ContainerModeling::handlePushFront},
-{{0, "emplace_front", 1},
- &ContainerModeling::handlePushFront},
-{{0, "pop_front", 0},
- &ContainerModeling::handlePopFront},
+  {{"clear", 0}, &ContainerModeling::handleClear},
+  {{"assign", 2}, &ContainerModeling::handleAssign},
+  {{"push_back", 1}, &ContainerModeling::handlePushBack},
+  {{"emplace_back", 1}, &ContainerModeling::handlePushBack},
+  {{"pop_back", 0}, &ContainerModeling::handlePop

[Diffusion] rGc93f93b2e3f2: Revert "Revert "Recommit "Revert "[CVP] processSwitch: Remove default case when…

2021-11-19 Thread Bogdan Graur via Phabricator via cfe-commits
bgraur added a comment.

Early heads up that this revision causes a large regression in compilation time 
for some of our internal source files: we are seeing seeing an almost 20x 
increase in compilation times for some files (from 42s to 728s).

I'm working on a reproducer which I'm going to upload when ready.


BRANCHES
  main

Users:
  junparser (Author)

https://reviews.llvm.org/rGc93f93b2e3f2

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


[clang] d5de568 - [analyzer][NFC] MaybeUInt -> MaybeCount

2021-11-19 Thread Balazs Benics via cfe-commits

Author: Balazs Benics
Date: 2021-11-19T18:36:55+01:00
New Revision: d5de568cc7375281b14bd2632576bff7f4afabc3

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

LOG: [analyzer][NFC] MaybeUInt -> MaybeCount

I forgot to include this in D113594

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

Added: 


Modified: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
clang/lib/StaticAnalyzer/Core/CallDescription.cpp

Removed: 




diff  --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
index 67db652a1e52..396c9a4de440 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
@@ -42,14 +42,14 @@ enum CallDescriptionFlags : unsigned {
 /// arguments and the name of the function.
 class CallDescription {
   friend class CallEvent;
-  using MaybeUInt = Optional;
+  using MaybeCount = Optional;
 
   mutable Optional II;
   // The list of the qualified names used to identify the specified CallEvent,
   // e.g. "{a, b}" represent the qualified names, like "a::b".
   std::vector QualifiedName;
-  MaybeUInt RequiredArgs;
-  MaybeUInt RequiredParams;
+  MaybeCount RequiredArgs;
+  MaybeCount RequiredParams;
   int Flags;
 
 public:
@@ -65,13 +65,13 @@ class CallDescription {
   /// name regardless the number of arguments.
   CallDescription(CallDescriptionFlags Flags,
   ArrayRef QualifiedName,
-  MaybeUInt RequiredArgs = None,
-  MaybeUInt RequiredParams = None);
+  MaybeCount RequiredArgs = None,
+  MaybeCount RequiredParams = None);
 
   /// Construct a CallDescription with default flags.
   CallDescription(ArrayRef QualifiedName,
-  MaybeUInt RequiredArgs = None,
-  MaybeUInt RequiredParams = None);
+  MaybeCount RequiredArgs = None,
+  MaybeCount RequiredParams = None);
 
   CallDescription(std::nullptr_t) = delete;
 

diff  --git a/clang/lib/StaticAnalyzer/Core/CallDescription.cpp 
b/clang/lib/StaticAnalyzer/Core/CallDescription.cpp
index 36c50e96311f..810fe365d021 100644
--- a/clang/lib/StaticAnalyzer/Core/CallDescription.cpp
+++ b/clang/lib/StaticAnalyzer/Core/CallDescription.cpp
@@ -22,11 +22,11 @@
 using namespace llvm;
 using namespace clang;
 
-using MaybeUInt = Optional;
+using MaybeCount = Optional;
 
 // A constructor helper.
-static MaybeUInt readRequiredParams(MaybeUInt RequiredArgs,
-MaybeUInt RequiredParams) {
+static MaybeCount readRequiredParams(MaybeCount RequiredArgs,
+ MaybeCount RequiredParams) {
   if (RequiredParams)
 return RequiredParams;
   if (RequiredArgs)
@@ -36,8 +36,8 @@ static MaybeUInt readRequiredParams(MaybeUInt RequiredArgs,
 
 ento::CallDescription::CallDescription(CallDescriptionFlags Flags,
ArrayRef QualifiedName,
-   MaybeUInt RequiredArgs /*= None*/,
-   MaybeUInt RequiredParams /*= None*/)
+   MaybeCount RequiredArgs /*= None*/,
+   MaybeCount RequiredParams /*= None*/)
 : RequiredArgs(RequiredArgs),
   RequiredParams(readRequiredParams(RequiredArgs, RequiredParams)),
   Flags(Flags) {
@@ -48,8 +48,8 @@ ento::CallDescription::CallDescription(CallDescriptionFlags 
Flags,
 
 /// Construct a CallDescription with default flags.
 ento::CallDescription::CallDescription(ArrayRef QualifiedName,
-   MaybeUInt RequiredArgs /*= None*/,
-   MaybeUInt RequiredParams /*= None*/)
+   MaybeCount RequiredArgs /*= None*/,
+   MaybeCount RequiredParams /*= None*/)
 : CallDescription(CDF_None, QualifiedName, RequiredArgs, RequiredParams) {}
 
 bool ento::CallDescription::matches(const CallEvent &Call) const {



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


[PATCH] D113250: [clang][driver] Add -fplugin-arg- to pass arguments to plugins

2021-11-19 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added inline comments.



Comment at: clang/docs/ClangPlugins.rst:131
+
+The clang compiler driver accepts the `fplugin` option to load a plugin.
+Clang plugins can receive arguments from the compiler driver command





Comment at: clang/docs/ClangPlugins.rst:141
+  $ export BD=/path/to/build/directory
+  $ (cd $BD && make CallSuperAttr )
+  $ clang++ -fplugin=$BD/lib/CallSuperAttr.so \





Comment at: clang/lib/Driver/ToolChains/Clang.cpp:6676
+if (FirstDashIndex == StringRef::npos)
+  continue;
+

This probably should be an error. See elsewhere in the file for error reporting.



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:6679
+auto Arg = ArgValue.substr(FirstDashIndex + 1);
+auto PluginName = ArgValue.substr(0, FirstDashIndex);
+





Comment at: clang/test/Driver/plugin-driver-args.cpp:5
+// CHECK: "-load"
+// CHECK: CallSuperAttr
+// CHECK: "-plugin-arg-call_super_plugin"

CHECK-SAME


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

https://reviews.llvm.org/D113250

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


[PATCH] D114025: [clang][NFC] Inclusive terms: replace some uses of sanity in clang

2021-11-19 Thread Zarko Todorovski via Phabricator via cfe-commits
ZarkoCA updated this revision to Diff 388550.
ZarkoCA marked 3 inline comments as done.
ZarkoCA added a comment.

- Address latest round of comments
- Fix unrelated formatting to stop distracting clang-format linter complaints


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114025

Files:
  clang/include/clang/AST/Redeclarable.h
  clang/include/clang/Analysis/CFG.h
  clang/include/clang/CodeGen/CGFunctionInfo.h
  clang/include/clang/Sema/Lookup.h
  clang/lib/Analysis/BodyFarm.cpp
  clang/lib/Analysis/RetainSummaryManager.cpp
  clang/lib/Basic/DiagnosticIDs.cpp
  clang/lib/Basic/SourceManager.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Format/Format.cpp
  clang/lib/Frontend/FrontendActions.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaExprCXX.cpp
  clang/lib/Sema/SemaLookup.cpp
  clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/MIGChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
  clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
  clang/lib/StaticAnalyzer/Core/Store.cpp
  clang/lib/Tooling/Syntax/Tree.cpp

Index: clang/lib/Tooling/Syntax/Tree.cpp
===
--- clang/lib/Tooling/Syntax/Tree.cpp
+++ clang/lib/Tooling/Syntax/Tree.cpp
@@ -126,7 +126,7 @@
   for (auto *N = New; N; N = N->NextSibling) {
 assert(N->Parent == nullptr);
 assert(N->getRole() != NodeRole::Detached && "Roles must be set");
-// FIXME: sanity-check the role.
+// FIXME: validate the role.
   }
 
   auto Reachable = [](Node *From, Node *N) {
Index: clang/lib/StaticAnalyzer/Core/Store.cpp
===
--- clang/lib/StaticAnalyzer/Core/Store.cpp
+++ clang/lib/StaticAnalyzer/Core/Store.cpp
@@ -249,7 +249,7 @@
 }
 
 SVal StoreManager::evalDerivedToBase(SVal Derived, const CastExpr *Cast) {
-  // Sanity check to avoid doing the wrong thing in the face of
+  // Early return to avoid doing the wrong thing in the face of
   // reinterpret_cast.
   if (!regionMatchesCXXRecordType(Derived, Cast->getSubExpr()->getType()))
 return UnknownVal();
Index: clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
===
--- clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -326,8 +326,8 @@
 }
 Result = InitWithAdjustments;
   } else {
-// We need to create a region no matter what. For sanity, make sure we don't
-// try to stuff a Loc into a non-pointer temporary region.
+// We need to create a region no matter what. Make sure we don't try to
+// stuff a Loc into a non-pointer temporary region.
 assert(!InitValWithAdjustments.getAs() ||
Loc::isLocType(Result->getType()) ||
Result->getType()->isMemberPointerType());
Index: clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
===
--- clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -1670,9 +1670,10 @@
   if (isUnderconstrained(PrevN)) {
 IsSatisfied = true;
 
-// As a sanity check, make sure that the negation of the constraint
-// was infeasible in the current state.  If it is feasible, we somehow
-// missed the transition point.
+// At this point, the negation of the constraint should be infeasible. If it
+// is feasible, make sure that the negation of the constrainti was
+// infeasible in the current state.  If it is feasible, we somehow missed
+// the transition point.
 assert(!isUnderconstrained(N));
 
 // We found the transition point for the constraint.  We now need to
Index: clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
@@ -182,8 +182,7 @@
   ProgramStateRef state = C.getState();
 
   if (CE->getNumArgs() < MinArgCount) {
-// The frontend should issue a warning for this case, so this is a sanity
-// check.
+// The frontend should issue a warning for this case. Just return.
 return;
   } else if (CE->getNumArgs() == MaxArgCount) {
 const Expr *Arg = CE->getArg(CreateModeArgIndex);
@@ -366,7 +365,7 @@
  const unsigned numArgs,
  const unsigned sizeArg,
  const char *fn) const {
-  // Sanity check for the correct number of argument

[PATCH] D114025: [clang][NFC] Inclusive terms: replace some uses of sanity in clang

2021-11-19 Thread Zarko Todorovski via Phabricator via cfe-commits
ZarkoCA added inline comments.



Comment at: clang/lib/Sema/SemaDeclCXX.cpp:9176
   // Don't check the implicit member of the anonymous union type.
-  // This is technically non-conformant, but sanity demands it.
+  // This is technically non-conformant, but validation tests demand it.
   return false;

Quuxplusone wrote:
> Quuxplusone wrote:
> > Quuxplusone wrote:
> > > This comment seems incorrectly translated.
> > This comment //still// seems incorrectly translated.
> > Things we do "for sanity's sake" aren't necessarily //required//, 
> > technically; but we're doing them anyway, for sanity.
> "Don't check ... but check it anyway"?
Right, that didn't make sense :). I noticed that there were warnings for this 
case in SemaDecl.cpp AFAIU so edited the comment to state that. Should be 
better now? 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114025

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


[PATCH] D103096: [analyzer] Implement cast for ranges of symbolic integers

2021-11-19 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov updated this revision to Diff 388552.
ASDenysPetrov added a comment.

Rebased.


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

https://reviews.llvm.org/D103096

Files:
  clang/include/clang/StaticAnalyzer/Checkers/SValExplainer.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymExpr.h
  clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
  clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
  clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
  clang/lib/StaticAnalyzer/Core/SymbolManager.cpp
  clang/test/Analysis/symbol-integral-cast.cpp

Index: clang/test/Analysis/symbol-integral-cast.cpp
===
--- /dev/null
+++ clang/test/Analysis/symbol-integral-cast.cpp
@@ -0,0 +1,374 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=debug.ExprInspection -analyzer-config eagerly-assume=false -analyzer-config support-symbolic-integer-casts=true -verify %s
+
+template 
+void clang_analyzer_eval(T);
+void clang_analyzer_warnIfReached();
+
+typedef short int16_t;
+typedef int int32_t;
+typedef unsigned short uint16_t;
+typedef unsigned int uint32_t;
+
+void test1(int x) {
+  // Even if two lower bytes of `x` equal to zero, it doesn't mean that
+  // the entire `x` is zero. We are not able to know the exact value of x.
+  // It can be one of  65536 possible values like [0, 65536, 131072, ...]
+  // and so on. To avoid huge range sets we still assume `x` in the range
+  // [INT_MIN, INT_MAX].
+  if (!(short)x) {
+if (!x)
+  clang_analyzer_warnIfReached(); // expected-warning {{REACHABLE}}
+else
+  clang_analyzer_warnIfReached(); // expected-warning {{REACHABLE}}
+  }
+}
+
+void test2(int x) {
+  // If two lower bytes of `x` equal to zero, and we know x to be 65537,
+  // which is not truncated to short as zero. Thus the branch is infisible.
+  short s = x;
+  if (!s) {
+if (x == 65537)
+  clang_analyzer_warnIfReached(); // no-warning
+else
+  clang_analyzer_warnIfReached(); // expected-warning {{REACHABLE}}
+  }
+}
+
+void test3(int x, short s) {
+  s = x;
+  if ((short)x > -10 && s < 10) {
+if (x > 0 && x < 10) {
+  // If the range of the whole variable was constrained then reason again
+  // about truncated bytes to make the ranges more precise.
+  clang_analyzer_eval((short)x <= 0); // expected-warning {{FALSE}}
+}
+  }
+}
+
+void test4(unsigned x) {
+  if ((char)x > 8) {
+// Constraint the range of the lowest byte of `x` to [9, CHAR_MAX].
+// The original range of `x` still remains [0, UINT_MAX].
+clang_analyzer_eval((char)x < 42); // expected-warning {{UNKNOWN}}
+if (x < 42) {
+  // Constraint the original range to [0, 42] and update (re-constraint)
+  // the range of the lowest byte of 'x' to [9, 42].
+  clang_analyzer_eval((char)x < 42); // expected-warning {{TRUE}}
+}
+  }
+}
+
+void test5(unsigned x) {
+  if ((char)x > -10 && (char)x < 10) {
+if ((short)x == 8) {
+  // If the range of higher bytes(short) was constrained then reason again
+  // about smaller truncated ranges(char) to make it more precise.
+  clang_analyzer_eval((char)x == 8);  // expected-warning {{TRUE}}
+  clang_analyzer_eval((short)x == 8); // expected-warning {{TRUE}}
+  // We still assume full version of `x` in the range [INT_MIN, INT_MAX].
+  clang_analyzer_eval(x == 8); // expected-warning {{UNKNOWN}}
+}
+  }
+}
+
+void test6(int x) {
+  // Even if two lower bytes of `x` less than zero, it doesn't mean that `x`
+  // can't be greater than zero. Thence we don't change the native range of
+  // `x` and this branch is feasible.
+  if (x > 0)
+if ((short)x < 0)
+  clang_analyzer_eval(x > 0); // expected-warning {{TRUE}}
+}
+
+void test7(int x) {
+  // The range of two lower bytes of `x` [1, SHORT_MAX] is enough to cover
+  // all possible values of char [CHAR_MIN, CHAR_MAX]. So the lowest byte
+  // can be lower than zero.
+  if ((short)x > 0) {
+if ((char)x < 0)
+  clang_analyzer_warnIfReached(); // expected-warning {{REACHABLE}}
+else
+  clang_analyzer_warnIfReached(); // expected-warning {{REACHABLE}}
+  }
+}
+
+void test8(int x) {
+  // Promotion from `signed int` to `signed long long` also reasoning about the
+  // original range, because we know the fact that even after promotion it
+  // remains in the range [INT_MIN, INT_MAX].
+  if ((long long)x < 0)
+clang_analyzer_eval(x < 0); // expected-warning {{TRUE}}
+}
+
+void test9(signed int x) {
+  // Any cast `signed` to `unsigned` produces an unsigned range, which is
+  // [0, UNSIGNED_MAX] and can not be lower than zero.
+  if ((unsigned long long)x < 0)
+clang_analyzer_warnIfReached(); // no-warning
+  else
+clang_analyzer_warnIfReached(); // expected-warning {{REACHABLE}}
+
+  if ((unsigned int)x < 0)
+clang_analyzer_warnIfReached(); // no-warning
+  else
+clang_analyzer_warnIfReached(); // expected-warning {{REACH

[PATCH] D114006: [analyzer][NFC] Enable access to CodeGenOptions from analyzer's instances

2021-11-19 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov added a comment.

In D114006#3142313 , @martong wrote:

> LGTM!

Thanks, guys!
I'll load it as soon as D110927  also be 
ready for load(I'm working on it), as this patch is just a preparatory one.


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

https://reviews.llvm.org/D114006

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


[PATCH] D114025: [clang][NFC] Inclusive terms: replace some uses of sanity in clang

2021-11-19 Thread Arthur O'Dwyer via Phabricator via cfe-commits
Quuxplusone added inline comments.



Comment at: clang/lib/Sema/SemaDeclCXX.cpp:9176
   // Don't check the implicit member of the anonymous union type.
-  // This is technically non-conformant, but sanity demands it.
+  // This is technically non-conformant, but validation tests demand it.
   return false;

ZarkoCA wrote:
> Quuxplusone wrote:
> > Quuxplusone wrote:
> > > Quuxplusone wrote:
> > > > This comment seems incorrectly translated.
> > > This comment //still// seems incorrectly translated.
> > > Things we do "for sanity's sake" aren't necessarily //required//, 
> > > technically; but we're doing them anyway, for sanity.
> > "Don't check ... but check it anyway"?
> Right, that didn't make sense :). I noticed that there were warnings for this 
> case in SemaDecl.cpp AFAIU so edited the comment to state that. Should be 
> better now? 
Well, this version of the comment now gives the //impression// that it must be 
clear to //someone//. ;) I don't understand its implications, but I also don't 
know the code.

Specifically, I don't know what "This" refers to (grammatically) — "Anonymous 
union types aren't conforming, but we support them anyway, and this is the 
right thing to do with them"? "Our behavior in this case isn't conforming, but 
it wouldn't make sense to do the conforming thing [wat]"? or something else?

More fundamentally to //my// confusion (but not to that hypothetical other 
someone), I don't know what "the implicit member of the anonymous union type" 
actually means (in terms of the arcane details of C++), i.e., I personally 
don't know when this codepath is hit or what its effect is when it does get hit.



Comment at: clang/lib/Sema/SemaDeclCXX.cpp:12260
   // even if hidden by ordinary names, *except* in a dependent context
-  // where it's important for the sanity of two-phase lookup.
+  // where it's important for the validation of two-phase lookup.
   if (!IsInstantiation)

Quuxplusone wrote:
> This comment seems incorrectly translated.
Perhaps just `// where they may be used by two-phase lookup.` (But this is now 
just a nit.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114025

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


[PATCH] D107944: [hmaptool] Port to python3

2021-11-19 Thread Nathan Lanza via Phabricator via cfe-commits
lanza updated this revision to Diff 388568.

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

https://reviews.llvm.org/D107944

Files:
  clang/utils/hmaptool/hmaptool


Index: clang/utils/hmaptool/hmaptool
===
--- clang/utils/hmaptool/hmaptool
+++ clang/utils/hmaptool/hmaptool
@@ -1,6 +1,7 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 from __future__ import absolute_import, division, print_function

+from ctypes import ArgumentError
 import json
 import optparse
 import os
@@ -9,8 +10,8 @@

 ###

-k_header_magic_LE = 'pamh'
-k_header_magic_BE = 'hmap'
+k_header_magic_LE = b'pamh'
+k_header_magic_BE = b'hmap'

 def hmap_hash(str):
 """hash(str) -> int
@@ -43,7 +44,7 @@
 path,))

 (version, reserved, strtable_offset, num_entries,
- num_buckets, max_value_len) = struct.unpack(header_fmt, data)
+ num_buckets) = struct.unpack(header_fmt, data)

 if version != 1:
 raise SystemExit("error: %s: unknown headermap version: %r" % (
@@ -83,7 +84,7 @@
 if len(strtable) != strtable_size:
 raise SystemExit("error: %s: unable to read complete string 
table"%(
 path,))
-if strtable[-1] != '\0':
+if strtable[-1] != 0:
 raise SystemExit("error: %s: invalid string table in 
headermap" % (
 path,))

@@ -97,8 +98,8 @@
 def get_string(self, idx):
 if idx >= len(self.strtable):
 raise SystemExit("error: %s: invalid string index" % (
-path,))
-end_idx = self.strtable.index('\0', idx)
+idx,))
+end_idx = self.strtable.index(0, idx)
 return self.strtable[idx:end_idx]

 @property
@@ -220,7 +221,7 @@

 # Write out the headermap.
 with open(output_path, 'wb') as f:
-f.write(magic.encode())
+f.write(magic)
 f.write(struct.pack(header_fmt, *header))
 for bucket in table:
 f.write(struct.pack(bucket_fmt, *bucket))


Index: clang/utils/hmaptool/hmaptool
===
--- clang/utils/hmaptool/hmaptool
+++ clang/utils/hmaptool/hmaptool
@@ -1,6 +1,7 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 from __future__ import absolute_import, division, print_function

+from ctypes import ArgumentError
 import json
 import optparse
 import os
@@ -9,8 +10,8 @@

 ###

-k_header_magic_LE = 'pamh'
-k_header_magic_BE = 'hmap'
+k_header_magic_LE = b'pamh'
+k_header_magic_BE = b'hmap'

 def hmap_hash(str):
 """hash(str) -> int
@@ -43,7 +44,7 @@
 path,))

 (version, reserved, strtable_offset, num_entries,
- num_buckets, max_value_len) = struct.unpack(header_fmt, data)
+ num_buckets) = struct.unpack(header_fmt, data)

 if version != 1:
 raise SystemExit("error: %s: unknown headermap version: %r" % (
@@ -83,7 +84,7 @@
 if len(strtable) != strtable_size:
 raise SystemExit("error: %s: unable to read complete string table"%(
 path,))
-if strtable[-1] != '\0':
+if strtable[-1] != 0:
 raise SystemExit("error: %s: invalid string table in headermap" % (
 path,))

@@ -97,8 +98,8 @@
 def get_string(self, idx):
 if idx >= len(self.strtable):
 raise SystemExit("error: %s: invalid string index" % (
-path,))
-end_idx = self.strtable.index('\0', idx)
+idx,))
+end_idx = self.strtable.index(0, idx)
 return self.strtable[idx:end_idx]

 @property
@@ -220,7 +221,7 @@

 # Write out the headermap.
 with open(output_path, 'wb') as f:
-f.write(magic.encode())
+f.write(magic)
 f.write(struct.pack(header_fmt, *header))
 for bucket in table:
 f.write(struct.pack(bucket_fmt, *bucket))
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D114268: [InstrProf] Use i32 for GEP index from lowering llvm.instrprof.increment

2021-11-19 Thread Ellis Hoag via Phabricator via cfe-commits
ellis created this revision.
Herald added subscribers: wenlei, arphaman, hiraditya.
ellis updated this revision to Diff 388564.
ellis added a comment.
ellis edited the summary of this revision.
ellis added a reviewer: MaskRay.
ellis retitled this revision from "[InstrProf] Use i32 for GEP index" to 
"[InstrProf] Use i32 for GEP index from lowering llvm.instrprof.increment".
ellis published this revision for review.
Herald added projects: clang, LLVM.
Herald added subscribers: llvm-commits, cfe-commits.

Run `clang-format`.


The `llvm.instrprof.increment` intrinsic uses `i32` for the index. We should 
use this same type for the index into the GEP instructions.

Add names to pgo registers for clarity.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D114268

Files:
  clang/test/CodeGen/profile-filter.c
  clang/test/Profile/branch-logical-mixed.cpp
  clang/test/Profile/c-captured.c
  clang/test/Profile/c-general.c
  clang/test/Profile/c-ternary.c
  clang/test/Profile/cxx-class.cpp
  clang/test/Profile/cxx-lambda.cpp
  clang/test/Profile/cxx-rangefor.cpp
  clang/test/Profile/cxx-stmt-initializers.cpp
  clang/test/Profile/cxx-templates.cpp
  clang/test/Profile/cxx-throws.cpp
  clang/test/Profile/objc-general.m
  llvm/lib/Transforms/Instrumentation/InstrProfiling.cpp
  llvm/test/Instrumentation/InstrProfiling/atomic-updates.ll
  llvm/test/Instrumentation/InstrProfiling/runtime-counter-relocation.ll
  llvm/test/Transforms/PGOProfile/counter_promo_exit_catchswitch.ll
  llvm/test/Transforms/PGOProfile/instr_entry_bb.ll

Index: llvm/test/Transforms/PGOProfile/instr_entry_bb.ll
===
--- llvm/test/Transforms/PGOProfile/instr_entry_bb.ll
+++ llvm/test/Transforms/PGOProfile/instr_entry_bb.ll
@@ -18,7 +18,7 @@
 ; GEN: entry:
 ; GEN: call void @llvm.instrprof.increment(i8* getelementptr inbounds ([9 x i8], [9 x i8]* @__profn_test_br_2, i32 0, i32 0), i64 {{[0-9]+}}, i32 2, i32 0)
 ; GENA: entry:
-; GENA: %{{[0-9+]}} = atomicrmw add i64* getelementptr inbounds ([2 x i64], [2 x i64]* @__profc_test_br_2, i64 0, i64 0), i64 1 monotonic
+; GENA: %{{[0-9+]}} = atomicrmw add i64* getelementptr inbounds ([2 x i64], [2 x i64]* @__profc_test_br_2, i32 0, i32 0), i64 1 monotonic
 ; USE: br i1 %cmp, label %if.then, label %if.else
 ; USE-SAME: !prof ![[BW_ENTRY:[0-9]+]]
 ; USE: ![[BW_ENTRY]] = !{!"branch_weights", i32 0, i32 1}
@@ -35,9 +35,9 @@
 ; GEN: if.else:
 ; GEN: call void @llvm.instrprof.increment(i8* getelementptr inbounds ([9 x i8], [9 x i8]* @__profn_test_br_2, i32 0, i32 0), i64 {{[0-9]+}}, i32 2, i32 1)
 ; GENA: if.else:
-; GENA:  %pgocount = load i64, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @__profc_test_br_2, i64 0, i64 1), align 8
+; GENA:  %pgocount = load i64, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @__profc_test_br_2, i32 0, i32 1), align 8
 ; GENA:  [[V:%[0-9]*]] = add i64 %pgocount, 1
-; GENA:  store i64 [[V]], i64* getelementptr inbounds ([2 x i64], [2 x i64]* @__profc_test_br_2, i64 0, i64 1), align 8
+; GENA:  store i64 [[V]], i64* getelementptr inbounds ([2 x i64], [2 x i64]* @__profc_test_br_2, i32 0, i32 1), align 8
   %sub = sub nsw i32 %i, 2
   br label %if.end
 
Index: llvm/test/Transforms/PGOProfile/counter_promo_exit_catchswitch.ll
===
--- llvm/test/Transforms/PGOProfile/counter_promo_exit_catchswitch.ll
+++ llvm/test/Transforms/PGOProfile/counter_promo_exit_catchswitch.ll
@@ -38,11 +38,11 @@
 
 for.body: ; preds = %for.cond
 ; CHECK: for.body:
-; NOTENTRY: %pgocount1 = load i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @"__profc_?run@@YAXH@Z", i64 0, i64 0)
-; TENTRY: %pgocount1 = load i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @"__profc_?run@@YAXH@Z", i64 0, i64 1)
+; NOTENTRY: %pgocount1 = load i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @"__profc_?run@@YAXH@Z", i32 0, i32 0)
+; TENTRY: %pgocount1 = load i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @"__profc_?run@@YAXH@Z", i32 0, i32 1)
 ; CHECK: %1 = add i64 %pgocount1, 1
-; NOTENTRY: store i64 %1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @"__profc_?run@@YAXH@Z", i64 0, i64 0)
-; ENTRY: store i64 %1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @"__profc_?run@@YAXH@Z", i64 0, i64 1)
+; NOTENTRY: store i64 %1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @"__profc_?run@@YAXH@Z", i32 0, i32 0)
+; ENTRY: store i64 %1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @"__profc_?run@@YAXH@Z", i32 0, i32 1)
   %idxprom = zext i32 %i.0 to i64
   %arrayidx = getelementptr inbounds [200 x i8], [200 x i8]* @"?buffer@@3PADA", i64 0, i64 %idxprom
   %0 = load i8, i8* %arrayidx, align 1
@@ -55,11 +55,11 @@
 
 for.inc:  ; preds = %if.end
 ; CHECK: for.inc:
-; NOTENTRY: %pgocount2 = load i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @"__profc_

[PATCH] D114095: [clang][lex] Include tracking: simplify and move to preprocessor

2021-11-19 Thread Volodymyr Sapsai via Phabricator via cfe-commits
vsapsai added inline comments.



Comment at: clang/lib/Serialization/ASTWriter.cpp:873
   RECORD(PP_TOKEN);
+  RECORD(PP_INCLUDED_FILES);
 

I believe `PP_INCLUDED_FILES` is located in `AST_BLOCK`. Yes, you write it in 
`ASTWriter::WritePreprocessor` but after `Stream.ExitBlock()` together with 
`MACRO_OFFSET`. And then you read it in `ASTReader::ReadASTBlock` at the top 
level and not inside `case PREPROCESSOR_BLOCK_ID` or from 
`ModuleFile::MacroCursor`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114095

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


[PATCH] D71016: [SYCL] Implement OpenCL kernel function generation

2021-11-19 Thread Zahira Ammarguellat via Phabricator via cfe-commits
zahiraam added a comment.

Added in the sycl_special_class attribute. This is still work in progress as I 
still have a few LIT tests failing and didn't address the issue of the 
separating sema from codegen work.


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

https://reviews.llvm.org/D71016

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


[PATCH] D114231: [clang][docs][dataflow] Added an introduction to dataflow analysis

2021-11-19 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added a comment.

Thanks for working on this! Publishing documentation alongside the feature is a 
great practice. I liked this documentation a lot. I have strong opinion about 
the ambiguous use of `path condition` in this document, otherwise I was only 
nitpicking.




Comment at: clang/docs/DataFlowAnalysisIntro.md:24
+*   [Introduction to Dataflow 
Analysis](https://www.youtube.com/watch?v=OROXJ9-wUQE)
+*   [Introduction to abstract 
interpretation](http://www.cs.tau.ac.il/~msagiv/courses/asv/absint-1.pdf).
+*   [Introduction to symbolic 
execution](https://www.cs.umd.edu/~mwh/se-tutorial/symbolic-exec.pdf).

I know, everyone has their favorite set of resources. Let me share mine: 
`https://cs.au.dk/~amoeller/spa/`
I think this one might have a bit more content with more examples. Feel free to 
leave it as is. 



Comment at: clang/docs/DataFlowAnalysisIntro.md:49
+  int x;
+  // x is {}
+  if (n > 0) {

Nit: I wonder if representing the value of `x` with an empty set is a good 
choice. One could argue that `x` has an indeterminate value that could be 
represented with the set of all integers using top. Others could argue for a 
bottom value. Those concepts are not yet introduced. Maybe initializing `x` in 
the source code would side step this problem.



Comment at: clang/docs/DataFlowAnalysisIntro.md:71-72
+Abstract algebra provides a nice formalism that models this type of structure,
+namely, a lattice. A lattice is a partially ordered set, in which every two
+elements have a least upper bound (called a *join*).
+

Technically, I think this would be a `join-semilattice`. To have a `lattice`, 
we would need both `join` and `meet`.



Comment at: clang/docs/DataFlowAnalysisIntro.md:86-87
+
+Computing the join in the lattice corresponds to finding the lowest common
+ancestor between two nodes in its Hasse diagram.
+

If we want to be practical, I wonder if we want to give some guidance how to 
implement that efficiently. E.g. we could cite a paper like this: 
https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.106.4911&rep=rep1&type=pdf



Comment at: clang/docs/DataFlowAnalysisIntro.md:111-112
+information that we track. In this case, we can, for example, arbitrarily limit
+the size of sets to 3 elements. If at a certain program point `x` has more than
+3 possible values, we stop tracking specific values at that program point.
+Instead, we denote possible values of `x` with the symbol `⊤` (pronounced "top"

I wonder if we want to cite widening and narrowing in this context to give 
people some pointers where to look for more info.



Comment at: clang/docs/DataFlowAnalysisIntro.md:182
+void Example(int n) {
+  int x;  // x is ⊥
+  if (n > 0) {

I think it would make sense to include the whole program state in the comments. 
E.g. `// x is ⊥, n is ⊤`.
This could showcase how we constrain the value of `n` to `42` in one of the 
branches.



Comment at: clang/docs/DataFlowAnalysisIntro.md:279
+```
+out = transfer(basic_block, join(in_1, in_2, ..., in_n))
+```

While I agree that this is the general formula, people sometimes do small 
variations, e.g.:
```
out =  join(transfer(basic_block,in_1), transfer(basic_block,in_2), ..., 
transfer(basic_block,in_n))
```

This is less efficient as we end up invoking the transfer function more often, 
but it can be more precise. E.g. with some ad-hoc notation:

```
Given the branches: x: {1}, x: {2}, x: {3}, x: {4}
join(in...) : x : {⊤}
transfer("x/2", ...) == x : {⊤}

vs.
Given the branches: x: {1}, x: {2}, x: {3}, x: {4}
transfer("x/2", ...) ==x : {0}, x : {1}, x : {1}, x: {2} == outs
join(outs) == x: {0, 1, 2}
```



Comment at: clang/docs/DataFlowAnalysisIntro.md:288
+Since the lattice has a finite height, the algorithm is guaranteed to 
terminate.
+Each iteration of the algorithm can change computed values only to larger 
values
+from the lattice. In the worst case, all computed values become `⊤`, which is

Only if our transfer functions are monotonic :)



Comment at: clang/docs/DataFlowAnalysisIntro.md:299
+
+## Symbolic execution: a very short informal introduction
+

I think many people find it confusing, what is the relationship between 
symbolic execution and abstract interpretation? I found this answer helpful: 
https://cstheory.stackexchange.com/questions/19708/symbolic-execution-is-a-case-of-abstract-interpretation
I wonder if it might be worth citing.



Comment at: clang/docs/DataFlowAnalysisIntro.md:365
+void ExampleOfSymbolicPointers(bool b) {
+  int x = 0; // x is {0}
+  int* ptr = &x; // x is {0}

Here, I think we want to include `ptr` in the comments describing the program 
state. 



Comme

[PATCH] D114251: [AST] Add a sugar type for types found via UsingDecl

2021-11-19 Thread Sam McCall via Phabricator via cfe-commits
sammccall added inline comments.



Comment at: clang/include/clang/AST/Type.h:4372
+class UsingType : public Type, public llvm::FoldingSetNode {
+  QualType UnderlyingTy;
+  NamedDecl *Found;

Hmm, maybe I should be getting this from Found, rather than storing it.
We'd have to do more work than e.g. TypedefType though, as we have to check the 
possible types of Found.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114251

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


[PATCH] D114163: Use VersionTuple for parsing versions in Triple. This makes it possible to distinguish between "16" and "16.0" after parsing, which previously was not possible.

2021-11-19 Thread Dan Albert via Phabricator via cfe-commits
danalbert accepted this revision.
danalbert added a comment.
This revision is now accepted and ready to land.

Nice, that's a lot of code cleaned up! LGTM, but probably should wait for 
someone from Apple to weigh in. I think the new formatting for those error 
messages is better for them too but that's not my call :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114163

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


[PATCH] D114234: [clang][dataflow] Add base types for building dataflow analyses

2021-11-19 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added inline comments.



Comment at: clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h:48
+/// Type-erased base class for dataflow analyses built on a single lattice 
type.
+class DataflowAnalysisDynamic {
+public:

Does the `Dynamic` in the suffix refer to the fact this is using type erasure 
as opposed to templates? 

I have multiple questions at this point:
* Why do we prefer type erasure over generic programming?
* Do you plan to have non-dynamic counterparts?

Nit: having Dynamic both in the class name and in the method names sounds 
overly verbose to me.
Nit: please add a comment what dynamic refers to in the name,



Comment at: clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h:140
+struct DataflowAnalysisState {
+  DataflowAnalysisState(AnyLatticeElement Lattice, Environment Env)
+  : Lattice(std::move(Lattice)), Env(std::move(Env)) {}

Do we need a ctor? Or is this a workaround for aggregate initialization not 
working well with certain library facilities?



Comment at: clang/lib/Analysis/FlowSensitive/DataflowAnalysis.cpp:26
+runDataflowAnalysis(const CFG &Cfg, DataflowAnalysisDynamic &Analysis,
+const Environment &InitEnv) {
+  // FIXME: Implement work list-based algorithm to compute the fixed

Is there a way to query how the CFG was built? Adding an assert to see if 
`setAlwaysAdd` was set might be useful.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114234

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


[PATCH] D114142: [clang-format] [PR52527] can join * with /* to form an outside of comment error C4138

2021-11-19 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks added a comment.

In D114142#3142122 , @MyDeveloperDay 
wrote:

>> I only now this from the tests with `-debug`. Is there a way to get "normal" 
>> clang-format to print these? Or did you write a test for that to print the 
>> information?
>
> I just use the --debug option to clang-format.exe?
>
> I develop on windows, using Visual Studio 2019 (Command Shell)  - (with 
> cygwin bash) and build with ninja (so much faster than anything else)
>
> I build Debug  (its possible --debug is only available on Debug builds)
>
>   export CC=cl.exe
>   export CXX=cl.exe
>   c:/Program\ Files/CMake/bin/cmake.exe ../llvm-project/llvm -G "Ninja" \
>   -DLLVM_BUILD_TESTS=ON \
>   -DCMAKE_BUILD_TYPE=Debug \
>   -DCMAKE_EXPORT_COMPILE_COMMANDS=ON \
>   -DLLVM_ENABLE_PROJECTS="clang;clang-tools-extra"
>
> Then just run with --debug
>
>   $ clang-format --debug test1.cpp
>   Args: C:\llvm\build_ninja\bin\clang-format.exe --debug test
>   1.cpp
>   Trying C:\clang-format-examples\comment\.clang-format...
>   Using configuration file C:\clang-format-examples\comment\.c
>   lang-format
>   File encoding: UTF8
>   Language: C++
>   
>   Line(0, FSC=0): comment[T=93, OC=0]
>   Line(0, FSC=0): eof[T=93, OC=119]

Okay, my debug build does not produce a working clang-format, only the tests. 
And my normal clang-format is release, maybe it's that.

On the matter of this change, I would second the test with `//`, and if the 
`tok::comment`` does the trick, that should be better, than using the type.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114142

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


[PATCH] D114025: [clang][NFC] Inclusive terms: replace some uses of sanity in clang

2021-11-19 Thread Zarko Todorovski via Phabricator via cfe-commits
ZarkoCA marked an inline comment as done.
ZarkoCA added a comment.

Thanks @aaron.ballman and @Quuxplusone for the constructive reviews.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114025

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


[clang] d8e5a0c - [clang][NFC] Inclusive terms: replace some uses of sanity in clang

2021-11-19 Thread Zarko Todorovski via cfe-commits

Author: Zarko Todorovski
Date: 2021-11-19T14:58:35-05:00
New Revision: d8e5a0c42bd8796cce9caa53aacab88c7cb2a3eb

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

LOG: [clang][NFC] Inclusive terms: replace some uses of sanity in clang

Rewording of comments to avoid using `sanity test, sanity check`.

Reviewed By: aaron.ballman, Quuxplusone

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

Added: 


Modified: 
clang/include/clang/AST/Redeclarable.h
clang/include/clang/Analysis/CFG.h
clang/include/clang/CodeGen/CGFunctionInfo.h
clang/include/clang/Sema/Lookup.h
clang/lib/Analysis/BodyFarm.cpp
clang/lib/Analysis/RetainSummaryManager.cpp
clang/lib/Basic/DiagnosticIDs.cpp
clang/lib/Basic/SourceManager.cpp
clang/lib/Driver/ToolChains/Clang.cpp
clang/lib/Format/Format.cpp
clang/lib/Frontend/FrontendActions.cpp
clang/lib/Sema/SemaChecking.cpp
clang/lib/Sema/SemaDecl.cpp
clang/lib/Sema/SemaDeclCXX.cpp
clang/lib/Sema/SemaExpr.cpp
clang/lib/Sema/SemaExprCXX.cpp
clang/lib/Sema/SemaLookup.cpp
clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
clang/lib/StaticAnalyzer/Checkers/MIGChecker.cpp
clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
clang/lib/StaticAnalyzer/Core/Store.cpp
clang/lib/Tooling/Syntax/Tree.cpp

Removed: 




diff  --git a/clang/include/clang/AST/Redeclarable.h 
b/clang/include/clang/AST/Redeclarable.h
index 77b827c52bfb3..58ec07973920c 100644
--- a/clang/include/clang/AST/Redeclarable.h
+++ b/clang/include/clang/AST/Redeclarable.h
@@ -258,7 +258,8 @@ class Redeclarable {
 
 redecl_iterator& operator++() {
   assert(Current && "Advancing while iterator has reached end");
-  // Sanity check to avoid infinite loop on invalid redecl chain.
+  // Make sure we don't infinitely loop on an invalid redecl chain. This
+  // should never happen.
   if (Current->isFirstDecl()) {
 if (PassedFirst) {
   assert(0 && "Passed first decl twice, invalid redecl chain!");

diff  --git a/clang/include/clang/Analysis/CFG.h 
b/clang/include/clang/Analysis/CFG.h
index f9223fe58a27a..3b9b22e87f35c 100644
--- a/clang/include/clang/Analysis/CFG.h
+++ b/clang/include/clang/Analysis/CFG.h
@@ -515,7 +515,7 @@ class CFGTerminator {
 /// of the most derived class while we're in the base class.
 VirtualBaseBranch,
 
-/// Number of 
diff erent kinds, for sanity checks. We subtract 1 so that
+/// Number of 
diff erent kinds, for validity checks. We subtract 1 so that
 /// to keep receiving compiler warnings when we don't cover all enum values
 /// in a switch.
 NumKindsMinusOne = VirtualBaseBranch

diff  --git a/clang/include/clang/CodeGen/CGFunctionInfo.h 
b/clang/include/clang/CodeGen/CGFunctionInfo.h
index 4899c9deda6a3..cd6c7e2e31287 100644
--- a/clang/include/clang/CodeGen/CGFunctionInfo.h
+++ b/clang/include/clang/CodeGen/CGFunctionInfo.h
@@ -250,7 +250,7 @@ class ABIArgInfo {
   static ABIArgInfo getCoerceAndExpand(llvm::StructType *coerceToType,
llvm::Type *unpaddedCoerceToType) {
 #ifndef NDEBUG
-// Sanity checks on unpaddedCoerceToType.
+// Check that unpaddedCoerceToType has roughly the right shape.
 
 // Assert that we only have a struct type if there are multiple elements.
 auto unpaddedStruct = dyn_cast(unpaddedCoerceToType);

diff  --git a/clang/include/clang/Sema/Lookup.h 
b/clang/include/clang/Sema/Lookup.h
index c6edc2df5b9f6..54fe7081b7105 100644
--- a/clang/include/clang/Sema/Lookup.h
+++ b/clang/include/clang/Sema/Lookup.h
@@ -319,7 +319,7 @@ class LookupResult {
   }
 
   LookupResultKind getResultKind() const {
-assert(sanity());
+assert(checkDebugAssumptions());
 return ResultKind;
   }
 
@@ -706,10 +706,9 @@ class LookupResult {
   void addDeclsFromBasePaths(const CXXBasePaths &P);
   void configure();
 
-  // Sanity checks.
-  bool sanity() const;
+  bool checkDebugAssumptions() const;
 
-  bool sanityCheckUnresolved() const {
+  bool checkUnresolved() const {
 for (iterator I = begin(), E = end(); I != E; ++I)
   if (isa((*I)->getUnderlyingDecl()))
 return true;

diff  --git a/clang/lib/Analysis/BodyFarm.cpp b/clang/lib/Analysis/BodyFarm.cpp
index 49ac74c233bd6..92c236ed9080c 100644
--- a/clang/lib/Analysis/BodyFarm.cpp
+++ b/clang/lib/Analysis/BodyFarm.cpp
@@ -790,9 +790,8 @@ static Stmt *createObjCPropertyGetter(ASTContext &Ctx,
 }
   }
 
-  // Sanity check that the property is the same type as the ivar, or a
-  // reference to it, and that it is either an o

[PATCH] D114025: [clang][NFC] Inclusive terms: replace some uses of sanity in clang

2021-11-19 Thread Zarko Todorovski via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGd8e5a0c42bd8: [clang][NFC] Inclusive terms: replace some 
uses of sanity in clang (authored by ZarkoCA).

Changed prior to commit:
  https://reviews.llvm.org/D114025?vs=388550&id=388587#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114025

Files:
  clang/include/clang/AST/Redeclarable.h
  clang/include/clang/Analysis/CFG.h
  clang/include/clang/CodeGen/CGFunctionInfo.h
  clang/include/clang/Sema/Lookup.h
  clang/lib/Analysis/BodyFarm.cpp
  clang/lib/Analysis/RetainSummaryManager.cpp
  clang/lib/Basic/DiagnosticIDs.cpp
  clang/lib/Basic/SourceManager.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Format/Format.cpp
  clang/lib/Frontend/FrontendActions.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaExprCXX.cpp
  clang/lib/Sema/SemaLookup.cpp
  clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/MIGChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
  clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
  clang/lib/StaticAnalyzer/Core/Store.cpp
  clang/lib/Tooling/Syntax/Tree.cpp

Index: clang/lib/Tooling/Syntax/Tree.cpp
===
--- clang/lib/Tooling/Syntax/Tree.cpp
+++ clang/lib/Tooling/Syntax/Tree.cpp
@@ -126,7 +126,7 @@
   for (auto *N = New; N; N = N->NextSibling) {
 assert(N->Parent == nullptr);
 assert(N->getRole() != NodeRole::Detached && "Roles must be set");
-// FIXME: sanity-check the role.
+// FIXME: validate the role.
   }
 
   auto Reachable = [](Node *From, Node *N) {
Index: clang/lib/StaticAnalyzer/Core/Store.cpp
===
--- clang/lib/StaticAnalyzer/Core/Store.cpp
+++ clang/lib/StaticAnalyzer/Core/Store.cpp
@@ -249,7 +249,7 @@
 }
 
 SVal StoreManager::evalDerivedToBase(SVal Derived, const CastExpr *Cast) {
-  // Sanity check to avoid doing the wrong thing in the face of
+  // Early return to avoid doing the wrong thing in the face of
   // reinterpret_cast.
   if (!regionMatchesCXXRecordType(Derived, Cast->getSubExpr()->getType()))
 return UnknownVal();
Index: clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
===
--- clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -326,8 +326,8 @@
 }
 Result = InitWithAdjustments;
   } else {
-// We need to create a region no matter what. For sanity, make sure we don't
-// try to stuff a Loc into a non-pointer temporary region.
+// We need to create a region no matter what. Make sure we don't try to
+// stuff a Loc into a non-pointer temporary region.
 assert(!InitValWithAdjustments.getAs() ||
Loc::isLocType(Result->getType()) ||
Result->getType()->isMemberPointerType());
Index: clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
===
--- clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -1670,9 +1670,10 @@
   if (isUnderconstrained(PrevN)) {
 IsSatisfied = true;
 
-// As a sanity check, make sure that the negation of the constraint
-// was infeasible in the current state.  If it is feasible, we somehow
-// missed the transition point.
+// At this point, the negation of the constraint should be infeasible. If it
+// is feasible, make sure that the negation of the constrainti was
+// infeasible in the current state.  If it is feasible, we somehow missed
+// the transition point.
 assert(!isUnderconstrained(N));
 
 // We found the transition point for the constraint.  We now need to
Index: clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
@@ -182,8 +182,7 @@
   ProgramStateRef state = C.getState();
 
   if (CE->getNumArgs() < MinArgCount) {
-// The frontend should issue a warning for this case, so this is a sanity
-// check.
+// The frontend should issue a warning for this case. Just return.
 return;
   } else if (CE->getNumArgs() == MaxArgCount) {
 const Expr *Arg = CE->getArg(CreateModeArgIndex);
@@ -366,7 +365,7 @@
  const unsigned numArgs,
  const unsigned sizeArg,
  const char *fn) const 

[PATCH] D113946: [libc][clang-tidy] fix namespace check for externals

2021-11-19 Thread Michael Jones via Phabricator via cfe-commits
michaelrj updated this revision to Diff 388588.
michaelrj marked 3 inline comments as done.
michaelrj added a comment.

address comments and rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113946

Files:
  clang-tools-extra/clang-tidy/llvmlibc/CalleeNamespaceCheck.cpp
  clang-tools-extra/test/clang-tidy/checkers/llvmlibc-callee-namespace.cpp
  libc/docs/clang_tidy_checks.rst
  libc/src/__support/FPUtil/NearestIntegerOperations.h
  libc/src/__support/str_to_float.h
  libc/src/__support/str_to_integer.h
  libc/src/math/generic/math_utils.h
  libc/src/string/strdup.cpp
  libc/src/string/strndup.cpp

Index: libc/src/string/strndup.cpp
===
--- libc/src/string/strndup.cpp
+++ libc/src/string/strndup.cpp
@@ -23,7 +23,7 @@
   size_t len = internal::string_length(src);
   if (len > size)
 len = size;
-  char *dest = reinterpret_cast(::malloc(len + 1)); // NOLINT
+  char *dest = reinterpret_cast(::malloc(len + 1));
   if (dest == nullptr)
 return nullptr;
   char *result =
Index: libc/src/string/strdup.cpp
===
--- libc/src/string/strdup.cpp
+++ libc/src/string/strdup.cpp
@@ -21,7 +21,7 @@
 return nullptr;
   }
   size_t len = internal::string_length(src) + 1;
-  char *dest = reinterpret_cast(::malloc(len)); // NOLINT
+  char *dest = reinterpret_cast(::malloc(len));
   if (dest == nullptr) {
 return nullptr;
   }
Index: libc/src/math/generic/math_utils.h
===
--- libc/src/math/generic/math_utils.h
+++ libc/src/math/generic/math_utils.h
@@ -55,7 +55,7 @@
 
 template  static inline T with_errno(T x, int err) {
   if (math_errhandling & MATH_ERRNO)
-errno = err; // NOLINT
+errno = err;
   return x;
 }
 
Index: libc/src/__support/str_to_integer.h
===
--- libc/src/__support/str_to_integer.h
+++ libc/src/__support/str_to_integer.h
@@ -74,7 +74,7 @@
   const char *original_src = src;
 
   if (base < 0 || base == 1 || base > 36) {
-errno = EINVAL; // NOLINT
+errno = EINVAL;
 return 0;
   }
 
@@ -114,19 +114,19 @@
 // the result cannot change, but we still need to advance src to the end of
 // the number.
 if (result == ABS_MAX) {
-  errno = ERANGE; // NOLINT
+  errno = ERANGE;
   continue;
 }
 
 if (result > ABS_MAX_DIV_BY_BASE) {
   result = ABS_MAX;
-  errno = ERANGE; // NOLINT
+  errno = ERANGE;
 } else {
   result = result * base;
 }
 if (result > ABS_MAX - cur_digit) {
   result = ABS_MAX;
-  errno = ERANGE; // NOLINT
+  errno = ERANGE;
 } else {
   result = result + cur_digit;
 }
Index: libc/src/__support/str_to_float.h
===
--- libc/src/__support/str_to_float.h
+++ libc/src/__support/str_to_float.h
@@ -200,7 +200,7 @@
   static_cast(fputil::FloatProperties::exponentBias)) {
 *outputMantissa = 0;
 *outputExp2 = fputil::FPBits::maxExponent;
-errno = ERANGE; // NOLINT
+errno = ERANGE;
 return;
   }
   // If the exponent is too small even for a subnormal, return 0.
@@ -210,7 +210,7 @@
fputil::FloatProperties::mantissaWidth)) {
 *outputMantissa = 0;
 *outputExp2 = 0;
-errno = ERANGE; // NOLINT
+errno = ERANGE;
 return;
   }
 
@@ -253,7 +253,7 @@
   if (exp2 >= fputil::FPBits::maxExponent) {
 *outputMantissa = 0;
 *outputExp2 = fputil::FPBits::maxExponent;
-errno = ERANGE; // NOLINT
+errno = ERANGE;
 return;
   }
 
@@ -289,7 +289,7 @@
   }
 
   if (exp2 == 0) {
-errno = ERANGE; // NOLINT
+errno = ERANGE;
   }
 
   *outputMantissa = finalMantissa;
@@ -391,7 +391,7 @@
   static_cast(fputil::FloatProperties::exponentBias) / 3) {
 *outputMantissa = 0;
 *outputExp2 = fputil::FPBits::maxExponent;
-errno = ERANGE; // NOLINT
+errno = ERANGE;
 return;
   }
   // If the exponent is too small even for a subnormal, return 0.
@@ -402,7 +402,7 @@
   2) {
 *outputMantissa = 0;
 *outputExp2 = 0;
-errno = ERANGE; // NOLINT
+errno = ERANGE;
 return;
   }
 
@@ -467,7 +467,7 @@
 // This indicates an overflow, so we make the result INF and set errno.
 *outputExp2 = (1 << fputil::FloatProperties::exponentWidth) - 1;
 *outputMantissa = 0;
-errno = ERANGE; // NOLINT
+errno = ERANGE;
 return;
   }
 
@@ -483,7 +483,7 @@
   // Return 0 if the exponent is too small.
   *outputMantissa = 0;
   *outputExp2 = 0;
-  errno = ERANGE; // NOLINT
+  errno = ERANGE;
   return;
 }
   }
@@ -511,12 +511,12 @@
 ++biasedExponent;
 
 if (biasedExponent == INF_EXP) {
-  errno = ERANGE; // NOLINT
+  errno = ERANGE;
 

[PATCH] D112773: Allow __attribute__((swift_attr)) in attribute push pragmas

2021-11-19 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman added a comment.

I will commit this on behalf of @beccadax as she doesn't have commit access yet.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112773

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


  1   2   >