[PATCH] D103228: [PoC][RISCV] Using pragma to register vector intrinsic

2021-05-27 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added inline comments.



Comment at: clang/lib/Sema/SemaRISCV.cpp:21
+  PP.getIdentifierTable(), PP.getLangOpts(), Builtin::RISCV_VECTOR_KIND);
+  Builtin::RegisterOverloadBuiltinFunc F = [](Sema &S, const Builtin::Info &BI,
+  unsigned ID) {

Can we capture Sema in the lambda capture list here so that it's not really 
passed to initializeTargetOverloadBuiltins. I don't think forward declaring 
Sema in Builtins.h is a good idea since the "Basic" library isn't supposed to 
know about Sema. That probably means you need to use a std::function instead of 
a function pointer.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103228

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


[PATCH] D103228: [PoC][RISCV] Using pragma to register vector intrinsic

2021-05-27 Thread Kito Cheng via Phabricator via cfe-commits
kito-cheng added inline comments.



Comment at: clang/lib/Sema/SemaRISCV.cpp:21
+  PP.getIdentifierTable(), PP.getLangOpts(), Builtin::RISCV_VECTOR_KIND);
+  Builtin::RegisterOverloadBuiltinFunc F = [](Sema &S, const Builtin::Info &BI,
+  unsigned ID) {

craig.topper wrote:
> Can we capture Sema in the lambda capture list here so that it's not really 
> passed to initializeTargetOverloadBuiltins. I don't think forward declaring 
> Sema in Builtins.h is a good idea since the "Basic" library isn't supposed to 
> know about Sema. That probably means you need to use a std::function instead 
> of a function pointer.
Thanks for the input, I am not family with modern C++ since GCC still using 
limited set of C++98 :P


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103228

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


[PATCH] D103229: [clang] NFC: split HeaderMapTest to have re-usable header map implementation for testing

2021-05-27 Thread Dmitry Polukhin via Phabricator via cfe-commits
DmitryPolukhin created this revision.
DmitryPolukhin added reviewers: dexonsmith, bruno.
DmitryPolukhin added a project: clang.
DmitryPolukhin requested review of this revision.

NFC changes required for https://reviews.llvm.org/D103142

Test Plan: check-clang


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D103229

Files:
  clang/unittests/Lex/HeaderMapTest.cpp
  clang/unittests/Lex/HeaderMapTestUtils.h

Index: clang/unittests/Lex/HeaderMapTestUtils.h
===
--- /dev/null
+++ clang/unittests/Lex/HeaderMapTestUtils.h
@@ -0,0 +1,100 @@
+//===- unittests/Lex/HeaderMapTestUtils.h - HeaderMap utils ---===//
+//
+// 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_UNITTESTS_LEX_HEADERMAPTESTUTILS_H
+#define LLVM_CLANG_UNITTESTS_LEX_HEADERMAPTESTUTILS_H
+
+#include "clang/Basic/CharInfo.h"
+#include "clang/Lex/HeaderMap.h"
+#include "clang/Lex/HeaderMapTypes.h"
+#include "llvm/Support/SwapByteOrder.h"
+#include 
+
+namespace clang {
+namespace test {
+
+// Lay out a header file for testing.
+template  struct HMapFileMock {
+  HMapHeader Header;
+  HMapBucket Buckets[NumBuckets];
+  unsigned char Bytes[NumBytes];
+
+  void init() {
+memset(this, 0, sizeof(HMapFileMock));
+Header.Magic = HMAP_HeaderMagicNumber;
+Header.Version = HMAP_HeaderVersion;
+Header.NumBuckets = NumBuckets;
+Header.StringsOffset = sizeof(Header) + sizeof(Buckets);
+  }
+
+  void swapBytes() {
+using llvm::sys::getSwappedBytes;
+Header.Magic = getSwappedBytes(Header.Magic);
+Header.Version = getSwappedBytes(Header.Version);
+Header.NumBuckets = getSwappedBytes(Header.NumBuckets);
+Header.StringsOffset = getSwappedBytes(Header.StringsOffset);
+  }
+
+  std::unique_ptr getBuffer() {
+return llvm::MemoryBuffer::getMemBuffer(
+StringRef(reinterpret_cast(this), sizeof(HMapFileMock)),
+"header",
+/* RequresNullTerminator */ false);
+  }
+};
+
+template  struct HMapFileMockMaker {
+  FileTy &File;
+  unsigned SI = 1;
+  unsigned BI = 0;
+  HMapFileMockMaker(FileTy &File) : File(File) {}
+
+  unsigned addString(StringRef S) {
+assert(SI + S.size() + 1 <= sizeof(File.Bytes));
+std::copy(S.begin(), S.end(), File.Bytes + SI);
+auto OldSI = SI;
+SI += S.size() + 1;
+return OldSI;
+  }
+
+  void addBucket(StringRef Str, unsigned Key, unsigned Prefix,
+ unsigned Suffix) {
+addBucket(getHash(Str), Key, Prefix, Suffix);
+  }
+
+  void addBucket(unsigned Hash, unsigned Key, unsigned Prefix,
+ unsigned Suffix) {
+assert(!(File.Header.NumBuckets & (File.Header.NumBuckets - 1)));
+unsigned I = Hash & (File.Header.NumBuckets - 1);
+do {
+  if (!File.Buckets[I].Key) {
+File.Buckets[I].Key = Key;
+File.Buckets[I].Prefix = Prefix;
+File.Buckets[I].Suffix = Suffix;
+++File.Header.NumEntries;
+return;
+  }
+  ++I;
+  I &= File.Header.NumBuckets - 1;
+} while (I != (Hash & (File.Header.NumBuckets - 1)));
+llvm_unreachable("no empty buckets");
+  }
+
+  // The header map hash function.
+  static unsigned getHash(StringRef Str) {
+unsigned Result = 0;
+for (char C : Str)
+  Result += toLowercase(C) * 13;
+return Result;
+  }
+};
+
+} // namespace test
+} // namespace clang
+
+#endif
Index: clang/unittests/Lex/HeaderMapTest.cpp
===
--- clang/unittests/Lex/HeaderMapTest.cpp
+++ clang/unittests/Lex/HeaderMapTest.cpp
@@ -6,89 +6,17 @@
 //
 //===--===//
 
-#include "clang/Basic/CharInfo.h"
-#include "clang/Lex/HeaderMap.h"
-#include "clang/Lex/HeaderMapTypes.h"
+#include "HeaderMapTestUtils.h"
 #include "llvm/ADT/SmallString.h"
-#include "llvm/Support/SwapByteOrder.h"
 #include "gtest/gtest.h"
-#include 
 #include 
 
 using namespace clang;
 using namespace llvm;
+using namespace clang::test;
 
 namespace {
 
-// Lay out a header file for testing.
-template  struct MapFile {
-  HMapHeader Header;
-  HMapBucket Buckets[NumBuckets];
-  unsigned char Bytes[NumBytes];
-
-  void init() {
-memset(this, 0, sizeof(MapFile));
-Header.Magic = HMAP_HeaderMagicNumber;
-Header.Version = HMAP_HeaderVersion;
-Header.NumBuckets = NumBuckets;
-Header.StringsOffset = sizeof(Header) + sizeof(Buckets);
-  }
-
-  void swapBytes() {
-using llvm::sys::getSwappedBytes;
-Header.Magic = getSwappedBytes(Header.Magic);
-Header.Version = getSwappedBytes(Header.Version);
-Header.NumBuckets = getSwappedBytes(Header.NumBuckets);
-Header.StringsOffset = getSwappedBytes(Header.StringsOffset);
-  }
-
-  std::

[PATCH] D103142: [clang][clangd] Use reverse header map lookup in suggestPathToFileForDiagnostics

2021-05-27 Thread Dmitry Polukhin via Phabricator via cfe-commits
DmitryPolukhin updated this revision to Diff 348183.
DmitryPolukhin marked 2 inline comments as done.
DmitryPolukhin added a comment.

Split changes into NFC https://reviews.llvm.org/D103229 and the rest


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103142

Files:
  clang/include/clang/Lex/HeaderMap.h
  clang/lib/Lex/HeaderMap.cpp
  clang/lib/Lex/HeaderSearch.cpp
  clang/unittests/Lex/HeaderSearchTest.cpp

Index: clang/unittests/Lex/HeaderSearchTest.cpp
===
--- clang/unittests/Lex/HeaderSearchTest.cpp
+++ clang/unittests/Lex/HeaderSearchTest.cpp
@@ -7,6 +7,7 @@
 //===--===//
 
 #include "clang/Lex/HeaderSearch.h"
+#include "HeaderMapTestUtils.h"
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/DiagnosticOptions.h"
 #include "clang/Basic/FileManager.h"
@@ -45,6 +46,21 @@
 Search.AddSearchPath(DL, /*isAngled=*/false);
   }
 
+  void addHeaderMap(llvm::StringRef Filename,
+std::unique_ptr Buf) {
+VFS->addFile(Filename, 0, std::move(Buf), /*User=*/None, /*Group=*/None,
+ llvm::sys::fs::file_type::regular_file);
+auto FE = FileMgr.getFile(Filename, true);
+assert(FE);
+
+// Test class supports only one HMap at a time.
+assert(!HMap);
+HMap = HeaderMap::Create(*FE, FileMgr);
+auto DL =
+DirectoryLookup(HMap.get(), SrcMgr::C_User, /*isFramework=*/false);
+Search.AddSearchPath(DL, /*isAngled=*/false);
+  }
+
   IntrusiveRefCntPtr VFS;
   FileSystemOptions FileMgrOpts;
   FileManager FileMgr;
@@ -55,6 +71,7 @@
   std::shared_ptr TargetOpts;
   IntrusiveRefCntPtr Target;
   HeaderSearch Search;
+  std::unique_ptr HMap;
 };
 
 TEST_F(HeaderSearchTest, NoSearchDir) {
@@ -136,5 +153,31 @@
 "y/z/t.h");
 }
 
+// Helper struct with null terminator character to make MemoryBuffer happy.
+template 
+struct NullTerminatedFile : public FileTy {
+  PaddingTy Padding = 0;
+};
+
+TEST_F(HeaderSearchTest, HeaderMapReverseLookup) {
+  typedef NullTerminatedFile, char> FileTy;
+  FileTy File;
+  File.init();
+
+  test::HMapFileMockMaker Maker(File);
+  auto a = Maker.addString("d.h");
+  auto b = Maker.addString("b/");
+  auto c = Maker.addString("c.h");
+  Maker.addBucket("d.h", a, b, c);
+
+  addHeaderMap("/x/y/z.hmap", File.getBuffer());
+  addSearchDir("/a");
+
+  EXPECT_EQ(Search.suggestPathToFileForDiagnostics("/a/b/c.h",
+   /*WorkingDir=*/"",
+   /*MainFile=*/""),
+"d.h");
+}
+
 } // namespace
 } // namespace clang
Index: clang/lib/Lex/HeaderSearch.cpp
===
--- clang/lib/Lex/HeaderSearch.cpp
+++ clang/lib/Lex/HeaderSearch.cpp
@@ -1834,7 +1834,7 @@
   };
 
   for (unsigned I = 0; I != SearchDirs.size(); ++I) {
-// FIXME: Support this search within frameworks and header maps.
+// FIXME: Support this search within frameworks.
 if (!SearchDirs[I].isNormalDir())
   continue;
 
@@ -1848,6 +1848,18 @@
   if (!BestPrefixLength && CheckDir(path::parent_path(MainFile)) && IsSystem)
 *IsSystem = false;
 
-
-  return path::convert_to_slash(File.drop_front(BestPrefixLength));
+  // Try resolving resulting filaname via reverse search in header maps,
+  // key from header name is user prefered name for the include file.
+  StringRef Filename = File.drop_front(BestPrefixLength);
+  for (unsigned I = 0; I != SearchDirs.size(); ++I) {
+if (SearchDirs[I].isHeaderMap()) {
+  StringRef SpelledFilename =
+  SearchDirs[I].getHeaderMap()->reverseLookupFilename(Filename);
+  if (!SpelledFilename.empty()) {
+Filename = SpelledFilename;
+break;
+  }
+}
+  }
+  return path::convert_to_slash(Filename);
 }
Index: clang/lib/Lex/HeaderMap.cpp
===
--- clang/lib/Lex/HeaderMap.cpp
+++ clang/lib/Lex/HeaderMap.cpp
@@ -240,3 +240,26 @@
 return StringRef(DestPath.begin(), DestPath.size());
   }
 }
+
+StringRef HeaderMapImpl::reverseLookupFilename(StringRef DestPath) const {
+  if (ReverseMap.empty()) {
+const HMapHeader &Hdr = getHeader();
+unsigned NumBuckets = getEndianAdjustedWord(Hdr.NumBuckets);
+for (unsigned i = 0; i != NumBuckets; ++i) {
+  HMapBucket B = getBucket(i);
+  if (B.Key == HMAP_EmptyBucketKey)
+continue;
+
+  Optional Key = getString(B.Key);
+  Optional Prefix = getString(B.Prefix);
+  Optional Suffix = getString(B.Suffix);
+  if (Key && Prefix && Suffix) {
+SmallVector Buf;
+Buf.append(Prefix->begin(), Prefix->end());
+Buf.append(Suffix->begin(), Suffix->end());
+ReverseMap[StringRef(Buf.begin(), Buf.size())] = *Key;
+  }
+}
+  }
+  return Revers

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

2021-05-27 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko added inline comments.



Comment at: clang/lib/StaticAnalyzer/Checkers/SmartPtr.h:57
+
+  void visitIfStmt(const ExplodedNode *Node, const ProgramStateRef State,
+   BugReporterContext &BRC, const Stmt *S,

IMO, these three `visit` functions are a bit confusing in their names. I guess, 
my expectation for a group of methods that have very similar names is that they 
have similar signatures. And here `visitIfStmt` doesn't return diagnostic piece 
as opposed to two other methods.
We are not bound here to name everything `visitABC` since these methods are not 
part of the visitor interface.
My suggestion here is to actually keep `visitIfStmt` because that's what you 
actually do here, you simply **visit** it. Maybe change the return type to bool 
(signifying that it was indeed an if statement), so we don't check for other 
possibilities.
As for other two functions, I'd prefer something like `emitNoteForAssignment` 
and `emitNoteForInitialization` to keep the naming pattern going.



Comment at: clang/lib/StaticAnalyzer/Checkers/SmartPtr.h:37
+
+class GetNoteVisitor : public BugReporterVisitor {
+private:

vsavchenko wrote:
> Sorry for picking on it again, but is it visiting "get notes"? Otherwise, it 
> is just a placeholder name that doesn't tell the reader what this class is 
> actually for.
> Also, is there a reason why it is declared in the header file and couldn't be 
> a part of `SmartPtrChecker.cpp` instead?
This comment is marked as "Done", but there is no code change nor justification.



Comment at: clang/lib/StaticAnalyzer/Checkers/SmartPtr.h:36
+
+class FindWhereConstrained : public BugReporterVisitor {
+private:

vsavchenko wrote:
> nit: class name should be a noun (functions and methods are verbs)
It is again some sort of verb. I don't know how to read it except for "emit 
note on get"-visitor. What about something like `GetNoteEmitter`? I mean do we 
really need to put `Visitor` in the name?



Comment at: clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp:111
 
+bool isStdSmartPtrCall(const CXXRecordDecl *Rec) {
+  if (!Rec || !Rec->getDeclContext()->isStdNamespace())

My guess is that it should be just `isStdSmartPtr`



Comment at: clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp:171
+
+PathDiagnosticPieceRef EmitNoteOnGetVisitor::emitBugReportAtGet(
+const ExplodedNode *Node, BugReporterContext &BRC, const Expr *E) {

I'm still here picking on names 😅 It doesn't emit "bug report" it emits "note".
And actually if you name your class as `GetNoteEmitter` or something similar 
you don't need to mention `get` here again.



Comment at: clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp:198-202
+  const auto *E = llvm::dyn_cast(S);
+  if (!E || E->getCastKind() != CastKind::CK_PointerToBoolean)
+return;
+  // Check if we are tracking the expression being casted
+  const Expr *Sub = E->getSubExpr();

I have two major questions about this implementation:

  - Why don't we need an actual check for `IfStmt`? Won't it trigger on `bool 
unused = !pointer;`? And if so it won't mean **constrained**.
  - Why do we only care about implicit pointer-to-bool conversion? What about 
situations like `pointer == nullptr`, `NULL != pointer`, 
`__builtin_expect(pointer, 0)`, etc?




Comment at: clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp:230
+  // If b is just a pointer, then we should add it to the set
+  if (const auto *ICE = llvm::dyn_cast(RHS)) {
+const Expr *Sub = ICE->getSubExpr();

It's better to use `IgnoreParenCasts` here as well.



Comment at: clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp:79
   {{"get"}, &SmartPtrModeling::handleGet}};
+  mutable llvm::ImmutableSet::Factory StmtSetFactory;
 };

vsavchenko wrote:
> I think it's better to use `REGISTER_SET_FACTORY_WITH_PROGRAMSTATE` instead 
> and keep factory as part of the state as well.
It is marked as "Done", but the code is same.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D97183

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


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

2021-05-27 Thread Deep Majumder via Phabricator via cfe-commits
RedDocMD added inline comments.



Comment at: clang/lib/StaticAnalyzer/Checkers/SmartPtr.h:37
+
+class GetNoteVisitor : public BugReporterVisitor {
+private:

vsavchenko wrote:
> Sorry for picking on it again, but is it visiting "get notes"? Otherwise, it 
> is just a placeholder name that doesn't tell the reader what this class is 
> actually for.
> Also, is there a reason why it is declared in the header file and couldn't be 
> a part of `SmartPtrChecker.cpp` instead?
Yes it is the line `const SVal *InnerPtr = 
State->get(ThisRegion);` in the `VisitNode` function. This 
uses the `TrackedRegionMap` which is defined in `SmartPtrModelling.cpp` but the 
visitor must be added to the bug-report in `SmartPtrChecker.cpp`.



Comment at: clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp:79
   {{"get"}, &SmartPtrModeling::handleGet}};
+  mutable llvm::ImmutableSet::Factory StmtSetFactory;
 };

vsavchenko wrote:
> I think it's better to use `REGISTER_SET_FACTORY_WITH_PROGRAMSTATE` instead 
> and keep factory as part of the state as well.
My bad, I should have put in the TODO.



Comment at: clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp:180
+  }
+  return std::shared_ptr();
+}

vsavchenko wrote:
> Just wondering if `return {};` will be sufficient here.
Yup



Comment at: clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp:632-633
+auto EmptySet = StmtSetFactory.getEmptySet();
+auto NewStmtSet = StmtSetFactory.add(EmptySet, CallExpr);
+State = State->set(ThisRegion, NewStmtSet);
+  }

vsavchenko wrote:
> I generally don't like repeating code in both branches of the `if` statement.
> Here they share the following logic: add `CallExpr` and update the state.
> We can easily update the code to share the code:
> ```
> const auto *ExistingSet = State->get(ThisRegion);
> auto BaseSet = ExistingSet ? *ExistingSet : StmtSetFactory.getEmptySet();
> auto NewStmtSet = StmtSetFactory.add(BaseSet, CallExpr);
> State = State->set(ThisRegion, NewStmtSet);
> ```
Right, thanks :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D97183

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


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

2021-05-27 Thread Deep Majumder via Phabricator via cfe-commits
RedDocMD added a comment.

My bad! I forgot to submit the replies.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D97183

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


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

2021-05-27 Thread Deep Majumder via Phabricator via cfe-commits
RedDocMD marked 9 inline comments as done.
RedDocMD added inline comments.



Comment at: clang/lib/StaticAnalyzer/Checkers/SmartPtr.h:36
+
+class FindWhereConstrained : public BugReporterVisitor {
+private:

vsavchenko wrote:
> vsavchenko wrote:
> > nit: class name should be a noun (functions and methods are verbs)
> It is again some sort of verb. I don't know how to read it except for "emit 
> note on get"-visitor. What about something like `GetNoteEmitter`? I mean do 
> we really need to put `Visitor` in the name?
I put in `Visitor` because all the visitors that I have come across end with 
*Visitor*. But then again, I am sure that if we look, we'll find 
counter-examples. So your call here ...


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D97183

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


[PATCH] D103191: [OpenCL] Add support of __opencl_c_program_scope_global_variables feature macro

2021-05-27 Thread Sven van Haastregt via Phabricator via cfe-commits
svenvh added inline comments.



Comment at: clang/test/SemaOpenCL/storageclass.cl:22
+extern generic float g_generic_extern_var;
+#ifndef __opencl_c_program_scope_global_variables
+// expected-error@-17 {{program scope variable must reside in constant address 
space}}

Not sure if this is the best way to restructure this test?  Now the diagnostics 
are quite far away from the declarations, and it is harder to see which 
diagnostic belongs to which declaration.

I wonder if the following would be a better structure instead:
```
int G3 = 0;
#ifndef __opencl_c_program_scope_global_variables
// expected-error@-2 {{program scope variable must reside in constant address 
space}}
#endif

global int G4 = 0;
#ifndef __opencl_c_program_scope_global_variables
// expected-error@-2 {{program scope variable must reside in constant address 
space}}
#endif

... etc. ...
```

The downside is that it is a bit more verbose due to the repetition of the 
`#if` guards, but it makes the test more readable/maintainable in my opinion.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103191

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


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

2021-05-27 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko added inline comments.



Comment at: clang/lib/StaticAnalyzer/Checkers/SmartPtr.h:37
+
+class GetNoteVisitor : public BugReporterVisitor {
+private:

vsavchenko wrote:
> RedDocMD wrote:
> > vsavchenko wrote:
> > > Sorry for picking on it again, but is it visiting "get notes"? Otherwise, 
> > > it is just a placeholder name that doesn't tell the reader what this 
> > > class is actually for.
> > > Also, is there a reason why it is declared in the header file and 
> > > couldn't be a part of `SmartPtrChecker.cpp` instead?
> > Yes it is the line `const SVal *InnerPtr = 
> > State->get(ThisRegion);` in the `VisitNode` function. 
> > This uses the `TrackedRegionMap` which is defined in 
> > `SmartPtrModelling.cpp` but the visitor must be added to the bug-report in 
> > `SmartPtrChecker.cpp`.
> This comment is marked as "Done", but there is no code change nor 
> justification.
I see. IMO it still means that the visitor belongs with the checker and was put 
into this header as a workaround.
So maybe instead we can add `getInnerPointer(const ProgramStateRef State, const 
MemRegion *ThisRegion)` since we already have a very similar `isNullSmartPtr` 
in this header.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D97183

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


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

2021-05-27 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko added inline comments.



Comment at: clang/lib/StaticAnalyzer/Checkers/SmartPtr.h:36
+
+class FindWhereConstrained : public BugReporterVisitor {
+private:

RedDocMD wrote:
> vsavchenko wrote:
> > vsavchenko wrote:
> > > nit: class name should be a noun (functions and methods are verbs)
> > It is again some sort of verb. I don't know how to read it except for "emit 
> > note on get"-visitor. What about something like `GetNoteEmitter`? I mean do 
> > we really need to put `Visitor` in the name?
> I put in `Visitor` because all the visitors that I have come across end with 
> *Visitor*. But then again, I am sure that if we look, we'll find 
> counter-examples. So your call here ...
That's true, but it doesn't mean that we shouldn't care about the names and how 
they read.  You cannot say that you visit "emit note on get", so the name 
doesn't help to understand what this class does. If you want to name it 
`GetVisitor` - no problem because it does visit `get`s.  But if you want to 
state in the name that it emits notes on gets, the name should say `Emitter`, 
and that second name is more specific.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D97183

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


[PATCH] D103142: [clang][clangd] Use reverse header map lookup in suggestPathToFileForDiagnostics

2021-05-27 Thread Dmitry Polukhin via Phabricator via cfe-commits
DmitryPolukhin added a subscriber: bkramer.
DmitryPolukhin added a comment.

In D103142#2783665 , @dexonsmith 
wrote:

> Naively, this sounds like it could be a non-trivial tax on build times. But 
> it looks like it's only called in Clang from `Sema::diagnoseMissingImport`, 
> which only happens on error anyway.

Yes, in Clang `suggestPathToFileForDiagnostics` is used only in 
`Sema::diagnoseMissingImport`. In addition to clangd this function is also used 
in clang-include-fixer but new logic should also work there too (add @bkramer 
author of clang-include-fixer). This diff builds reverse index lazy only when 
it is required so it shouldn't normal build speed.




Comment at: clang/lib/Lex/HeaderSearch.cpp:1855
+  for (unsigned I = 0; I != SearchDirs.size(); ++I) {
+if (SearchDirs[I].isHeaderMap()) {
+  StringRef SpelledFilename =

bruno wrote:
> Can we save some dir scanning time by adding this logic to the previous loop? 
> Shouldn't get hard to read if you early `continue` for each failed condition.
It seems that unfortunately no, because we need the previous loop to convert 
absolute path into relative and this loop to convert relative path to key in 
header map. Normal header lookup also happens as two lookups: first lookup uses 
header map to convert key to relative path and then another lookup of the 
relative path.



Comment at: clang/lib/Lex/HeaderSearch.cpp:1855
+  for (unsigned I = 0; I != SearchDirs.size(); ++I) {
+if (SearchDirs[I].isHeaderMap()) {
+  StringRef SpelledFilename =

DmitryPolukhin wrote:
> bruno wrote:
> > Can we save some dir scanning time by adding this logic to the previous 
> > loop? Shouldn't get hard to read if you early `continue` for each failed 
> > condition.
> It seems that unfortunately no, because we need the previous loop to convert 
> absolute path into relative and this loop to convert relative path to key in 
> header map. Normal header lookup also happens as two lookups: first lookup 
> uses header map to convert key to relative path and then another lookup of 
> the relative path.
It seems that unfortunately no, because we need the previous loop to convert 
absolute path into relative and this loop to convert relative path to key in 
header map. Normal header lookup also happens as two lookups: first lookup uses 
header map to convert key to relative path and then another lookup of the 
relative path.



Comment at: clang/lib/Lex/HeaderSearch.cpp:1859
+  if (!SpelledFilename.empty()) {
+Filename = SpelledFilename;
+break;

bruno wrote:
> I guess one of the rationale behind this change is that whatever is consuming 
> your diagnostics is expecting the hmap key entry as an actionable path they 
> could use.
> 
> I wonder whether other consumers of `suggestPathToFileForDiagnostics` expect 
> an actual mapped value or just don't care. If the former, this might be 
> better under some flag.
> 
> @dexonsmith @vsapsai @JDevlieghere @arphaman how does this relate with what 
> you expect out of `suggestPathToFileForDiagnostics`? (If at all).
I think it is safe to change default behaviour without introducing new 
flag/option because I don't expect that anyone really needs value from header 
map search in the source.



Comment at: clang/unittests/Lex/HeaderMapTest.cpp:9
 
-#include "clang/Basic/CharInfo.h"
-#include "clang/Lex/HeaderMap.h"
-#include "clang/Lex/HeaderMapTypes.h"
+#include "HeaderMapTestUtils.h"
 #include "llvm/ADT/SmallString.h"

dexonsmith wrote:
> Splitting this out seems like a great idea, but please split it out to a 
> separate prep commit that's NFC.
Done, https://reviews.llvm.org/D103229


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103142

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


[PATCH] D103231: [clang][AST] Set correct DeclContext in ASTImporter lookup table for ParmVarDecl.

2021-05-27 Thread Balázs Kéri via Phabricator via cfe-commits
balazske created this revision.
Herald added subscribers: whisperity, martong, teemperor, gamesh411, Szelethus, 
dkrupp, kristof.beyls.
Herald added a reviewer: a.sidorin.
Herald added a reviewer: shafik.
balazske requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

ParmVarDecl is created with translation unit as the parent DeclContext
and later moved to the correct DeclContext. ASTImporterLookupTable
should be updated at this move.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D103231

Files:
  clang/include/clang/AST/ASTImporterLookupTable.h
  clang/lib/AST/ASTImporter.cpp
  clang/lib/AST/ASTImporterLookupTable.cpp
  clang/unittests/AST/ASTImporterTest.cpp

Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -5341,6 +5341,33 @@
   CheckError(FromFooC);
 }
 
+TEST_P(ErrorHandlingTest, ODRViolationWithinParmVarDecls) {
+  // Importing of 'f' and parameter 'P' should cause an ODR error.
+  // The error happens after the ParmVarDecl for 'P' was already created.
+  // This is a special case because the ParmVarDecl has a temporary DeclContext.
+  // Expected is no crash at error handling of ASTImporter.
+  constexpr auto ToTUCode = R"(
+  struct X {
+char A;
+  };
+  )";
+  constexpr auto FromTUCode = R"(
+  struct X {
+enum Y { Z };
+  };
+  void f(int P = X::Z);
+  )";
+  Decl *ToTU = getToTuDecl(ToTUCode, Lang_CXX11);
+  static_cast(ToTU);
+  Decl *FromTU = getTuDecl(FromTUCode, Lang_CXX11);
+  auto *FromF = FirstDeclMatcher().match(
+  FromTU, functionDecl(hasName("f")));
+  ASSERT_TRUE(FromF);
+
+  auto *ImportedF = Import(FromF, Lang_CXX11);
+  EXPECT_FALSE(ImportedF);
+}
+
 TEST_P(ASTImporterOptionSpecificTestBase, LambdaInFunctionBody) {
   Decl *FromTU = getTuDecl(
   R"(
@@ -6158,6 +6185,23 @@
   ASSERT_TRUE(ToD);
 }
 
+TEST_P(ImportFunctions, ParmVarDeclDeclContext) {
+  constexpr auto FromTUCode = R"(
+  void f(int P);
+  )";
+  Decl *FromTU = getTuDecl(FromTUCode, Lang_CXX11);
+  auto *FromF = FirstDeclMatcher().match(
+  FromTU, functionDecl(hasName("f")));
+  ASSERT_TRUE(FromF);
+
+  auto *ImportedF = Import(FromF, Lang_CXX11);
+  EXPECT_TRUE(ImportedF);
+  EXPECT_FALSE(
+  SharedStatePtr->getLookupTable()
+  ->lookup(ImportedF, ImportedF->getParamDecl(0)->getDeclName())
+  .empty());
+}
+
 // FIXME Move these tests out of ASTImporterTest. For that we need to factor
 // out the ASTImporter specific pars from ASTImporterOptionSpecificTestBase
 // into a new test Fixture. Then we should lift up this Fixture to its own
Index: clang/lib/AST/ASTImporterLookupTable.cpp
===
--- clang/lib/AST/ASTImporterLookupTable.cpp
+++ clang/lib/AST/ASTImporterLookupTable.cpp
@@ -117,6 +117,17 @@
 remove(ReDC, ND);
 }
 
+void ASTImporterLookupTable::update(NamedDecl *ND, DeclContext *OldDC) {
+  assert(OldDC != ND->getDeclContext());
+  if (!lookup(ND->getDeclContext(), ND->getDeclName()).empty()) {
+assert(lookup(OldDC, ND->getDeclName()).empty());
+return;
+  }
+
+  remove(OldDC, ND);
+  add(ND);
+}
+
 ASTImporterLookupTable::LookupResult
 ASTImporterLookupTable::lookup(DeclContext *DC, DeclarationName Name) const {
   auto DCI = LookupTable.find(DC->getPrimaryContext());
Index: clang/lib/AST/ASTImporter.cpp
===
--- clang/lib/AST/ASTImporter.cpp
+++ clang/lib/AST/ASTImporter.cpp
@@ -3501,6 +3501,8 @@
   for (auto *Param : Parameters) {
 Param->setOwningFunction(ToFunction);
 ToFunction->addDeclInternal(Param);
+if (ASTImporterLookupTable *LT = Importer.SharedState->getLookupTable())
+  LT->update(Param, Importer.getToContext().getTranslationUnitDecl());
   }
   ToFunction->setParams(Parameters);
 
Index: clang/include/clang/AST/ASTImporterLookupTable.h
===
--- clang/include/clang/AST/ASTImporterLookupTable.h
+++ clang/include/clang/AST/ASTImporterLookupTable.h
@@ -63,6 +63,18 @@
   ASTImporterLookupTable(TranslationUnitDecl &TU);
   void add(NamedDecl *ND);
   void remove(NamedDecl *ND);
+  // Sometimes a declaration is created first with a temporarily value of decl
+  // context (often the translation unit) and later moved to the final context.
+  // This happens for declarations that are created before the final declaration
+  // context. In such cases the lookup table needs to be updated.
+  // (The declaration is in these cases not added to the temporary decl context,
+  // only its parent is set.)
+  // FIXME: It would be better to not add the declaration to the temporary
+  // context at all in the lookup table, but this requires big change in
+  // ASTImporter.
+  // The function shoul

[PATCH] D102839: [RISCV][Clang] Add -mno-div option to disable hardware int division

2021-05-27 Thread Luís Marques via Phabricator via cfe-commits
luismarques added a comment.

In D102839#2783636 , @ksyx wrote:

> So it seems the better way to do this would definitely by adding a 
> subextension as the spec had changed. But I'd like  also to ask how will GCC 
> deal with this option, and should we make this option an alias to turn off M 
> extension and turn on ZMMul extension?

Regarding "turn off M extension", see Krste's comment in the PR:

> I think -mno-div is OK as a compiler option, but it's meaning is for the 
> compiler not to generate divide instructions, not to indicate what the ISA 
> is. So for example, -mno-div should not set ELF flags in binary to indicate 
> ISA doesn't have divide - it should simply not generate divide instructions.


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

https://reviews.llvm.org/D102839

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


[PATCH] D103204: [clang-format] New BreakInheritanceList style AfterComma

2021-05-27 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay requested changes to this revision.
MyDeveloperDay added a comment.
This revision now requires changes to proceed.

Adding such a feature like this needs unit tests, it won't be let in without 
them, you need to add them to clang/unittest/Format/Format.cpp

You also need to update the ReleaseNotes.rst to mention this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103204

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


[PATCH] D91949: [clang-format] Add BeforeStructInitialization option in BraceWrapping configuration

2021-05-27 Thread Anastasiia Lukianenko via Phabricator via cfe-commits
anastasiia_lukianenko updated this revision to Diff 348205.
anastasiia_lukianenko edited the summary of this revision.

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

https://reviews.llvm.org/D91949

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/include/clang/Format/Format.h
  clang/lib/Format/Format.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
@@ -5069,6 +5069,114 @@
 format(Input, Style));
 }
 
+TEST_F(FormatTest, BreakBeforeClassStructInit) {
+  FormatStyle Style = getLLVMStyle();
+  Style.ColumnLimit = 80;
+  Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+  Style.BraceWrapping.BeforeClassStructInit = true;
+  Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_No;
+  verifyFormat("struct new_struct struct_name =\n"
+   "{a = 1};",
+   Style);
+  verifyFormat("class new_class class_name =\n"
+   "{a = 1};",
+   Style);
+  verifyFormat("struct new_struct struct_name =\n"
+   "{a = 1, b = 2};",
+   Style);
+  verifyFormat("struct new_struct struct_name =\n"
+   "{\n"
+   "a = 1,\n"
+   "b = 2,\n"
+   "};",
+   Style);
+  verifyFormat("typedef struct Foo =\n"
+   "{\n"
+   "a = 1,\n"
+   "b = 2,\n"
+   "};",
+   Style);
+  verifyFormat("static constexpr struct Foo =\n"
+   "{\n"
+   "a = 1,\n"
+   "b = 2,\n"
+   "};",
+   Style);
+  verifyFormat("template <> struct Foo =\n"
+   "{\n"
+   "a = 1,\n"
+   "b = 2,\n"
+   "};",
+   Style);
+  verifyFormat("struct =\n"
+   "{\n"
+   "a = 1,\n"
+   "b = 2,\n"
+   "};",
+   Style);
+  // BeforeClassStructInit doesn't affect on AfterStruct behavior
+  Style.BraceWrapping.AfterStruct = false;
+  verifyFormat("struct new_struct struct_name {\n"
+   "  a = 1;\n"
+   "  b = 2;\n"
+   "};",
+   Style);
+  Style.BraceWrapping.AfterStruct = true;
+  verifyFormat("struct new_struct struct_name\n"
+   "{\n"
+   "  a = 1;\n"
+   "  b = 2;\n"
+   "};",
+   Style);
+  Style.BraceWrapping.BeforeClassStructInit = false;
+  verifyFormat("struct new_struct struct_name = {a = 1};", Style);
+  verifyFormat("struct new_struct struct_name = {a = 1, b = 2};", Style);
+  verifyFormat("struct new_struct struct_name = {\n"
+   "a = 1,\n"
+   "b = 2,\n"
+   "};",
+   Style);
+  verifyFormat("class new_class class_name = {\n"
+   "a = 1,\n"
+   "b = 2,\n"
+   "};",
+   Style);
+  verifyFormat("typedef struct Foo = {\n"
+   "a = 1,\n"
+   "b = 2,\n"
+   "};",
+   Style);
+  verifyFormat("static constexpr struct Foo = {\n"
+   "a = 1,\n"
+   "b = 2,\n"
+   "};",
+   Style);
+  verifyFormat("template <> struct Foo = {\n"
+   "a = 1,\n"
+   "b = 2,\n"
+   "};",
+   Style);
+  verifyFormat("struct = {\n"
+   "a = 1,\n"
+   "b = 2,\n"
+   "};",
+   Style);
+  // BeforeClassStructInit doesn't affect on AfterStruct behavior
+  Style.BraceWrapping.AfterStruct = false;
+  verifyFormat("struct new_struct struct_name {\n"
+   "  a = 1;\n"
+   "  b = 2;\n"
+   "};",
+   Style);
+  Style.BraceWrapping.AfterStruct = true;
+  verifyFormat("struct new_struct struct_name\n"
+   "{\n"
+   "  a = 1;\n"
+   "  b = 2;\n"
+   "};",
+   Style);
+}
+
 TEST_F(FormatTest, BreakConstructorInitializersAfterColon) {
   FormatStyle Style = getLLVMStyle();
   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
@@ -16328,6 +16436,7 @@
   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch);
   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse);
   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody);
+  CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeClassStructInit);
   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeWhile);
   CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces);
   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction);
Index: clang/lib/Format/UnwrappedLineParser.cpp

[PATCH] D102839: [RISCV][Clang] Add -mno-div option to disable hardware int division

2021-05-27 Thread ksyx via Phabricator via cfe-commits
ksyx updated this revision to Diff 348206.
ksyx marked an inline comment as done.
ksyx edited the summary of this revision.
ksyx added a comment.

Implemented Zmmul subextension, and let `no-div` to be using this subextension 
instead of M itself.


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

https://reviews.llvm.org/D102839

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Basic/Targets/RISCV.cpp
  clang/lib/Basic/Targets/RISCV.h
  clang/lib/Driver/ToolChains/Arch/RISCV.cpp
  clang/test/Driver/riscv-no-div.c
  llvm/lib/Target/RISCV/RISCV.td
  llvm/lib/Target/RISCV/RISCVISelLowering.cpp
  llvm/lib/Target/RISCV/RISCVInstrInfoM.td
  llvm/lib/Target/RISCV/RISCVSubtarget.h
  llvm/test/CodeGen/RISCV/zmmul.ll
  llvm/test/MC/RISCV/rv32i-invalid.s
  llvm/test/MC/RISCV/rv32zmmul-invaild.s
  llvm/test/MC/RISCV/rv32zmmul-valid.s
  llvm/test/MC/RISCV/rv64zmmul-invalid.s
  llvm/test/MC/RISCV/rv64zmmul-valid.s

Index: llvm/test/MC/RISCV/rv64zmmul-valid.s
===
--- /dev/null
+++ llvm/test/MC/RISCV/rv64zmmul-valid.s
@@ -0,0 +1,5 @@
+# RUN: llvm-mc %s -triple=riscv64 -mattr=+zmmul -riscv-no-aliases 2>&1 \
+# RUN:  | FileCheck -check-prefixes=CHECK-INST %s
+
+# CHECK-INST: mulw ra, sp, gp
+mulw ra, sp, gp
Index: llvm/test/MC/RISCV/rv64zmmul-invalid.s
===
--- /dev/null
+++ llvm/test/MC/RISCV/rv64zmmul-invalid.s
@@ -0,0 +1,14 @@
+# RUN: not llvm-mc %s -triple=riscv64 -mattr=+zmmul -riscv-no-aliases 2>&1 \
+# RUN:  | FileCheck -check-prefixes=CHECK-ERROR %s
+
+# CHECK-ERROR: 5:1: error: instruction requires the following: 'M' (Integer Multiplication and Division)
+divw tp, t0, t1
+
+# CHECK-ERROR: 8:1: error: instruction requires the following: 'M' (Integer Multiplication and Division)
+divuw t2, s0, s2
+
+# CHECK-ERROR: 11:1: error: instruction requires the following: 'M' (Integer Multiplication and Division)
+remw a0, a1, a2
+
+# CHECK-ERROR: 14:1: error: instruction requires the following: 'M' (Integer Multiplication and Division)
+remuw a3, a4, a5
Index: llvm/test/MC/RISCV/rv32zmmul-valid.s
===
--- /dev/null
+++ llvm/test/MC/RISCV/rv32zmmul-valid.s
@@ -0,0 +1,14 @@
+# RUN: llvm-mc %s -triple=riscv32 -mattr=+zmmul -riscv-no-aliases 2>&1 \
+# RUN:  | FileCheck -check-prefixes=CHECK-INST %s
+
+# CHECK-INST: mul a4, ra, s0
+mul a4, ra, s0
+
+# CHECK-INST: mulh ra, zero, zero
+mulh x1, x0, x0
+
+# CHECK-INST: mulhsu t0, t2, t1
+mulhsu t0, t2, t1
+
+# CHECK-INST: mulhu a5, a4, a3
+mulhu a5, a4, a3
Index: llvm/test/MC/RISCV/rv32zmmul-invaild.s
===
--- /dev/null
+++ llvm/test/MC/RISCV/rv32zmmul-invaild.s
@@ -0,0 +1,14 @@
+# RUN: not llvm-mc %s -triple=riscv32 -mattr=+zmmul -riscv-no-aliases 2>&1 \
+# RUN:  | FileCheck -check-prefixes=CHECK-ERROR %s
+
+# CHECK-ERROR: 5:1: error: instruction requires the following: 'M' (Integer Multiplication and Division)
+div s0, s0, s0
+
+# CHECK-ERROR: 8:1: error: instruction requires the following: 'M' (Integer Multiplication and Division)
+divu gp, a0, a1
+
+# CHECK-ERROR: 11:1: error: instruction requires the following: 'M' (Integer Multiplication and Division)
+rem s2, s2, s8
+
+# CHECK-ERROR: 14:1: error: instruction requires the following: 'M' (Integer Multiplication and Division)
+remu x18, x18, x24
Index: llvm/test/MC/RISCV/rv32i-invalid.s
===
--- llvm/test/MC/RISCV/rv32i-invalid.s
+++ llvm/test/MC/RISCV/rv32i-invalid.s
@@ -169,7 +169,7 @@
 xor s2, s2 # CHECK: :[[@LINE]]:1: error: too few operands for instruction
 
 # Instruction not in the base ISA
-mul a4, ra, s0 # CHECK: :[[@LINE]]:1: error: instruction requires the following: 'M' (Integer Multiplication and Division)
+div a4, ra, s0 # CHECK: :[[@LINE]]:1: error: instruction requires the following: 'M' (Integer Multiplication and Division)
 amomaxu.w s5, s4, (s3) # CHECK: :[[@LINE]]:1: error: instruction requires the following: 'A' (Atomic Instructions)
 fadd.s ft0, ft1, ft2 # CHECK: :[[@LINE]]:1: error: instruction requires the following: 'F' (Single-Precision Floating-Point)
 fadd.h ft0, ft1, ft2 # CHECK: :[[@LINE]]:1: error: instruction requires the following: 'Zfh' (Half-Precision Floating-Point)
Index: llvm/test/CodeGen/RISCV/zmmul.ll
===
--- /dev/null
+++ llvm/test/CodeGen/RISCV/zmmul.ll
@@ -0,0 +1,41 @@
+; RUN: llc -mtriple=riscv32 -mattr=+zmmul -verify-machineinstrs < %s \
+; RUN:  | not FileCheck -check-prefix=CHECK-DIV %s
+; RUN: llc -mtriple=riscv64 -mattr=+zmmul -verify-machineinstrs < %s \
+; RUN:  | not FileCheck -check-prefix=CHECK-DIV %s
+; RUN: llc -mtriple=riscv32 -mattr=+zmmul -verify-machineinstrs < %s \
+; RUN:  | not FileCheck -check-prefix=CHECK-REM %s
+; RUN: llc -mtriple=riscv64 -mattr=+zmmul -verify-ma

[PATCH] D103235: [SPE] Disable strict-fp for SPE by default

2021-05-27 Thread Qiu Chaofan via Phabricator via cfe-commits
qiucf created this revision.
qiucf added reviewers: nemanjai, jhibbits, vit9696, kpn.
Herald added subscribers: steven.zhang, kbarton.
qiucf requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

As discussed in PR50385 , 
strict-fp on PowerPC SPE has not been handled well. This patch disables it by 
default for SPE.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D103235

Files:
  clang/lib/Basic/Targets/PPC.cpp
  clang/test/CodeGen/builtins-ppc-fpconstrained.c


Index: clang/test/CodeGen/builtins-ppc-fpconstrained.c
===
--- clang/test/CodeGen/builtins-ppc-fpconstrained.c
+++ clang/test/CodeGen/builtins-ppc-fpconstrained.c
@@ -11,6 +11,9 @@
 // RUN: -fallow-half-arguments-and-returns -S -ffp-exception-behavior=strict \
 // RUN: -o - %s | FileCheck --check-prefix=CHECK-ASM \
 // RUN: --check-prefix=FIXME-CHECK  %s
+// RUN: %clang_cc1 -triple powerpcspe -S -ffp-exception-behavior=strict \
+// RUN: -target-feature +spe -fexperimental-strict-floating-point -emit-llvm \
+// RUN: %s -o - | FileCheck --check-prefix=CHECK-CONSTRAINED %s
 
 typedef __attribute__((vector_size(4 * sizeof(float float vec_float;
 typedef __attribute__((vector_size(2 * sizeof(double double vec_double;
Index: clang/lib/Basic/Targets/PPC.cpp
===
--- clang/lib/Basic/Targets/PPC.cpp
+++ clang/lib/Basic/Targets/PPC.cpp
@@ -59,6 +59,7 @@
 } else if (Feature == "+prefix-instrs") {
   HasPrefixInstrs = true;
 } else if (Feature == "+spe" || Feature == "+efpu2") {
+  HasStrictFP = false;
   HasSPE = true;
   LongDoubleWidth = LongDoubleAlign = 64;
   LongDoubleFormat = &llvm::APFloat::IEEEdouble();


Index: clang/test/CodeGen/builtins-ppc-fpconstrained.c
===
--- clang/test/CodeGen/builtins-ppc-fpconstrained.c
+++ clang/test/CodeGen/builtins-ppc-fpconstrained.c
@@ -11,6 +11,9 @@
 // RUN: -fallow-half-arguments-and-returns -S -ffp-exception-behavior=strict \
 // RUN: -o - %s | FileCheck --check-prefix=CHECK-ASM \
 // RUN: --check-prefix=FIXME-CHECK  %s
+// RUN: %clang_cc1 -triple powerpcspe -S -ffp-exception-behavior=strict \
+// RUN: -target-feature +spe -fexperimental-strict-floating-point -emit-llvm \
+// RUN: %s -o - | FileCheck --check-prefix=CHECK-CONSTRAINED %s
 
 typedef __attribute__((vector_size(4 * sizeof(float float vec_float;
 typedef __attribute__((vector_size(2 * sizeof(double double vec_double;
Index: clang/lib/Basic/Targets/PPC.cpp
===
--- clang/lib/Basic/Targets/PPC.cpp
+++ clang/lib/Basic/Targets/PPC.cpp
@@ -59,6 +59,7 @@
 } else if (Feature == "+prefix-instrs") {
   HasPrefixInstrs = true;
 } else if (Feature == "+spe" || Feature == "+efpu2") {
+  HasStrictFP = false;
   HasSPE = true;
   LongDoubleWidth = LongDoubleAlign = 64;
   LongDoubleFormat = &llvm::APFloat::IEEEdouble();
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D102839: [RISCV][Clang] Add -mno-div option to disable hardware int division

2021-05-27 Thread ksyx via Phabricator via cfe-commits
ksyx added a comment.

In D102839#2784197 , @luismarques 
wrote:

> In D102839#2783636 , @ksyx wrote:
>
>> So it seems the better way to do this would definitely by adding a 
>> subextension as the spec had changed. But I'd like  also to ask how will GCC 
>> deal with this option, and should we make this option an alias to turn off M 
>> extension and turn on ZMMul extension?
>
> Regarding "turn off M extension", see Krste's comment in the PR:
>
>> I think -mno-div is OK as a compiler option, but it's meaning is for the 
>> compiler not to generate divide instructions, not to indicate what the ISA 
>> is. So for example, -mno-div should not set ELF flags in binary to indicate 
>> ISA doesn't have divide - it should simply not generate divide instructions.

Thanks for mentioning that! Now, I changed the effect of `no-div` option into 
choosing a proper extension and implemented the `Zmmul` subextension. Is this 
solution acceptable or are there anything need further changes?


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

https://reviews.llvm.org/D102839

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


[PATCH] D103235: [SPE] Disable strict-fp for SPE by default

2021-05-27 Thread Nemanja Ivanovic via Phabricator via cfe-commits
nemanjai accepted this revision.
nemanjai added a comment.
This revision is now accepted and ready to land.

LGTM. Thanks.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103235

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


[PATCH] D102478: [Matrix] Emit assumption that matrix indices are valid.

2021-05-27 Thread Florian Hahn via Phabricator via cfe-commits
fhahn updated this revision to Diff 348210.
fhahn added a comment.

Thanks for the comments!

Updates:

- Only emit assumptions for optimized builds; the assumes are not helpful for 
unoptimized builds
- Use builder::CreateAssumption instead of manually constructing assume calls
- Add assert that condition must be true, if simplified to a constant.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D102478

Files:
  clang/lib/CodeGen/CGExpr.cpp
  clang/lib/CodeGen/CGExprScalar.cpp
  clang/test/CodeGen/matrix-type-operators.c
  clang/test/CodeGenCXX/matrix-type-operators.cpp
  clang/test/CodeGenObjC/matrix-type-operators.m
  llvm/include/llvm/IR/MatrixBuilder.h

Index: llvm/include/llvm/IR/MatrixBuilder.h
===
--- llvm/include/llvm/IR/MatrixBuilder.h
+++ llvm/include/llvm/IR/MatrixBuilder.h
@@ -231,9 +231,23 @@
: (IsUnsigned ? B.CreateUDiv(LHS, RHS) : B.CreateSDiv(LHS, RHS));
   }
 
-  /// Extracts the element at (\p RowIdx, \p ColumnIdx) from \p Matrix.
-  Value *CreateExtractElement(Value *Matrix, Value *RowIdx, Value *ColumnIdx,
-  unsigned NumRows, Twine const &Name = "") {
+  /// Create an assumption that \p Idx is less than \p NumElements.
+  void CreateIndexAssumption(Value *Idx, unsigned NumElements,
+ Twine const &Name = "") {
+
+Value *NumElts =
+B.getIntN(Idx->getType()->getScalarSizeInBits(), NumElements);
+auto *Cmp = B.CreateICmpULT(Idx, NumElts);
+if (auto *ConstCond = dyn_cast(Cmp))
+  assert(ConstCond->isOne() && "Index must be valid!");
+else
+  B.CreateAssumption(Cmp);
+  }
+
+  /// Compute the index to access the element at (\p RowIdx, \p ColumnIdx) from
+  /// a matrix with \p NumRows embedded in a vector.
+  Value *CreateIndex(Value *RowIdx, Value *ColumnIdx, unsigned NumRows,
+ Twine const &Name = "") {
 
 unsigned MaxWidth = std::max(RowIdx->getType()->getScalarSizeInBits(),
  ColumnIdx->getType()->getScalarSizeInBits());
@@ -241,9 +255,7 @@
 RowIdx = B.CreateZExt(RowIdx, IntTy);
 ColumnIdx = B.CreateZExt(ColumnIdx, IntTy);
 Value *NumRowsV = B.getIntN(MaxWidth, NumRows);
-return B.CreateExtractElement(
-Matrix, B.CreateAdd(B.CreateMul(ColumnIdx, NumRowsV), RowIdx),
-"matext");
+return B.CreateAdd(B.CreateMul(ColumnIdx, NumRowsV), RowIdx);
   }
 };
 
Index: clang/test/CodeGenObjC/matrix-type-operators.m
===
--- clang/test/CodeGenObjC/matrix-type-operators.m
+++ clang/test/CodeGenObjC/matrix-type-operators.m
@@ -22,9 +22,11 @@
 // CHECK-NEXT:[[IV2_PTR:%.*]] = bitcast %0* [[IV2]] to i8*
 // CHECK-NEXT:[[CALL1:%.*]] = call i32 bitcast (i8* (i8*, i8*, ...)* @objc_msgSend to i32 (i8*, i8*)*)(i8* [[IV2_PTR]], i8* [[SEL2]])
 // CHECK-NEXT:[[CONV2:%.*]] = sext i32 [[CALL1]] to i64
-// CHECK-NEXT:[[MAT:%.*]] = load <16 x double>, <16 x double>* {{.*}} align 8
 // CHECK-NEXT:[[IDX1:%.*]] = mul i64 [[CONV2]], 4
 // CHECK-NEXT:[[IDX2:%.*]] = add i64 [[IDX1]], [[CONV]]
+// CHECK-NEXT:   [[CMP:%.*]] = icmp ult i64 [[IDX2]], 16
+// CHECK-NEXT:call void @llvm.assume(i1 [[CMP]])
+// CHECK-NEXT:[[MAT:%.*]] = load <16 x double>, <16 x double>* {{.*}} align 8
 // CHECK-NEXT:[[MATEXT:%.*]] = extractelement <16 x double> [[MAT]], i64 [[IDX2]]
 // CHECK-NEXT:ret double [[MATEXT]]
 //
@@ -49,12 +51,14 @@
 // CHECK-NEXT:[[IV2_PTR:%.*]] = bitcast %0* [[IV2]] to i8*
 // CHECK-NEXT:[[CALL1:%.*]] = call i32 bitcast (i8* (i8*, i8*, ...)* @objc_msgSend to i32 (i8*, i8*)*)(i8* [[IV2_PTR]], i8* [[SEL2]])
 // CHECK-NEXT:[[CONV2:%.*]] = sext i32 [[CALL1]] to i64
+// CHECK-NEXT:[[IDX1:%.*]] = mul i64 [[CONV2]], 4
+// CHECK-NEXT:[[IDX2:%.*]] = add i64 [[IDX1]], [[CONV]]
+// CHECK-NEXT:[[CMP:%.*]] = icmp ult i64 [[IDX2]], 16
+// CHECK-NEXT:call void @llvm.assume(i1 [[CMP]])
 // CHECK-NEXT:[[M:%.*]] = load %1*, %1** %m.addr, align 8
 // CHECK-NEXT:[[SEL3:%.*]] = load i8*, i8** @OBJC_SELECTOR_REFERENCES_, align 8, !invariant.load !7
 // CHECK-NEXT:[[M_PTR:%.*]] = bitcast %1* [[M]] to i8*
 // CHECK-NEXT:[[MAT:%.*]] = call <16 x double> bitcast (i8* (i8*, i8*, ...)* @objc_msgSend to <16 x double> (i8*, i8*)*)(i8* [[M_PTR]], i8* [[SEL3]])
-// CHECK-NEXT:[[IDX1:%.*]] = mul i64 [[CONV2]], 4
-// CHECK-NEXT:[[IDX2:%.*]] = add i64 [[IDX1]], [[CONV]]
 // CHECK-NEXT:[[MATEXT:%.*]] = extractelement <16 x double> [[MAT]], i64 [[IDX2]]
 // CHECK-NEXT:ret double [[MATEXT]]
 //
Index: clang/test/CodeGenCXX/matrix-type-operators.cpp
===
--- clang/test/CodeGenCXX/matrix-type-operators.cpp
+++ clang/test/CodeGenCXX/matrix-type-operators.cpp
@@ -1,4 +1,5 @@
-// RUN: %clang_cc1 -fenab

[PATCH] D102839: [RISCV][Clang] Add -mno-div option to disable hardware int division

2021-05-27 Thread Luís Marques via Phabricator via cfe-commits
luismarques added a comment.

In D102839#2784275 , @ksyx wrote:

> Thanks for mentioning that! Now, I changed the effect of `no-div` option into 
> choosing a proper extension and implemented the `Zmmul` subextension. Is this 
> solution acceptable or are there anything need further changes?

It seems like the community is quickly converging on just using the ISA string 
with Zmmul, and not using no-div. While being compatible with the GNU tools is 
nice, if they are planning on dropping support for no-div soonish then we 
probably shouldn't add support for it. IMO, Zmmul should be a separate patch 
and presumably (at the moment) be gated by `-menable-experimental-extensions`.


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

https://reviews.llvm.org/D102839

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


[PATCH] D102478: [Matrix] Emit assumption that matrix indices are valid.

2021-05-27 Thread Florian Hahn via Phabricator via cfe-commits
fhahn marked an inline comment as done.
fhahn added inline comments.



Comment at: llvm/include/llvm/IR/MatrixBuilder.h:242
+auto *Cmp = B.CreateICmpULT(Idx, NumElts);
+if (!isa(Cmp)) {
+  Function *TheFn =

rjmccall wrote:
> xbolva00 wrote:
> > Prefer early exit?
> Should this do something special if the index is statically out of bounds?
I think this cause should never happen and if it does it means earlier checks 
have been missed. I added an assert.



Comment at: llvm/include/llvm/IR/MatrixBuilder.h:245
+  Intrinsic::getDeclaration(getModule(), Intrinsic::assume);
+  B.CreateCall(TheFn->getFunctionType(), TheFn, {Cmp}, Name);
+}

xbolva00 wrote:
> B.CreateAssumption(Cmp) may work well as well? and shorter.
Updated, thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D102478

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


[PATCH] D102478: [Matrix] Emit assumption that matrix indices are valid.

2021-05-27 Thread Florian Hahn via Phabricator via cfe-commits
fhahn updated this revision to Diff 348212.
fhahn marked an inline comment as done.
fhahn added a comment.

Fix clang-tidy warnings.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D102478

Files:
  clang/lib/CodeGen/CGExpr.cpp
  clang/lib/CodeGen/CGExprScalar.cpp
  clang/test/CodeGen/matrix-type-operators.c
  clang/test/CodeGenCXX/matrix-type-operators.cpp
  clang/test/CodeGenObjC/matrix-type-operators.m
  llvm/include/llvm/IR/MatrixBuilder.h

Index: llvm/include/llvm/IR/MatrixBuilder.h
===
--- llvm/include/llvm/IR/MatrixBuilder.h
+++ llvm/include/llvm/IR/MatrixBuilder.h
@@ -231,9 +231,23 @@
: (IsUnsigned ? B.CreateUDiv(LHS, RHS) : B.CreateSDiv(LHS, RHS));
   }
 
-  /// Extracts the element at (\p RowIdx, \p ColumnIdx) from \p Matrix.
-  Value *CreateExtractElement(Value *Matrix, Value *RowIdx, Value *ColumnIdx,
-  unsigned NumRows, Twine const &Name = "") {
+  /// Create an assumption that \p Idx is less than \p NumElements.
+  void CreateIndexAssumption(Value *Idx, unsigned NumElements,
+ Twine const &Name = "") {
+
+Value *NumElts =
+B.getIntN(Idx->getType()->getScalarSizeInBits(), NumElements);
+auto *Cmp = B.CreateICmpULT(Idx, NumElts);
+if (auto *ConstCond = dyn_cast(Cmp))
+  assert(ConstCond->isOne() && "Index must be valid!");
+else
+  B.CreateAssumption(Cmp);
+  }
+
+  /// Compute the index to access the element at (\p RowIdx, \p ColumnIdx) from
+  /// a matrix with \p NumRows embedded in a vector.
+  Value *CreateIndex(Value *RowIdx, Value *ColumnIdx, unsigned NumRows,
+ Twine const &Name = "") {
 
 unsigned MaxWidth = std::max(RowIdx->getType()->getScalarSizeInBits(),
  ColumnIdx->getType()->getScalarSizeInBits());
@@ -241,9 +255,7 @@
 RowIdx = B.CreateZExt(RowIdx, IntTy);
 ColumnIdx = B.CreateZExt(ColumnIdx, IntTy);
 Value *NumRowsV = B.getIntN(MaxWidth, NumRows);
-return B.CreateExtractElement(
-Matrix, B.CreateAdd(B.CreateMul(ColumnIdx, NumRowsV), RowIdx),
-"matext");
+return B.CreateAdd(B.CreateMul(ColumnIdx, NumRowsV), RowIdx);
   }
 };
 
Index: clang/test/CodeGenObjC/matrix-type-operators.m
===
--- clang/test/CodeGenObjC/matrix-type-operators.m
+++ clang/test/CodeGenObjC/matrix-type-operators.m
@@ -22,9 +22,11 @@
 // CHECK-NEXT:[[IV2_PTR:%.*]] = bitcast %0* [[IV2]] to i8*
 // CHECK-NEXT:[[CALL1:%.*]] = call i32 bitcast (i8* (i8*, i8*, ...)* @objc_msgSend to i32 (i8*, i8*)*)(i8* [[IV2_PTR]], i8* [[SEL2]])
 // CHECK-NEXT:[[CONV2:%.*]] = sext i32 [[CALL1]] to i64
-// CHECK-NEXT:[[MAT:%.*]] = load <16 x double>, <16 x double>* {{.*}} align 8
 // CHECK-NEXT:[[IDX1:%.*]] = mul i64 [[CONV2]], 4
 // CHECK-NEXT:[[IDX2:%.*]] = add i64 [[IDX1]], [[CONV]]
+// CHECK-NEXT:   [[CMP:%.*]] = icmp ult i64 [[IDX2]], 16
+// CHECK-NEXT:call void @llvm.assume(i1 [[CMP]])
+// CHECK-NEXT:[[MAT:%.*]] = load <16 x double>, <16 x double>* {{.*}} align 8
 // CHECK-NEXT:[[MATEXT:%.*]] = extractelement <16 x double> [[MAT]], i64 [[IDX2]]
 // CHECK-NEXT:ret double [[MATEXT]]
 //
@@ -49,12 +51,14 @@
 // CHECK-NEXT:[[IV2_PTR:%.*]] = bitcast %0* [[IV2]] to i8*
 // CHECK-NEXT:[[CALL1:%.*]] = call i32 bitcast (i8* (i8*, i8*, ...)* @objc_msgSend to i32 (i8*, i8*)*)(i8* [[IV2_PTR]], i8* [[SEL2]])
 // CHECK-NEXT:[[CONV2:%.*]] = sext i32 [[CALL1]] to i64
+// CHECK-NEXT:[[IDX1:%.*]] = mul i64 [[CONV2]], 4
+// CHECK-NEXT:[[IDX2:%.*]] = add i64 [[IDX1]], [[CONV]]
+// CHECK-NEXT:[[CMP:%.*]] = icmp ult i64 [[IDX2]], 16
+// CHECK-NEXT:call void @llvm.assume(i1 [[CMP]])
 // CHECK-NEXT:[[M:%.*]] = load %1*, %1** %m.addr, align 8
 // CHECK-NEXT:[[SEL3:%.*]] = load i8*, i8** @OBJC_SELECTOR_REFERENCES_, align 8, !invariant.load !7
 // CHECK-NEXT:[[M_PTR:%.*]] = bitcast %1* [[M]] to i8*
 // CHECK-NEXT:[[MAT:%.*]] = call <16 x double> bitcast (i8* (i8*, i8*, ...)* @objc_msgSend to <16 x double> (i8*, i8*)*)(i8* [[M_PTR]], i8* [[SEL3]])
-// CHECK-NEXT:[[IDX1:%.*]] = mul i64 [[CONV2]], 4
-// CHECK-NEXT:[[IDX2:%.*]] = add i64 [[IDX1]], [[CONV]]
 // CHECK-NEXT:[[MATEXT:%.*]] = extractelement <16 x double> [[MAT]], i64 [[IDX2]]
 // CHECK-NEXT:ret double [[MATEXT]]
 //
Index: clang/test/CodeGenCXX/matrix-type-operators.cpp
===
--- clang/test/CodeGenCXX/matrix-type-operators.cpp
+++ clang/test/CodeGenCXX/matrix-type-operators.cpp
@@ -1,4 +1,5 @@
-// RUN: %clang_cc1 -fenable-matrix -triple x86_64-apple-darwin %s -emit-llvm -disable-llvm-passes -o - -std=c++11 | FileCheck %s
+// RUN: %clang_cc1 -O0 -fenable-matrix -triple x86_64-apple-darwin %s -emit-llvm -disable-llvm-passes -o - -std=c

[PATCH] D101868: [clang-format] Adds a formatter for aligning arrays of structs

2021-05-27 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks added inline comments.



Comment at: clang/lib/Format/FormatToken.cpp:86
+  (SplitMax > 0 && SplitMax < ColumnWidth) ? SplitMax : ColumnWidth;
+  ColWidth += (is(tok::comment)) ? 1 : 0;
+  const auto *NextColEntry = Next;

Personal style, don't know about LLVM. Same below.



Comment at: clang/unittests/Format/FormatTest.cpp:16472
+   "{56,23, /* a comment */ \"hello\" },\n"
+   "{-1, 93463, \"world\" },\n"
+   "{ 7, 5,\"!!\" }\n"

And a comment after the value?



Comment at: clang/unittests/Format/FormatTest.cpp:16478
+   "{56, /* a comment */ 23, \"hello\" },\n"
+   "{-1,  93463, \"world\" },\n"
+   "{ 7,  5,\"!!\" }\n"

Or at the line end?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D101868

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


[PATCH] D103204: [clang-format] New BreakInheritanceList style AfterComma

2021-05-27 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks added inline comments.



Comment at: clang/include/clang/Format/Format.h:1839
+/// \endcode
+BILS_AfterComma
   };

Maybe add a comma, so that the next addition will not need to modify this line?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103204

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


[PATCH] D103112: Reimplement __builtin_unique_stable_name as __builtin_sycl_unique_stable_name

2021-05-27 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/include/clang/Basic/LangOptions.h:448
+
+  bool isSYCL() const { return SYCLIsDevice || SYCLIsHost; }
 };

FWIW, we also have `SYCLVersion != SYCL_None` as a possible way to express 
this. Perhaps we should just use that anywhere we're using `SYCLIsDevice || 
SYCLIsHost` currently? (I don't have a strong opinion but am bringing it up in 
case someone else does.)



Comment at: clang/test/CodeGenSYCL/unique_stable_name.cpp:86-89
+  // FIXME: Ensure that j is incremented because VLAs are terrible.
+  int j = 55;
+  puts(__builtin_sycl_unique_stable_name(int[++j]));
+  // CHECK: call spir_func void @puts(i8 addrspace(4)* addrspacecast (i8* 
getelementptr inbounds ([[STRING_SIZE]], [[STRING_SIZE]]* @[[STRING]], i32 0, 
i32 0) to i8 addrspace(4)*))

@rjmccall  -- any opinions or ideas on this? I think VLAs should likely behave 
the same as they do in `sizeof`, etc.


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

https://reviews.llvm.org/D103112

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


[clang] 7faffde - [clang-format] [NFC] realign documentation in Format.h...

2021-05-27 Thread Björn Schäpers via cfe-commits

Author: Max Sagebaum
Date: 2021-05-27T13:12:55+02:00
New Revision: 7faffdeb48d3d81ba8fc1353f1a9a563a25adf6d

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

LOG: [clang-format] [NFC] realign documentation in Format.h...

... and ClanfFormatStyleOptions.rst for EmptyLineAfterAccessModifier

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

Added: 


Modified: 
clang/include/clang/Format/Format.h

Removed: 




diff  --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index d13c6ff4d9334..4392b4aa4b43a 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -1973,7 +1973,9 @@ struct FormatStyle {
 ELAAMS_Always,
   };
 
-  /// Defines in which cases to put empty line after access modifiers.
+  /// Defines when to put an empty line after access modifiers.
+  /// ``EmptyLineBeforeAccessModifier`` configuration handles the number of
+  /// empty lines between two access modifiers.
   EmptyLineAfterAccessModifierStyle EmptyLineAfterAccessModifier;
 
   /// Different styles for empty line before access modifiers.



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


[PATCH] D98895: [X86][Draft] Disable long double type for -mno-x87 option

2021-05-27 Thread Andrew Savonichev via Phabricator via cfe-commits
asavonic updated this revision to Diff 348219.
asavonic added a comment.

- Disabled double or float return for x86 targets
- Refactored checks into a separate function.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D98895

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Basic/TargetInfo.h
  clang/include/clang/Sema/Sema.h
  clang/lib/Basic/TargetInfo.cpp
  clang/lib/Basic/Targets/X86.cpp
  clang/lib/Basic/Targets/X86.h
  clang/lib/Sema/SemaChecking.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/test/Sema/x86-no-x87.c

Index: clang/test/Sema/x86-no-x87.c
===
--- /dev/null
+++ clang/test/Sema/x86-no-x87.c
@@ -0,0 +1,93 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s -triple x86_64-linux-gnu -target-feature -x87
+// RUN: %clang_cc1 -fsyntax-only -verify %s -triple i686-linux-gnu -target-feature -x87 -DRET_ERROR
+// RUN: %clang_cc1 -fsyntax-only -verify %s -triple x86_64-windows-msvc -target-feature -x87 -DNOERROR
+// RUN: %clang_cc1 -fsyntax-only -verify %s -triple x86_64-linux-gnu -DNOERROR
+
+#ifdef NOERROR
+// expected-no-diagnostics
+#endif
+
+typedef long double long_double;
+
+// Declaration is fine, unless it is called or defined.
+double decl(long_double x, long_double y);
+
+#ifndef NOERROR
+// expected-error@+3{{long double is not supported on this target}}
+// expected-error@+2{{long double is not supported on this target}}
+#endif
+double ld_args(long_double x, long_double y);
+
+long_double ld_ret(double x, double y);
+
+#ifdef RET_ERROR
+// expected-error@+4{{return value of type double is not supported on this target}}
+// expected-error@+2{{return value of type double is not supported on this target}}
+#endif
+double args(double x, double y) {
+  return ld_args(x, y);
+}
+
+#ifdef RET_ERROR
+// expected-error@+2{{return value of type double is not supported on this target}}
+#endif
+double ret1(double x, double y) {
+#ifndef NOERROR
+  // expected-error@+2{{long double is not supported on this target}}
+#endif
+  return ld_ret(x, y);
+}
+
+#ifdef RET_ERROR
+// expected-error@+2{{return value of type float is not supported on this target}}
+#endif
+const float ret2(float a, double b) {
+  return a * b;
+}
+
+#ifdef RET_ERROR
+// expected-error@+2{{return value of type double is not supported on this target}}
+#endif
+double binop(double x, double y) {
+#ifndef NOERROR
+  // expected-error@+2{{long double is not supported on this target}}
+#endif
+  double z = (long_double)x * (long_double)y;
+  return z;
+}
+
+void assign1(long_double *ret, double x) {
+#ifndef NOERROR
+  // expected-error@+2{{long double is not supported on this target}}
+#endif
+  *ret = x;
+}
+
+struct st_long_double {
+  long_double ld;
+};
+
+void assign2() {
+  struct st_long_double st;
+  st.ld = 0.42;
+}
+
+void assign3() {
+  struct st_long_double st;
+  st.ld = 42;
+}
+
+void assign4(double d) {
+  struct st_long_double st;
+#ifndef NOERROR
+  // expected-error@+2{{long double is not supported on this target}}
+#endif
+  st.ld = d;
+}
+
+void assign5() {
+#ifndef NOERROR
+  // expected-error@+2{{long double is not supported on this target}}
+#endif
+  long_double ld = 0.42;
+}
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -14002,6 +14002,20 @@
 }
   }
 
+  // Allow assignment of a literal, because it compiles to just a
+  // store of a constant.
+  bool IsLiteralAssign = (Opc == BO_Assign) && (isa(RHSExpr) ||
+isa(RHSExpr));
+
+  if (!IsLiteralAssign) {
+if (CheckTargetTypeSupport(Context.getTargetInfo(), LHSExpr->getType(),
+   OpLoc, /*IsReturnType=*/false) ||
+CheckTargetTypeSupport(Context.getTargetInfo(), RHSExpr->getType(),
+   OpLoc, /*IsReturnType=*/false)) {
+  return ExprError();
+}
+  }
+
   switch (Opc) {
   case BO_Assign:
 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
@@ -14840,6 +14854,13 @@
   if (Opc != UO_AddrOf && Opc != UO_Deref)
 CheckArrayAccess(Input.get());
 
+  if (CheckTargetTypeSupport(Context.getTargetInfo(), resultType, OpLoc,
+ /*IsReturnType=*/false) ||
+  CheckTargetTypeSupport(Context.getTargetInfo(), InputExpr->getType(),
+ OpLoc, /*IsReturnType=*/false)) {
+return ExprError();
+  }
+
   auto *UO =
   UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
 OpLoc, CanOverflow, CurFPFeatureOverrides());
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -7270,6 +7270,9 @@
 }

[PATCH] D103175: [C++4OpenCL] Fix ICE with invalid use of half

2021-05-27 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia accepted this revision.
Anastasia added a comment.
This revision is now accepted and ready to land.

LGTM! Thanks

Yeah I think this is the only case where `DefaultLvalueConversion` exits with 
an error at present.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103175

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


[PATCH] D103241: [OpenCL] Add memory_scope_all_devices

2021-05-27 Thread Sven van Haastregt via Phabricator via cfe-commits
svenvh created this revision.
svenvh added reviewers: Anastasia, azabaznov.
svenvh added a project: clang.
Herald added subscribers: ldrumm, jfb, yaxunl.
svenvh requested review of this revision.
Herald added a subscriber: cfe-commits.

Add the `memory_scope_all_devices` enum value, which is restricted to
OpenCL 3.0 or newer and the `__opencl_c_atomic_scope_all_devices`
feature.  Also guard `memory_scope_all_svm_devices` accordingly, which
is already available in OpenCL 2.0.

This patch only adds a negative test for now.  Ideally adding a CL3.0
run line to `atomic-ops.cl` should suffice as a positive test, but we
cannot do that yet until (at least) generic address spaces and program
scope variables are supported in OpenCL 3.0 mode.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D103241

Files:
  clang/include/clang/Basic/OpenCLExtensions.def
  clang/lib/Headers/opencl-c-base.h
  clang/test/SemaOpenCL/atomic-ops.cl


Index: clang/test/SemaOpenCL/atomic-ops.cl
===
--- clang/test/SemaOpenCL/atomic-ops.cl
+++ clang/test/SemaOpenCL/atomic-ops.cl
@@ -2,6 +2,7 @@
 // RUN:   -fsyntax-only -triple=spir64 -fdeclare-opencl-builtins 
-finclude-default-header
 // RUN: %clang_cc1 %s -cl-std=CL2.0 -verify -fsyntax-only \
 // RUN:   -triple=amdgcn-amd-amdhsa -fdeclare-opencl-builtins 
-finclude-default-header
+// TODO: add -cl-std=CL3.0 line when generic and psv are supported.
 
 // Basic parsing/Sema tests for __opencl_atomic_*
 
@@ -161,6 +162,11 @@
   (void)__opencl_atomic_load(Ap, memory_order_relaxed, 
memory_scope_work_group);
   (void)__opencl_atomic_load(Ap, memory_order_relaxed, memory_scope_device);
   (void)__opencl_atomic_load(Ap, memory_order_relaxed, 
memory_scope_all_svm_devices);
+  (void)__opencl_atomic_load(Ap, memory_order_relaxed, 
memory_scope_all_devices);
+#if __OPENCL_C_VERSION__ < CL_VERSION_3_0
+  // expected-error@-2{{use of undeclared identifier 
'memory_scope_all_devices'}}
+  // expected-note@* {{'memory_scope_all_svm_devices' declared here}}
+#endif
   (void)__opencl_atomic_load(Ap, memory_order_relaxed, memory_scope_sub_group);
   (void)__opencl_atomic_load(Ap, memory_order_relaxed, scope);
   (void)__opencl_atomic_load(Ap, memory_order_relaxed, 10);
//expected-error{{synchronization scope argument to atomic operation is 
invalid}}
Index: clang/lib/Headers/opencl-c-base.h
===
--- clang/lib/Headers/opencl-c-base.h
+++ clang/lib/Headers/opencl-c-base.h
@@ -312,7 +312,12 @@
   memory_scope_work_item = __OPENCL_MEMORY_SCOPE_WORK_ITEM,
   memory_scope_work_group = __OPENCL_MEMORY_SCOPE_WORK_GROUP,
   memory_scope_device = __OPENCL_MEMORY_SCOPE_DEVICE,
+#if defined(__opencl_c_atomic_scope_all_devices)
   memory_scope_all_svm_devices = __OPENCL_MEMORY_SCOPE_ALL_SVM_DEVICES,
+#if (__OPENCL_C_VERSION__ >= CL_VERSION_3_0)
+  memory_scope_all_devices = memory_scope_all_svm_devices,
+#endif // __OPENCL_C_VERSION__ >= CL_VERSION_3_0
+#endif // defined(__opencl_c_atomic_scope_all_devices)
 #if defined(cl_intel_subgroups) || defined(cl_khr_subgroups)
   memory_scope_sub_group = __OPENCL_MEMORY_SCOPE_SUB_GROUP
 #endif
Index: clang/include/clang/Basic/OpenCLExtensions.def
===
--- clang/include/clang/Basic/OpenCLExtensions.def
+++ clang/include/clang/Basic/OpenCLExtensions.def
@@ -110,6 +110,7 @@
 OPENCL_OPTIONALCOREFEATURE(__opencl_c_generic_address_space, false, 300, 
OCL_C_30)
 OPENCL_OPTIONALCOREFEATURE(__opencl_c_atomic_order_acq_rel, false, 300, 
OCL_C_30)
 OPENCL_OPTIONALCOREFEATURE(__opencl_c_atomic_order_seq_cst, false, 300, 
OCL_C_30)
+OPENCL_OPTIONALCOREFEATURE(__opencl_c_atomic_scope_all_devices, false, 300, 
OCL_C_30)
 OPENCL_OPTIONALCOREFEATURE(__opencl_c_subgroups, false, 300, OCL_C_30)
 OPENCL_OPTIONALCOREFEATURE(__opencl_c_3d_image_writes, false, 300, OCL_C_30)
 OPENCL_OPTIONALCOREFEATURE(__opencl_c_device_enqueue, false, 300, OCL_C_30)


Index: clang/test/SemaOpenCL/atomic-ops.cl
===
--- clang/test/SemaOpenCL/atomic-ops.cl
+++ clang/test/SemaOpenCL/atomic-ops.cl
@@ -2,6 +2,7 @@
 // RUN:   -fsyntax-only -triple=spir64 -fdeclare-opencl-builtins -finclude-default-header
 // RUN: %clang_cc1 %s -cl-std=CL2.0 -verify -fsyntax-only \
 // RUN:   -triple=amdgcn-amd-amdhsa -fdeclare-opencl-builtins -finclude-default-header
+// TODO: add -cl-std=CL3.0 line when generic and psv are supported.
 
 // Basic parsing/Sema tests for __opencl_atomic_*
 
@@ -161,6 +162,11 @@
   (void)__opencl_atomic_load(Ap, memory_order_relaxed, memory_scope_work_group);
   (void)__opencl_atomic_load(Ap, memory_order_relaxed, memory_scope_device);
   (void)__opencl_atomic_load(Ap, memory_order_relaxed, memory_scope_all_svm_devices);
+  (void)__opencl_atomic_load(Ap, memory_order_relaxed, memory_scope_all_devices);
+#if __OPENCL_C_VERSION__ < CL_VERSION

[PATCH] D103241: [OpenCL] Add memory_scope_all_devices

2021-05-27 Thread Anton Zabaznov via Phabricator via cfe-commits
azabaznov added inline comments.



Comment at: clang/include/clang/Basic/OpenCLExtensions.def:113
 OPENCL_OPTIONALCOREFEATURE(__opencl_c_atomic_order_seq_cst, false, 300, 
OCL_C_30)
+OPENCL_OPTIONALCOREFEATURE(__opencl_c_atomic_scope_all_devices, false, 300, 
OCL_C_30)
 OPENCL_OPTIONALCOREFEATURE(__opencl_c_subgroups, false, 300, OCL_C_30)

This feature is header only. We had a lot of discussions on that and the main 
idea was not to declare header only features/extensions in 
`OpenCLExtensions.def` and use `-D__opencl_c_atomic_scope_all_devices=1` 
instead, @Anastasia can comment on this.

I personally would like to introduce new flag for OpenCL options in 
`OpenCLExtensions.def` which will indicate that feature/extension is 
header-only, and thus all of such options can be declared in 
`OpenCLExtensions.def`: if flag is set to true it can be stripped out from the 
parser. What do you think about this?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103241

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


[PATCH] D91949: [clang-format] Add BeforeStructInitialization option in BraceWrapping configuration

2021-05-27 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

Are we happy with the way this behaves? I realise some of this needs semantic 
information but I think the fact it only handles 1 of these 4 cases leaves me 
feeling a little cold. (I just don't want to be having to defend this as to why 
it doesn't work in all cases.)

  ---
  Language: Cpp
  BasedOnStyle: LLVM
  BreakBeforeBraces: Custom
  BraceWrapping:
  BeforeClassStructInit: true



  struct S2 {
int x, y;
  };
  
  void foo() {
struct S2 a1 =
{1, 2};
struct S2 a2[3] = {{1, 2}, {3, 4}, 5, 6};
  
S2 a3 = {1, 2};
S2 a4[3] = {{1, 2}, {3, 4}, 5, 6};
  }
  
  int main(int argc, char **argv) { return 0; }


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

https://reviews.llvm.org/D91949

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


[PATCH] D98895: [X86][Draft] Disable long double type for -mno-x87 option

2021-05-27 Thread Pengfei Wang via Phabricator via cfe-commits
pengfei accepted this revision.
pengfei added a comment.
This revision is now accepted and ready to land.

LGTM. But let's wait one or more days to see if others have more comments.




Comment at: clang/lib/Sema/SemaChecking.cpp:4762
+
+  for (ParmVarDecl *Param : FDecl->parameters()) {
+CheckTargetTypeSupport(Context.getTargetInfo(), Param->getType(),

Nit: We can save the curly bracket for it.



Comment at: clang/lib/Sema/SemaChecking.cpp:14202
+if (CheckTargetTypeSupport(Context.getTargetInfo(), Param->getType(),
+   Param->getLocation(), /*IsReturnType=*/false)) {
+  HasInvalidParm = true;

ditto


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D98895

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


[PATCH] D103195: Add matchers for gtest's ASSERT_THAT, EXPECT_THAT, ON_CALL and EXPECT_CALL

2021-05-27 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel added inline comments.



Comment at: clang/include/clang/ASTMatchers/GtestMatchers.h:55-59
+/// Matcher for gtest's `ON_CALL` macro. When `Args` is `NoMatchers`,
+/// this matches a mock call to a method without argument matchers e.g.
+/// `ON_CALL(mock, TwoParamMethod)`; when `Args` is `HasMatchers`, this
+/// matches a mock call to a method with argument matchers e.g.
+/// `ON_CALL(mock, TwoParamMethod(m1, m2))`. `MockObject` matches the mock

Please move this to a comment describing the `MockArgs` enum.



Comment at: clang/include/clang/ASTMatchers/GtestMatchers.h:34
 
+enum class MockArgs {
+  NoMatchers,

hokein wrote:
> worth comments.
> 
> out of curiosity, what do we call this `Matchers`? I'd be careful to 
> introduce a different matcher concept in the ast_matcher library, it would 
> easily cause confusion. 
+1 Please move the comments relating to this enum from the two `gtestOnCall` 
functions to here.

hokein@ -- the "Matchers" is because its describing googletest matchers.  But, 
it is a bit confusing in this context and doesn't really add anything. What do 
you think of `None` and `Some` instead?



Comment at: clang/lib/ASTMatchers/GtestMatchers.cpp:47
 
-static llvm::StringRef getAssertMacro(GtestCmp Cmp) {
-  switch (Cmp) {
-case GtestCmp::Eq:
-  return "ASSERT_EQ";
-case GtestCmp::Ne:
-  return "ASSERT_NE";
-case GtestCmp::Ge:
-  return "ASSERT_GE";
-case GtestCmp::Gt:
-  return "ASSERT_GT";
-case GtestCmp::Le:
-  return "ASSERT_LE";
-case GtestCmp::Lt:
-  return "ASSERT_LT";
+static llvm::StringRef getMacroTypeName(MacroType Macro) {
+  switch (Macro) {

hokein wrote:
> the `static` qualifier is not needed as you wrap it within an anonymous 
> namespace. the same below.
nit: per the style guide 
(https://releases.llvm.org/2.7/docs/CodingStandards.html#micro_anonns), I think 
it would be better to shrink the anonymous namespace to only enclose the enum 
decl, and keep these `static` annotations and in fact add a few that are 
currently missing on the `gtestCallInternal` functions.


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

https://reviews.llvm.org/D103195

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


[PATCH] D102760: [llvm] Let SmallVector construct from any Iterable

2021-05-27 Thread Guillaume Chatelet via Phabricator via cfe-commits
gchatelet updated this revision to Diff 348228.
gchatelet added a comment.

- Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D102760

Files:
  clang/include/clang/Basic/Module.h
  llvm/include/llvm/ADT/IterableTraits.h
  llvm/include/llvm/ADT/SmallVector.h
  llvm/tools/llvm-xray/xray-converter.cpp
  llvm/unittests/ADT/CMakeLists.txt
  llvm/unittests/ADT/IterableTraitsTest.cpp
  llvm/unittests/ADT/SmallVectorTest.cpp

Index: llvm/unittests/ADT/SmallVectorTest.cpp
===
--- llvm/unittests/ADT/SmallVectorTest.cpp
+++ llvm/unittests/ADT/SmallVectorTest.cpp
@@ -226,6 +226,22 @@
   this->assertValuesInOrder(this->theVector, 3u, 1, 2, 3);
 }
 
+// Constructor test.
+TYPED_TEST(SmallVectorTest, ConstructorIterableCArrayTest) {
+  SCOPED_TRACE("ConstructorTest");
+  int arr[] = {1, 2, 3};
+  this->theVector = SmallVector(arr);
+  this->assertValuesInOrder(this->theVector, 3u, 1, 2, 3);
+}
+
+// Constructor test.
+TYPED_TEST(SmallVectorTest, ConstructorIterableVectorTest) {
+  SCOPED_TRACE("ConstructorTest");
+  std::vector vec = {1, 2, 3};
+  this->theVector = SmallVector(vec);
+  this->assertValuesInOrder(this->theVector, 3u, 1, 2, 3);
+}
+
 // New vector test.
 TYPED_TEST(SmallVectorTest, EmptyVectorTest) {
   SCOPED_TRACE("EmptyVectorTest");
Index: llvm/unittests/ADT/IterableTraitsTest.cpp
===
--- /dev/null
+++ llvm/unittests/ADT/IterableTraitsTest.cpp
@@ -0,0 +1,62 @@
+//===- IterableTraitsTest.cpp - Unit tests for is_range_iterable --===//
+//
+// 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
+//
+//===--===//
+
+#include "llvm/ADT/IterableTraits.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/iterator_range.h"
+#include "gtest/gtest.h"
+#include 
+#include 
+#include 
+
+namespace llvm {
+
+class ForwardDeclared;
+
+TEST(IteratorRangeTest, IsForwardIterator) {
+  EXPECT_FALSE(is_forward_iterator::value);
+  EXPECT_TRUE(is_forward_iterator::value);
+  EXPECT_TRUE(is_forward_iterator::value);
+  EXPECT_TRUE(is_forward_iterator::value);
+  using ForwardList = std::forward_list;
+  EXPECT_TRUE(is_forward_iterator::value);
+  EXPECT_TRUE(is_forward_iterator::value);
+}
+
+TEST(IteratorRangeTest, IsIterableCArray) {
+  int Data[4];
+  EXPECT_TRUE(
+  is_range_iterable>::value);
+}
+
+TEST(IteratorRangeTest, IsIterableVector) {
+  using Vector = std::vector;
+  EXPECT_TRUE(is_range_iterable::value);
+}
+
+TEST(IteratorRangeTest, IsIterableArray) {
+  using Array = std::array;
+  EXPECT_TRUE(is_range_iterable::value);
+}
+
+TEST(IteratorRangeTest, IsIterableSmallVector) {
+  using SVector = SmallVector;
+  EXPECT_TRUE(is_range_iterable::value);
+}
+
+TEST(IteratorRangeTest, IsIterableRange) {
+  using Range = iterator_range;
+  EXPECT_TRUE(is_range_iterable::value);
+}
+
+TEST(IteratorRangeTest, NonIterableTypes) {
+  EXPECT_FALSE(is_range_iterable::value);
+  EXPECT_FALSE(is_range_iterable::value);
+}
+
+} // namespace llvm
Index: llvm/unittests/ADT/CMakeLists.txt
===
--- llvm/unittests/ADT/CMakeLists.txt
+++ llvm/unittests/ADT/CMakeLists.txt
@@ -41,6 +41,7 @@
   IntEqClassesTest.cpp
   IntervalMapTest.cpp
   IntrusiveRefCntPtrTest.cpp
+  IterableTraitsTest.cpp
   IteratorTest.cpp
   MappedIteratorTest.cpp
   MapVectorTest.cpp
Index: llvm/tools/llvm-xray/xray-converter.cpp
===
--- llvm/tools/llvm-xray/xray-converter.cpp
+++ llvm/tools/llvm-xray/xray-converter.cpp
@@ -158,6 +158,8 @@
 // A structure that allows building a dictionary of stack ids for the Chrome
 // trace event format.
 struct StackIdData {
+  StackIdData(const StackIdData &) = default;
+
   // Each Stack of function calls has a unique ID.
   unsigned id;
 
Index: llvm/include/llvm/ADT/SmallVector.h
===
--- llvm/include/llvm/ADT/SmallVector.h
+++ llvm/include/llvm/ADT/SmallVector.h
@@ -13,7 +13,7 @@
 #ifndef LLVM_ADT_SMALLVECTOR_H
 #define LLVM_ADT_SMALLVECTOR_H
 
-#include "llvm/ADT/iterator_range.h"
+#include "llvm/ADT/IterableTraits.h"
 #include "llvm/Support/Compiler.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/MathExtras.h"
@@ -1188,10 +1188,13 @@
 this->append(S, E);
   }
 
-  template 
-  explicit SmallVector(const iterator_range &R)
+  template 
+  explicit SmallVector(
+  Iterable &&Range,
+  std::enable_if_t::value, bool> = true)
   : SmallVectorImpl(N) {
-this->append(R.begin(), R.end());
+this->append(std::begin(std::forward(Range)),
+ 

[PATCH] D103245: [clang-format] Fix PointerAlignmentRight with AlignConsecutiveDeclarations

2021-05-27 Thread Gerhard Gappmeier via Phabricator via cfe-commits
gergap created this revision.
gergap added reviewers: djasper, berenm.
gergap requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This re-applies the old patch D27651 , which 
was never landed, into the
latest "main" branch, without understanding the code. I just applied
the changes "mechanically" and made it compiling again.

This makes the right pointer alignment working as expected.

For instance

  const char* const* v1;
  float const* v2;
  SomeVeryLongType const& v3;

was formatted as

  const char *const * v1;
  float const *   v2;
  SomeVeryLongType const &v3;

This patch keep the *s or &s aligned to the right, next to their variable.
The above example is now formatted as

  const char *const  *v1;
  float const*v2;
  SomeVeryLongType const &v3;

It is a pity that this still does not work with clang-format in 2021,
even though there was a fix available in 2016. IMHO right pointer alignment
is the default case in C, because syntactically the pointer belongs to the
variable.

See

  int* a, b, c; // wrong, just the 1st variable is a pointer

vs.

  int *a, *b, c*; // right

Prominent example is the Linux kernel coding style.

Some styles argue the left pointer alignment is better and declaration
lists as shown above should be avoid. That's ok, as different projects
can use different styles, but this important style should work too.

I hope that somebody that has a better understanding about the code,
can take over this patch and land it into main.

For now I must maintain this fork to make it working for our projects.

Cheers,
Gerhard.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D103245

Files:
  clang/lib/Format/WhitespaceManager.cpp
  clang/unittests/Format/FormatTest.cpp

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -15039,9 +15039,11 @@
"  doublebar();\n"
"};\n",
Alignment);
+
+  // PAS_RIGHT
   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
 "  int const i   = 1;\n"
-"  int * j   = 2;\n"
+"  int  *j   = 2;\n"
 "  int   big = 1;\n"
 "\n"
 "  unsigned oneTwoThree = 123;\n"
@@ -15062,6 +15064,140 @@
"int ll=1;\n"
"}",
Alignment));
+  EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
+"  int const i   = 1;\n"
+"  int **j   = 2, ***k;\n"
+"  int  &k   = i;\n"
+"  int &&l   = i + j;\n"
+"  int   big = 1;\n"
+"\n"
+"  unsigned oneTwoThree = 123;\n"
+"  int  oneTwo  = 12;\n"
+"  method();\n"
+"  float k  = 2;\n"
+"  int   ll = 1;\n"
+"}",
+format("void SomeFunction(int parameter= 0) {\n"
+   " int const  i= 1;\n"
+   "  int **j=2,***k;\n"
+   "int &k=i;\n"
+   "int &&l=i+j;\n"
+   " int big  =  1;\n"
+   "\n"
+   "unsigned oneTwoThree  =123;\n"
+   "int oneTwo = 12;\n"
+   "  method();\n"
+   "float k= 2;\n"
+   "int ll=1;\n"
+   "}",
+   Alignment));
+
+  // PAS_LEFT
+  FormatStyle AlignmentLeft = Alignment;
+  AlignmentLeft.PointerAlignment = FormatStyle::PAS_Left;
+  EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
+"  int const i   = 1;\n"
+"  int*  j   = 2;\n"
+"  int   big = 1;\n"
+"\n"
+"  unsigned oneTwoThree = 123;\n"
+"  int  oneTwo  = 12;\n"
+"  method();\n"
+"  float k  = 2;\n"
+"  int   ll = 1;\n"
+"}",
+format("void SomeFunction(int parameter= 0) {\n"
+   " int const  i= 1;\n"
+   "  int *j=2;\n"
+   " int big  =  1;\n"
+   "\n"
+   "unsigned oneTwoThree  =123;\n"
+   "int oneTwo = 12;\n"
+   "  method();\n"
+   "float k= 2;\n"
+   "int ll=1;\n"
+   "}",
+   AlignmentLeft));
+  EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
+"  int const i   = 1;\n"
+"  int** j   = 2;\n"
+"  int&  k   = i;\n"
+"  int&& l   = i + j;\n"
+"  int   big = 1;\n"
+"\n"
+"  unsigned oneTwoThree = 123;\n"
+"  int  oneTwo  = 12;\n"
+"  method(

[PATCH] D103241: [OpenCL] Add memory_scope_all_devices

2021-05-27 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added inline comments.



Comment at: clang/include/clang/Basic/OpenCLExtensions.def:113
 OPENCL_OPTIONALCOREFEATURE(__opencl_c_atomic_order_seq_cst, false, 300, 
OCL_C_30)
+OPENCL_OPTIONALCOREFEATURE(__opencl_c_atomic_scope_all_devices, false, 300, 
OCL_C_30)
 OPENCL_OPTIONALCOREFEATURE(__opencl_c_subgroups, false, 300, OCL_C_30)

azabaznov wrote:
> This feature is header only. We had a lot of discussions on that and the main 
> idea was not to declare header only features/extensions in 
> `OpenCLExtensions.def` and use `-D__opencl_c_atomic_scope_all_devices=1` 
> instead, @Anastasia can comment on this.
> 
> I personally would like to introduce new flag for OpenCL options in 
> `OpenCLExtensions.def` which will indicate that feature/extension is 
> header-only, and thus all of such options can be declared in 
> `OpenCLExtensions.def`: if flag is set to true it can be stripped out from 
> the parser. What do you think about this?
Yes, I agree the idea is to align with C/C++ directions for scalability i.e. we 
should only add what is absolutely necessary to the compiler and implement the 
rest using libraries - just like regular C and C++. We won't be able to scale 
if we keep adding everything in the compiler. In fact, we already have a huge 
scalability issue with our builtin functions. If we look at modern C++ - more 
than 70% of features are not in the compiler at all.

Would it be possible to do something like suggested here: 
https://reviews.llvm.org/D91531#change-AKXhB4ko4nAO for `cl_khr_depth_images`?

> I personally would like to introduce new flag for OpenCL options in 
> OpenCLExtensions.def which will indicate that feature/extension is 
> header-only, and thus all of such options can be declared in 
> OpenCLExtensions.def: if flag is set to true it can be stripped out from the 
> parser. What do you think about this?

Hmm, I think the macros should either be declared in the headers or using a 
flag `-D`. I don't know why would adding them in `OpenCLExtensions.def` be 
beneficial if we can use conventional approaches? This allows avoiding the 
complexity and makes things more modular. If we look at the OpenCL vendor 
extensions for example - we probably don't want them all in one place?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103241

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


[PATCH] D103125: [Clang][WIP] Allow renaming of "clang"

2021-05-27 Thread Paul Robinson via Phabricator via cfe-commits
probinson added a comment.

In D103125#2782096 , @echristo wrote:

> I'm also not a fan of this change. From a project perspective the binary is 
> clang and while people may wish to change the name for their own product 
> teams it seems like that onus should be on them.

It occurs to me that there's precedent regarding prefixes, which is that you 
can rename/soft-link clang to have a triple embedded in the name (e.g., 
x86_64-pc-linux-clang) and then the driver will factor the prefix into 
default-target computations.  But AFAIK there's no support for directly doing 
that renaming/linking in the build system.  I agree with @echristo this 
properly belongs to the vendors not the project.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103125

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


[clang] 8edd346 - Add support for #elifdef and #elifndef

2021-05-27 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2021-05-27T08:57:47-04:00
New Revision: 8edd3464afbff65d7d5945b3a8b20009d6ff5deb

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

LOG: Add support for #elifdef and #elifndef

WG14 adopted N2645 and WG21 EWG has accepted P2334 in principle (still
subject to full EWG vote + CWG review + plenary vote), which add
support for #elifdef as shorthand for #elif defined and #elifndef as
shorthand for #elif !defined. This patch adds support for the new
preprocessor directives.

Added: 
clang/test/Preprocessor/elifdef.c

Modified: 
clang/include/clang/Basic/DiagnosticLexKinds.td
clang/include/clang/Basic/TokenKinds.def
clang/include/clang/Lex/DependencyDirectivesSourceMinimizer.h
clang/include/clang/Lex/PPCallbacks.h
clang/include/clang/Lex/PPConditionalDirectiveRecord.h
clang/include/clang/Lex/PreprocessingRecord.h
clang/include/clang/Lex/Preprocessor.h
clang/lib/Basic/IdentifierTable.cpp
clang/lib/Format/UnwrappedLineParser.cpp
clang/lib/Index/IndexingAction.cpp
clang/lib/Lex/DependencyDirectivesSourceMinimizer.cpp
clang/lib/Lex/Lexer.cpp
clang/lib/Lex/PPConditionalDirectiveRecord.cpp
clang/lib/Lex/PPDirectives.cpp
clang/lib/Lex/PreprocessingRecord.cpp
clang/lib/Lex/Preprocessor.cpp
clang/lib/Sema/SemaCodeComplete.cpp
clang/test/Index/complete-preprocessor.m
clang/test/Preprocessor/if_warning.c
clang/test/Preprocessor/ifdef-recover.c
clang/test/Preprocessor/macro_misc.c
clang/test/Preprocessor/macro_vaopt_check.cpp
clang/unittests/Lex/DependencyDirectivesSourceMinimizerTest.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticLexKinds.td 
b/clang/include/clang/Basic/DiagnosticLexKinds.td
index 64026a1ee9227..ce6d0d0394b48 100644
--- a/clang/include/clang/Basic/DiagnosticLexKinds.td
+++ b/clang/include/clang/Basic/DiagnosticLexKinds.td
@@ -455,9 +455,11 @@ def err_pp_malformed_ident : Error<"invalid #ident 
directive">;
 def err_pp_unterminated_conditional : Error<
   "unterminated conditional directive">;
 def pp_err_else_after_else : Error<"#else after #else">;
-def pp_err_elif_after_else : Error<"#elif after #else">;
+def pp_err_elif_after_else : Error<
+  "%select{#elif|#elifdef|#elifndef}0 after #else">;
 def pp_err_else_without_if : Error<"#else without #if">;
-def pp_err_elif_without_if : Error<"#elif without #if">;
+def pp_err_elif_without_if : Error<
+  "%select{#elif|#elifdef|#elifndef}0 without #if">;
 def err_pp_endif_without_if : Error<"#endif without #if">;
 def err_pp_expected_value_in_expr : Error<"expected value in expression">;
 def err_pp_expected_rparen : Error<"expected ')' in preprocessor expression">;

diff  --git a/clang/include/clang/Basic/TokenKinds.def 
b/clang/include/clang/Basic/TokenKinds.def
index 572ebae6618db..be258c95d2fac 100644
--- a/clang/include/clang/Basic/TokenKinds.def
+++ b/clang/include/clang/Basic/TokenKinds.def
@@ -98,6 +98,8 @@ PPKEYWORD(if)
 PPKEYWORD(ifdef)
 PPKEYWORD(ifndef)
 PPKEYWORD(elif)
+PPKEYWORD(elifdef)
+PPKEYWORD(elifndef)
 PPKEYWORD(else)
 PPKEYWORD(endif)
 PPKEYWORD(defined)

diff  --git a/clang/include/clang/Lex/DependencyDirectivesSourceMinimizer.h 
b/clang/include/clang/Lex/DependencyDirectivesSourceMinimizer.h
index d832df6b6146b..9bb820156c252 100644
--- a/clang/include/clang/Lex/DependencyDirectivesSourceMinimizer.h
+++ b/clang/include/clang/Lex/DependencyDirectivesSourceMinimizer.h
@@ -44,6 +44,8 @@ enum TokenKind {
   pp_ifdef,
   pp_ifndef,
   pp_elif,
+  pp_elifdef,
+  pp_elifndef,
   pp_else,
   pp_endif,
   decl_at_import,

diff  --git a/clang/include/clang/Lex/PPCallbacks.h 
b/clang/include/clang/Lex/PPCallbacks.h
index de5e8eb2ca220..d57be1990caff 100644
--- a/clang/include/clang/Lex/PPCallbacks.h
+++ b/clang/include/clang/Lex/PPCallbacks.h
@@ -351,6 +351,22 @@ class PPCallbacks {
  const MacroDefinition &MD) {
   }
 
+  /// Hook called whenever an \#elifdef branch is taken.
+  /// \param Loc the source location of the directive.
+  /// \param MacroNameTok Information on the token being tested.
+  /// \param MD The MacroDefinition if the name was a macro, null otherwise.
+  virtual void Elifdef(SourceLocation Loc, const Token &MacroNameTok,
+   const MacroDefinition &MD) {
+  }
+  /// Hook called whenever an \#elifdef is skipped.
+  /// \param Loc the source location of the directive.
+  /// \param ConditionRange The SourceRange of the expression being tested.
+  /// \param IfLoc the source location of the \#if/\#ifdef/\#ifndef directive.
+  // FIXME: better to pass in a list (or tree!) of Tokens.
+  virtual void Elifdef(SourceLocation Loc, SourceRange ConditionRange,
+   SourceLocation IfLoc) {
+  }
+
   /// Hook called whene

[PATCH] D101192: Add support for #elifdef and #elifndef

2021-05-27 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman closed this revision.
aaron.ballman added a comment.

I've landed in 8edd3464afbff65d7d5945b3a8b20009d6ff5deb 



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

https://reviews.llvm.org/D101192

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


[PATCH] D66481: [C++20] Support for lambdas in unevaluated context

2021-05-27 Thread Stéphane Janel via Phabricator via cfe-commits
sjanel added a comment.

Hello,

Any news on this? GCC and MSVC support them since a while now.

Thanks a lot in advance !

Stephane


Repository:
  rC Clang

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

https://reviews.llvm.org/D66481

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


[PATCH] D103112: Reimplement __builtin_unique_stable_name as __builtin_sycl_unique_stable_name

2021-05-27 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: clang/include/clang/AST/Expr.h:2045
+// representation of the type (or type of the expression) in a way that permits
+// us to properly encode information about the SYCL kernels.
+class UniqueStableNameExpr final

rjmccall wrote:
> erichkeane wrote:
> > rjmccall wrote:
> > > rjmccall wrote:
> > > > Since this is really just for internal use in system headers (right?), 
> > > > is there a need for it to be as flexible as this about whether it takes 
> > > > an expression or a type?
> > > That said, I don't really have a strong objection to supporting either a 
> > > type or an expression operand.
> > I had responded to this I thought?  I found no good reason to do 
> > expression, we can sprinkle decltype around to deal with that, I'll prep a 
> > patch to remove the expr bits.
> Okay.  So this doesn't really need trailing storage anymore, and the 
> documentation needs to be updated to not mention the expression production.
Oh!  Good point!  *doh!*



Comment at: clang/include/clang/AST/Mangle.h:174
+  using KernelMangleCallbackTy =
+  llvm::Optional (*)(ASTContext &, const CXXRecordDecl *);
   explicit ItaniumMangleContext(ASTContext &C, DiagnosticsEngine &D)

rjmccall wrote:
> The concept here isn't kernel-specific, and it's not an arbitrary callback.  
> I think it would be better to call this something more generic, like 
> DiscriminatorOverride.
> 
> Should the argument have to be a record?  Other local declarations can show 
> up as e.g. template arguments, like enums or (I think) static local variables.
Currently we are only specializing this for lambdas, so I chose CXXRecordDecl 
to avoid the need to cast in each of the 'discriminators'.  I will switch it to 
'NamedDecl', though both discriminators will be only checking CXXRecordDecl 
stuff.



Comment at: clang/include/clang/Basic/LangOptions.h:448
+
+  bool isSYCL() const { return SYCLIsDevice || SYCLIsHost; }
 };

aaron.ballman wrote:
> FWIW, we also have `SYCLVersion != SYCL_None` as a possible way to express 
> this. Perhaps we should just use that anywhere we're using `SYCLIsDevice || 
> SYCLIsHost` currently? (I don't have a strong opinion but am bringing it up 
> in case someone else does.)
IMO, that is a fairly 'indirect' mechanism for it. I think host+device is the 
'right' way to do it, an d I think the SYCLVersion is a 'consequence' of those.

It is unfortunate that SYCL forces us to have 3 things to express in language 
opts (vs 2 for the other languages).




Comment at: clang/test/CodeGenSYCL/unique_stable_name.cpp:86-89
+  // FIXME: Ensure that j is incremented because VLAs are terrible.
+  int j = 55;
+  puts(__builtin_sycl_unique_stable_name(int[++j]));
+  // CHECK: call spir_func void @puts(i8 addrspace(4)* addrspacecast (i8* 
getelementptr inbounds ([[STRING_SIZE]], [[STRING_SIZE]]* @[[STRING]], i32 0, 
i32 0) to i8 addrspace(4)*))

aaron.ballman wrote:
> @rjmccall  -- any opinions or ideas on this? I think VLAs should likely 
> behave the same as they do in `sizeof`, etc.
VLA side-effects are a bit of an edge case in the language that I think are an 
unfortunate 'gotcha'.  

I'm not sure where I fall on this in general (other than hating it as a 
'feature' of C), but I'd hope that this is something we can leave as a FIXME, 
as this is a builtin for the use of a library.  I don't suspect that it will 
affect the normal uses of this builtin at all, so I hope it is something we 
look into once someone actually cares.


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

https://reviews.llvm.org/D103112

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


[PATCH] D102839: [RISCV][Clang] Add -mno-div option to disable hardware int division

2021-05-27 Thread Kito Cheng via Phabricator via cfe-commits
kito-cheng added a comment.

Personally I prefer to deprecate `-mno-div` soon, but based on the rule for 
RISC-V GNU toolchain, it need to wait `Zmmul` extension frozen.
My plan is deprecate the `-mno-div` and emit warning to tell user should use 
`Zmmul` instead once it frozen.


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

https://reviews.llvm.org/D102839

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


[PATCH] D102760: [llvm] Let SmallVector construct from any Iterable

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



Comment at: llvm/include/llvm/ADT/IterableTraits.h:17-31
+namespace detail {
+
+template  auto is_forward_iterator(...) -> std::false_type;
+
+template 
+auto is_forward_iterator(int) -> decltype(
+std::next(std::declval()),

Instead of all this, I would recommend
```
template
using is_input_iterator = std::is_base_of::iterator_category>;

template
using iterator_type_of = std::decay_t()))>;

template
struct is_range_iterable : std::false_type {};

template
struct is_range_iterable>::type> : std::true_type {};
```
(Notice that we're supposed to be checking for //input// iterability, not 
//forward// iterability. But also, the right way to see if something is an 
input iterator is not to check an ad-hoc bunch of operators like `*` and `!=`, 
but simply to check its STL iterator category.)

However, in real life, I personally would reject this patch, because I think 
"saving a couple of calls to begin/end at the call site" is not worth the peril 
of letting people accidentally write e.g.
```
SmallVector v("hello world");
assert(v.size() == 12);  // elements are "h"s, "e"s, "l"s, etc.
```



Comment at: llvm/include/llvm/ADT/SmallVector.h:1191-1194
+  template 
+  explicit SmallVector(
+  Iterable &&Range,
+  std::enable_if_t::value, bool> = true)

Watch out: this greedy constructor template will be used for non-const copy 
construction, e.g.

SmallVector x;
SmallVector y = x;  // calls 
SmallVector::SmallVector&>(SmallVector&, bool),
// which is a better match than SmallVector::SmallVector(const 
SmallVector&)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D102760

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


[PATCH] D103112: Reimplement __builtin_unique_stable_name as __builtin_sycl_unique_stable_name

2021-05-27 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/include/clang/Basic/LangOptions.h:448
+
+  bool isSYCL() const { return SYCLIsDevice || SYCLIsHost; }
 };

erichkeane wrote:
> aaron.ballman wrote:
> > FWIW, we also have `SYCLVersion != SYCL_None` as a possible way to express 
> > this. Perhaps we should just use that anywhere we're using `SYCLIsDevice || 
> > SYCLIsHost` currently? (I don't have a strong opinion but am bringing it up 
> > in case someone else does.)
> IMO, that is a fairly 'indirect' mechanism for it. I think host+device is the 
> 'right' way to do it, an d I think the SYCLVersion is a 'consequence' of 
> those.
> 
> It is unfortunate that SYCL forces us to have 3 things to express in language 
> opts (vs 2 for the other languages).
> 
That's a fair point -- I'm happy with either approach. Using `isSYCL()` is 
similarly expressive but with less typing, so I'm fine with it.



Comment at: clang/test/CodeGenSYCL/unique_stable_name.cpp:86-89
+  // FIXME: Ensure that j is incremented because VLAs are terrible.
+  int j = 55;
+  puts(__builtin_sycl_unique_stable_name(int[++j]));
+  // CHECK: call spir_func void @puts(i8 addrspace(4)* addrspacecast (i8* 
getelementptr inbounds ([[STRING_SIZE]], [[STRING_SIZE]]* @[[STRING]], i32 0, 
i32 0) to i8 addrspace(4)*))

erichkeane wrote:
> aaron.ballman wrote:
> > @rjmccall  -- any opinions or ideas on this? I think VLAs should likely 
> > behave the same as they do in `sizeof`, etc.
> VLA side-effects are a bit of an edge case in the language that I think are 
> an unfortunate 'gotcha'.  
> 
> I'm not sure where I fall on this in general (other than hating it as a 
> 'feature' of C), but I'd hope that this is something we can leave as a FIXME, 
> as this is a builtin for the use of a library.  I don't suspect that it will 
> affect the normal uses of this builtin at all, so I hope it is something we 
> look into once someone actually cares.
My feeling is: I think we should support the usual VLA semantics if SYCL 
supports VLAs in any way. If it's easy to do so as part of this patch then 
great, but if it continues to elude us, I'm totally fine doing it as a 
follow-up because this is definitely a wonky edge case.


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

https://reviews.llvm.org/D103112

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


[clang] ce276b7 - Fix -Wswitch warning; NFC

2021-05-27 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2021-05-27T09:24:43-04:00
New Revision: ce276b7a6448d9c30f55235392c38b0416e91bbb

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

LOG: Fix -Wswitch warning; NFC

Added: 


Modified: 
clang/lib/Lex/PPDirectives.cpp

Removed: 




diff  --git a/clang/lib/Lex/PPDirectives.cpp b/clang/lib/Lex/PPDirectives.cpp
index 1ccf24c6f767..8fe70668a406 100644
--- a/clang/lib/Lex/PPDirectives.cpp
+++ b/clang/lib/Lex/PPDirectives.cpp
@@ -3259,6 +3259,9 @@ void Preprocessor::HandleElifFamilyDirective(Token 
&ElifToken,
 case tok::pp_elifndef:
   Callbacks->Elifndef(ElifToken.getLocation(), ConditionRange, CI.IfLoc);
   break;
+default:
+  assert(false && "unexpected directive kind");
+  break;
 }
   }
 



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


[PATCH] D103112: Reimplement __builtin_unique_stable_name as __builtin_sycl_unique_stable_name

2021-05-27 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: clang/test/CodeGenSYCL/unique_stable_name.cpp:86-89
+  // FIXME: Ensure that j is incremented because VLAs are terrible.
+  int j = 55;
+  puts(__builtin_sycl_unique_stable_name(int[++j]));
+  // CHECK: call spir_func void @puts(i8 addrspace(4)* addrspacecast (i8* 
getelementptr inbounds ([[STRING_SIZE]], [[STRING_SIZE]]* @[[STRING]], i32 0, 
i32 0) to i8 addrspace(4)*))

aaron.ballman wrote:
> erichkeane wrote:
> > aaron.ballman wrote:
> > > @rjmccall  -- any opinions or ideas on this? I think VLAs should likely 
> > > behave the same as they do in `sizeof`, etc.
> > VLA side-effects are a bit of an edge case in the language that I think are 
> > an unfortunate 'gotcha'.  
> > 
> > I'm not sure where I fall on this in general (other than hating it as a 
> > 'feature' of C), but I'd hope that this is something we can leave as a 
> > FIXME, as this is a builtin for the use of a library.  I don't suspect that 
> > it will affect the normal uses of this builtin at all, so I hope it is 
> > something we look into once someone actually cares.
> My feeling is: I think we should support the usual VLA semantics if SYCL 
> supports VLAs in any way. If it's easy to do so as part of this patch then 
> great, but if it continues to elude us, I'm totally fine doing it as a 
> follow-up because this is definitely a wonky edge case.
I looked into it at one point, and it seems that the VLA handling in sizeof 
(and similar builtins) is done quite manually in quite a few places, it seemed 
like a pretty involved amount of work.  I'd still hope to do it as a part of a 
follow-up (keyed by a user mentioning they care).

So I checked up on this... 
1- The SYCL "Language" spec doesn't support VLAs at all (the same way C++ 
doesnt :)).

2- In our to-be-upstreamed downstream, we enforce the SYCL language rule that 
VLAs aren't allowed to be passed to kernels as they aren't a sized type.

3- The offload 'spir' target that is used for SYCL ALSO disallows VLAs with the 
error: error: variable length arrays are not supported for the current target

So I think it would be quite a bit of twisting for someone to get this builtin 
to apply to a VLA.  WDYT?


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

https://reviews.llvm.org/D103112

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


[PATCH] D103112: Reimplement __builtin_unique_stable_name as __builtin_sycl_unique_stable_name

2021-05-27 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/test/CodeGenSYCL/unique_stable_name.cpp:86-89
+  // FIXME: Ensure that j is incremented because VLAs are terrible.
+  int j = 55;
+  puts(__builtin_sycl_unique_stable_name(int[++j]));
+  // CHECK: call spir_func void @puts(i8 addrspace(4)* addrspacecast (i8* 
getelementptr inbounds ([[STRING_SIZE]], [[STRING_SIZE]]* @[[STRING]], i32 0, 
i32 0) to i8 addrspace(4)*))

erichkeane wrote:
> aaron.ballman wrote:
> > erichkeane wrote:
> > > aaron.ballman wrote:
> > > > @rjmccall  -- any opinions or ideas on this? I think VLAs should likely 
> > > > behave the same as they do in `sizeof`, etc.
> > > VLA side-effects are a bit of an edge case in the language that I think 
> > > are an unfortunate 'gotcha'.  
> > > 
> > > I'm not sure where I fall on this in general (other than hating it as a 
> > > 'feature' of C), but I'd hope that this is something we can leave as a 
> > > FIXME, as this is a builtin for the use of a library.  I don't suspect 
> > > that it will affect the normal uses of this builtin at all, so I hope it 
> > > is something we look into once someone actually cares.
> > My feeling is: I think we should support the usual VLA semantics if SYCL 
> > supports VLAs in any way. If it's easy to do so as part of this patch then 
> > great, but if it continues to elude us, I'm totally fine doing it as a 
> > follow-up because this is definitely a wonky edge case.
> I looked into it at one point, and it seems that the VLA handling in sizeof 
> (and similar builtins) is done quite manually in quite a few places, it 
> seemed like a pretty involved amount of work.  I'd still hope to do it as a 
> part of a follow-up (keyed by a user mentioning they care).
> 
> So I checked up on this... 
> 1- The SYCL "Language" spec doesn't support VLAs at all (the same way C++ 
> doesnt :)).
> 
> 2- In our to-be-upstreamed downstream, we enforce the SYCL language rule that 
> VLAs aren't allowed to be passed to kernels as they aren't a sized type.
> 
> 3- The offload 'spir' target that is used for SYCL ALSO disallows VLAs with 
> the error: error: variable length arrays are not supported for the current 
> target
> 
> So I think it would be quite a bit of twisting for someone to get this 
> builtin to apply to a VLA.  WDYT?
> So I think it would be quite a bit of twisting for someone to get this 
> builtin to apply to a VLA. WDYT?

Sold on leaving this as a FIXME until someone finds an actual issue they care 
about. Thanks for checking on all this!


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

https://reviews.llvm.org/D103112

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


[PATCH] D103112: Reimplement __builtin_unique_stable_name as __builtin_sycl_unique_stable_name

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

LGTM, thanks Erich!


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

https://reviews.llvm.org/D103112

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


[PATCH] D103195: Add matchers for gtest's ASSERT_THAT, EXPECT_THAT, ON_CALL and EXPECT_CALL

2021-05-27 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clang/include/clang/ASTMatchers/GtestMatchers.h:34
 
+enum class MockArgs {
+  NoMatchers,

ymandel wrote:
> hokein wrote:
> > worth comments.
> > 
> > out of curiosity, what do we call this `Matchers`? I'd be careful to 
> > introduce a different matcher concept in the ast_matcher library, it would 
> > easily cause confusion. 
> +1 Please move the comments relating to this enum from the two `gtestOnCall` 
> functions to here.
> 
> hokein@ -- the "Matchers" is because its describing googletest matchers.  
> But, it is a bit confusing in this context and doesn't really add anything. 
> What do you think of `None` and `Some` instead?
> What do you think of None and Some instead?

this sounds good to me.



Comment at: clang/lib/ASTMatchers/GtestMatchers.cpp:47
 
-static llvm::StringRef getAssertMacro(GtestCmp Cmp) {
-  switch (Cmp) {
-case GtestCmp::Eq:
-  return "ASSERT_EQ";
-case GtestCmp::Ne:
-  return "ASSERT_NE";
-case GtestCmp::Ge:
-  return "ASSERT_GE";
-case GtestCmp::Gt:
-  return "ASSERT_GT";
-case GtestCmp::Le:
-  return "ASSERT_LE";
-case GtestCmp::Lt:
-  return "ASSERT_LT";
+static llvm::StringRef getMacroTypeName(MacroType Macro) {
+  switch (Macro) {

ymandel wrote:
> hokein wrote:
> > the `static` qualifier is not needed as you wrap it within an anonymous 
> > namespace. the same below.
> nit: per the style guide 
> (https://releases.llvm.org/2.7/docs/CodingStandards.html#micro_anonns), I 
> think it would be better to shrink the anonymous namespace to only enclose 
> the enum decl, and keep these `static` annotations and in fact add a few that 
> are currently missing on the `gtestCallInternal` functions.
Up to you -- I'm fine with either  (these two styles exit in LLVM codebase)- 
using anonymous namespace aligns more with google style...


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

https://reviews.llvm.org/D103195

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


[PATCH] D102696: [Analyzer] Find constraints that are directly attached to a BinOp

2021-05-27 Thread Gabor Marton via Phabricator via cfe-commits
martong added a comment.

Alright, I see your point. I agree that solving the problem of "$a +$b +$c
constrained and then $a + $c got constrained" requires canonicalization.
However, canonicalization seems to be not trivial to implement. And there are
some other easier cases that I think we could (should) solve before starting to
implement canonicalization.

Parent map is just an optimization. The functionality should be working even if
we apply brute-force to go through all existing constraints.

Because of the above, I suggest the following steps. These steps could be
implemented as individual patches that depend on each other and once all of
them accepted then we could merge them in one lock-step.

1. Update `setConstraint` to simplify existing constraints (and adding the

simplified constraint) when a new constraint is added. In this step we'd just
simply iterate over all existing constraints and would try to simplfy them with
`simplifySVal`. This would solve the simplest cases where we have two symbols
in the tree. E.g. these cases would pass:

  int test_rhs_further_constrained(int x, int y) {
if (x + y != 0)
  return 0;
if (y != 0)
  return 0;
clang_analyzer_eval(x + y == 0); // expected-warning{{TRUE}}
clang_analyzer_eval(y == 0); // expected-warning{{TRUE}}
return 0;
  }
  
  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;
  }



2. Add the capability to simplify more complex constraints, where there are 3

symbols in the tree. In this change I suggest the extension and overhaul of
`simplifySVal`. This change would make the following cases to pass (notice the
3rd check in each test-case).

  int test_left_tree_constrained(int x, int y, int z) {
if (x + y + z != 0)
  return 0;
if (x + y != 0)
  return 0;
clang_analyzer_eval(x + y + z == 0); // expected-warning{{TRUE}}
clang_analyzer_eval(x + y == 0); // expected-warning{{TRUE}}
clang_analyzer_eval(z == 0); // expected-warning{{TRUE}}
x = y = z = 1;
return 0;
  }
  
  int test_right_tree_constrained(int x, int y, int z) {
if (x + (y + z) != 0)
  return 0;
if (y + z != 0)
  return 0;
clang_analyzer_eval(x + y + z == 0); // expected-warning{{TRUE}}
clang_analyzer_eval(y + z == 0); // expected-warning{{TRUE}}
clang_analyzer_eval(x == 0); // expected-warning{{TRUE}}
return 0;
  }



3. Add canonical trees to the solver. The way we should do this is to build

"flat" sub-trees of associative operands. E.g. `b + a + c` becomes `+(a, b, c)`,
i.e. a tree with a root and 3 children [1]. The ordering of the children
could be done by their addresses (`Stmt *`) and we could simply store them in an
array. Probably we'll need a new mapping: SymbolRef -> CanonicalTree.

When a new constraint is added then we build up its canonical tree (if not
existing yet) Then, we check each existing constraints' canonical tree to check
whether the newly constrained expression is a sub-expression of that. (The
check could be a simple recursively descending search in the children arrays of
the nodes.) If it is a sub-expression then we simplify that with a customized
canonical tree visitor that will call evalBinOp appropriately.

In this step we should handle only `+` and `*`

This would pass the below tests:

  int test_left_tree_constrained_commutative(int x, int y, int z) {
if (x + y + z != 0)
  return 0;
if (y + x != 0)
  return 0;
clang_analyzer_eval(x + y + z == 0); // expected-warning{{TRUE}}
clang_analyzer_eval(x + y == 0); // expected-warning{{TRUE}}
clang_analyzer_eval(z == 0); // expected-warning{{TRUE}}
return 0;
  }
  
  int test_associative(int x, int y, int z) {
if (x + y + z != 0)
  return 0;
if (x + z != 0)
  return 0;
clang_analyzer_printState();
clang_analyzer_eval(x + y + z == 0); // expected-warning{{TRUE}}
clang_analyzer_eval(x + z == 0); // expected-warning{{TRUE}}
clang_analyzer_eval(y == 0); // expected-warning{{TRUE}}
return 0;



4. Extend 3) with `-` and `/`. `lhs - rhs` becomes a `lhs + (-rhs)` and `lhs 
/rhs`

is substituted wit `lhs * (1/rhs)`.

5. There are still some expressions that the solver will not be able to reason 
about

(e.g. `<<`), but it may happen that we store a constraint for them. In these
cases it is a good idea to search for the expression in the constraint map, but
without constant folding. This functionality might be solved by step 2). If
not, then https://reviews.llvm.org/D102696 could be a good alternative.

6. Do performance measurements and enhance perhaps with parent maps.

I am planning to upload a patch for steps 1) and 2) very soon.

[1] Hans Vangheluwe et al, An

[PATCH] D103241: [OpenCL] Add memory_scope_all_devices

2021-05-27 Thread Sven van Haastregt via Phabricator via cfe-commits
svenvh updated this revision to Diff 348245.
svenvh edited the summary of this revision.
svenvh added a comment.

Update change to be header-only.


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

https://reviews.llvm.org/D103241

Files:
  clang/lib/Headers/opencl-c-base.h
  clang/test/Headers/opencl-c-header.cl
  clang/test/SemaOpenCL/atomic-ops.cl


Index: clang/test/SemaOpenCL/atomic-ops.cl
===
--- clang/test/SemaOpenCL/atomic-ops.cl
+++ clang/test/SemaOpenCL/atomic-ops.cl
@@ -2,6 +2,7 @@
 // RUN:   -fsyntax-only -triple=spir64 -fdeclare-opencl-builtins 
-finclude-default-header
 // RUN: %clang_cc1 %s -cl-std=CL2.0 -verify -fsyntax-only \
 // RUN:   -triple=amdgcn-amd-amdhsa -fdeclare-opencl-builtins 
-finclude-default-header
+// TODO: add -cl-std=CL3.0 line when generic and psv are supported.
 
 // Basic parsing/Sema tests for __opencl_atomic_*
 
@@ -161,6 +162,11 @@
   (void)__opencl_atomic_load(Ap, memory_order_relaxed, 
memory_scope_work_group);
   (void)__opencl_atomic_load(Ap, memory_order_relaxed, memory_scope_device);
   (void)__opencl_atomic_load(Ap, memory_order_relaxed, 
memory_scope_all_svm_devices);
+  (void)__opencl_atomic_load(Ap, memory_order_relaxed, 
memory_scope_all_devices);
+#if __OPENCL_C_VERSION__ < CL_VERSION_3_0
+  // expected-error@-2{{use of undeclared identifier 
'memory_scope_all_devices'}}
+  // expected-note@* {{'memory_scope_all_svm_devices' declared here}}
+#endif
   (void)__opencl_atomic_load(Ap, memory_order_relaxed, memory_scope_sub_group);
   (void)__opencl_atomic_load(Ap, memory_order_relaxed, scope);
   (void)__opencl_atomic_load(Ap, memory_order_relaxed, 10);
//expected-error{{synchronization scope argument to atomic operation is 
invalid}}
Index: clang/test/Headers/opencl-c-header.cl
===
--- clang/test/Headers/opencl-c-header.cl
+++ clang/test/Headers/opencl-c-header.cl
@@ -151,7 +151,13 @@
 #endif //(defined(__OPENCL_CPP_VERSION__) || __OPENCL_C_VERSION__ >= 200)
 
 // OpenCL C features.
-#if (defined(__OPENCL_CPP_VERSION__) || __OPENCL_C_VERSION__ == 200)
+#if (__OPENCL_C_VERSION__ == 300)
+
+#if __opencl_c_atomic_scope_all_devices != 1
+#error "Incorrectly defined feature macro __opencl_c_atomic_scope_all_devices"
+#endif
+
+#elif (defined(__OPENCL_CPP_VERSION__) || __OPENCL_C_VERSION__ == 200)
 
 #ifndef  __opencl_c_pipes
 #error "Feature macro __opencl_c_pipes should be defined"
Index: clang/lib/Headers/opencl-c-base.h
===
--- clang/lib/Headers/opencl-c-base.h
+++ clang/lib/Headers/opencl-c-base.h
@@ -39,6 +39,11 @@
 #define __opencl_c_images 1
 #endif
 
+// Define header-only feature macros for OpenCL C 3.0.
+#if (__OPENCL_C_VERSION__ == 300)
+#define __opencl_c_atomic_scope_all_devices 1
+#endif
+
 // built-in scalar data types:
 
 /**
@@ -312,7 +317,12 @@
   memory_scope_work_item = __OPENCL_MEMORY_SCOPE_WORK_ITEM,
   memory_scope_work_group = __OPENCL_MEMORY_SCOPE_WORK_GROUP,
   memory_scope_device = __OPENCL_MEMORY_SCOPE_DEVICE,
+#if defined(__opencl_c_atomic_scope_all_devices)
   memory_scope_all_svm_devices = __OPENCL_MEMORY_SCOPE_ALL_SVM_DEVICES,
+#if (__OPENCL_C_VERSION__ >= CL_VERSION_3_0)
+  memory_scope_all_devices = memory_scope_all_svm_devices,
+#endif // __OPENCL_C_VERSION__ >= CL_VERSION_3_0
+#endif // defined(__opencl_c_atomic_scope_all_devices)
 #if defined(cl_intel_subgroups) || defined(cl_khr_subgroups)
   memory_scope_sub_group = __OPENCL_MEMORY_SCOPE_SUB_GROUP
 #endif


Index: clang/test/SemaOpenCL/atomic-ops.cl
===
--- clang/test/SemaOpenCL/atomic-ops.cl
+++ clang/test/SemaOpenCL/atomic-ops.cl
@@ -2,6 +2,7 @@
 // RUN:   -fsyntax-only -triple=spir64 -fdeclare-opencl-builtins -finclude-default-header
 // RUN: %clang_cc1 %s -cl-std=CL2.0 -verify -fsyntax-only \
 // RUN:   -triple=amdgcn-amd-amdhsa -fdeclare-opencl-builtins -finclude-default-header
+// TODO: add -cl-std=CL3.0 line when generic and psv are supported.
 
 // Basic parsing/Sema tests for __opencl_atomic_*
 
@@ -161,6 +162,11 @@
   (void)__opencl_atomic_load(Ap, memory_order_relaxed, memory_scope_work_group);
   (void)__opencl_atomic_load(Ap, memory_order_relaxed, memory_scope_device);
   (void)__opencl_atomic_load(Ap, memory_order_relaxed, memory_scope_all_svm_devices);
+  (void)__opencl_atomic_load(Ap, memory_order_relaxed, memory_scope_all_devices);
+#if __OPENCL_C_VERSION__ < CL_VERSION_3_0
+  // expected-error@-2{{use of undeclared identifier 'memory_scope_all_devices'}}
+  // expected-note@* {{'memory_scope_all_svm_devices' declared here}}
+#endif
   (void)__opencl_atomic_load(Ap, memory_order_relaxed, memory_scope_sub_group);
   (void)__opencl_atomic_load(Ap, memory_order_relaxed, scope);
   (void)__opencl_atomic_load(Ap, memory_order_relaxed, 10);//expected-error{{synchronization scope argume

[clang] 758f51c - Speculatively fix a -Woverloaded-virtual diagnostic; NFC

2021-05-27 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2021-05-27T09:49:39-04:00
New Revision: 758f51c14ac3d4f243fce83e9733e2aea44dbd9e

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

LOG: Speculatively fix a -Woverloaded-virtual diagnostic; NFC

Added: 


Modified: 
clang/include/clang/Lex/PreprocessingRecord.h

Removed: 




diff  --git a/clang/include/clang/Lex/PreprocessingRecord.h 
b/clang/include/clang/Lex/PreprocessingRecord.h
index 52f1ec9e59bb..54489cb3a564 100644
--- a/clang/include/clang/Lex/PreprocessingRecord.h
+++ b/clang/include/clang/Lex/PreprocessingRecord.h
@@ -538,6 +538,8 @@ class Token;
const MacroDefinition &MD) override;
 void Ifndef(SourceLocation Loc, const Token &MacroNameTok,
 const MacroDefinition &MD) override;
+
+using PPCallbacks::Elifdef, PPCallback::Elifndef;
 void Elifdef(SourceLocation Loc, const Token &MacroNameTok,
  const MacroDefinition &MD) override;
 void Elifndef(SourceLocation Loc, const Token &MacroNameTok,



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


[PATCH] D103241: [OpenCL] Add memory_scope_all_devices

2021-05-27 Thread Sven van Haastregt via Phabricator via cfe-commits
svenvh added inline comments.



Comment at: clang/include/clang/Basic/OpenCLExtensions.def:113
 OPENCL_OPTIONALCOREFEATURE(__opencl_c_atomic_order_seq_cst, false, 300, 
OCL_C_30)
+OPENCL_OPTIONALCOREFEATURE(__opencl_c_atomic_scope_all_devices, false, 300, 
OCL_C_30)
 OPENCL_OPTIONALCOREFEATURE(__opencl_c_subgroups, false, 300, OCL_C_30)

Anastasia wrote:
> azabaznov wrote:
> > This feature is header only. We had a lot of discussions on that and the 
> > main idea was not to declare header only features/extensions in 
> > `OpenCLExtensions.def` and use `-D__opencl_c_atomic_scope_all_devices=1` 
> > instead, @Anastasia can comment on this.
> > 
> > I personally would like to introduce new flag for OpenCL options in 
> > `OpenCLExtensions.def` which will indicate that feature/extension is 
> > header-only, and thus all of such options can be declared in 
> > `OpenCLExtensions.def`: if flag is set to true it can be stripped out from 
> > the parser. What do you think about this?
> Yes, I agree the idea is to align with C/C++ directions for scalability i.e. 
> we should only add what is absolutely necessary to the compiler and implement 
> the rest using libraries - just like regular C and C++. We won't be able to 
> scale if we keep adding everything in the compiler. In fact, we already have 
> a huge scalability issue with our builtin functions. If we look at modern C++ 
> - more than 70% of features are not in the compiler at all.
> 
> Would it be possible to do something like suggested here: 
> https://reviews.llvm.org/D91531#change-AKXhB4ko4nAO for `cl_khr_depth_images`?
> 
> > I personally would like to introduce new flag for OpenCL options in 
> > OpenCLExtensions.def which will indicate that feature/extension is 
> > header-only, and thus all of such options can be declared in 
> > OpenCLExtensions.def: if flag is set to true it can be stripped out from 
> > the parser. What do you think about this?
> 
> Hmm, I think the macros should either be declared in the headers or using a 
> flag `-D`. I don't know why would adding them in `OpenCLExtensions.def` be 
> beneficial if we can use conventional approaches? This allows avoiding the 
> complexity and makes things more modular. If we look at the OpenCL vendor 
> extensions for example - we probably don't want them all in one place?
> This feature is header only.

Good catch!  I have updated the patch to define the feature macro in the header 
instead.  Currently that definition is not optional, since we don't have 
finalized the solution for handling this yet (though the __undef proposal seems 
to be compatible with this change).

> I personally would like to introduce new flag for OpenCL options in 
> OpenCLExtensions.def which will indicate that feature/extension is header-only

If we still need to add header-only features to OpenCLExtensions.def, then they 
aren't really header-only anymore I'd argue (as @Anastasia pointed out above).  
So I'm not sure we need it either, or perhaps I missed something.


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

https://reviews.llvm.org/D103241

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


[clang] caf86d2 - Speculatively fix this harder and with improved spelling capabilities.

2021-05-27 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2021-05-27T09:54:09-04:00
New Revision: caf86d2959d5e900ed29af5e0ae2be23e3d299c5

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

LOG: Speculatively fix this harder and with improved spelling capabilities.

Added: 


Modified: 
clang/include/clang/Lex/PreprocessingRecord.h
clang/lib/Index/IndexingAction.cpp

Removed: 




diff  --git a/clang/include/clang/Lex/PreprocessingRecord.h 
b/clang/include/clang/Lex/PreprocessingRecord.h
index 54489cb3a564..0137d871e916 100644
--- a/clang/include/clang/Lex/PreprocessingRecord.h
+++ b/clang/include/clang/Lex/PreprocessingRecord.h
@@ -539,7 +539,8 @@ class Token;
 void Ifndef(SourceLocation Loc, const Token &MacroNameTok,
 const MacroDefinition &MD) override;
 
-using PPCallbacks::Elifdef, PPCallback::Elifndef;
+using PPCallbacks::Elifdef;
+using PPCallbacks::Elifndef;
 void Elifdef(SourceLocation Loc, const Token &MacroNameTok,
  const MacroDefinition &MD) override;
 void Elifndef(SourceLocation Loc, const Token &MacroNameTok,

diff  --git a/clang/lib/Index/IndexingAction.cpp 
b/clang/lib/Index/IndexingAction.cpp
index 65479a483b17..c9fcaad31128 100644
--- a/clang/lib/Index/IndexingAction.cpp
+++ b/clang/lib/Index/IndexingAction.cpp
@@ -78,6 +78,8 @@ class IndexPPCallbacks final : public PPCallbacks {
*MD.getMacroInfo());
   }
 
+  using PPCallbacks::Elifdef;
+  using PPCallbacks::Elifndef;
   void Elifdef(SourceLocation Loc, const Token &MacroNameTok,
const MacroDefinition &MD) override {
 if (!MD.getMacroInfo()) // Ignore non-existent macro.



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


[PATCH] D98798: Produce warning for performing pointer arithmetic on a null pointer.

2021-05-27 Thread Jamie Schmeiser via Phabricator via cfe-commits
jamieschmeiser added a reviewer: thakis.
jamieschmeiser added a comment.

ping


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

https://reviews.llvm.org/D98798

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


[PATCH] D103231: [clang][AST] Set correct DeclContext in ASTImporter lookup table for ParmVarDecl.

2021-05-27 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.
Herald added a subscriber: rnkovacs.

Thanks, looks good to me, with a nit in the tests.




Comment at: clang/unittests/AST/ASTImporterTest.cpp:6199
+  EXPECT_TRUE(ImportedF);
+  EXPECT_FALSE(
+  SharedStatePtr->getLookupTable()

Instead of `.empty()`, perhaps we should examine if the found entry is indeed 
the imported ParmVarDecl.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103231

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


[PATCH] D103241: [OpenCL] Add memory_scope_all_devices

2021-05-27 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added inline comments.



Comment at: clang/include/clang/Basic/OpenCLExtensions.def:113
 OPENCL_OPTIONALCOREFEATURE(__opencl_c_atomic_order_seq_cst, false, 300, 
OCL_C_30)
+OPENCL_OPTIONALCOREFEATURE(__opencl_c_atomic_scope_all_devices, false, 300, 
OCL_C_30)
 OPENCL_OPTIONALCOREFEATURE(__opencl_c_subgroups, false, 300, OCL_C_30)

svenvh wrote:
> Anastasia wrote:
> > azabaznov wrote:
> > > This feature is header only. We had a lot of discussions on that and the 
> > > main idea was not to declare header only features/extensions in 
> > > `OpenCLExtensions.def` and use `-D__opencl_c_atomic_scope_all_devices=1` 
> > > instead, @Anastasia can comment on this.
> > > 
> > > I personally would like to introduce new flag for OpenCL options in 
> > > `OpenCLExtensions.def` which will indicate that feature/extension is 
> > > header-only, and thus all of such options can be declared in 
> > > `OpenCLExtensions.def`: if flag is set to true it can be stripped out 
> > > from the parser. What do you think about this?
> > Yes, I agree the idea is to align with C/C++ directions for scalability 
> > i.e. we should only add what is absolutely necessary to the compiler and 
> > implement the rest using libraries - just like regular C and C++. We won't 
> > be able to scale if we keep adding everything in the compiler. In fact, we 
> > already have a huge scalability issue with our builtin functions. If we 
> > look at modern C++ - more than 70% of features are not in the compiler at 
> > all.
> > 
> > Would it be possible to do something like suggested here: 
> > https://reviews.llvm.org/D91531#change-AKXhB4ko4nAO for 
> > `cl_khr_depth_images`?
> > 
> > > I personally would like to introduce new flag for OpenCL options in 
> > > OpenCLExtensions.def which will indicate that feature/extension is 
> > > header-only, and thus all of such options can be declared in 
> > > OpenCLExtensions.def: if flag is set to true it can be stripped out from 
> > > the parser. What do you think about this?
> > 
> > Hmm, I think the macros should either be declared in the headers or using a 
> > flag `-D`. I don't know why would adding them in `OpenCLExtensions.def` be 
> > beneficial if we can use conventional approaches? This allows avoiding the 
> > complexity and makes things more modular. If we look at the OpenCL vendor 
> > extensions for example - we probably don't want them all in one place?
> > This feature is header only.
> 
> Good catch!  I have updated the patch to define the feature macro in the 
> header instead.  Currently that definition is not optional, since we don't 
> have finalized the solution for handling this yet (though the __undef 
> proposal seems to be compatible with this change).
> 
> > I personally would like to introduce new flag for OpenCL options in 
> > OpenCLExtensions.def which will indicate that feature/extension is 
> > header-only
> 
> If we still need to add header-only features to OpenCLExtensions.def, then 
> they aren't really header-only anymore I'd argue (as @Anastasia pointed out 
> above).  So I'm not sure we need it either, or perhaps I missed something.
FYI we have already added extended subgroups extension macros for SPIR in 
`opencl-c-base.h` without the `__undef<...>` trick.

```
#if defined(__SPIR__)
#define cl_khr_subgroup_extended_types 1
#define cl_khr_subgroup_non_uniform_vote 1
#define cl_khr_subgroup_ballot 1
#define cl_khr_subgroup_non_uniform_arithmetic 1
#define cl_khr_subgroup_shuffle 1
#define cl_khr_subgroup_shuffle_relative 1
#define cl_khr_subgroup_clustered_reduce 1
#endif // defined(__SPIR__)
```

But extra conditions can be added any time if we get the agreement on the route 
forward. 



Comment at: clang/lib/Headers/opencl-c-base.h:44
+#if (__OPENCL_C_VERSION__ == 300)
+#define __opencl_c_atomic_scope_all_devices 1
+#endif

I think we should at least add a `defined(__SPIR__)` check though? Otherwise it 
won't be correct for other targets using the same header.


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

https://reviews.llvm.org/D103241

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


[PATCH] D103245: [clang-format] Fix PointerAlignmentRight with AlignConsecutiveDeclarations

2021-05-27 Thread Gerhard Gappmeier via Phabricator via cfe-commits
gergap updated this revision to Diff 348248.
gergap added a comment.

fixing some tests


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103245

Files:
  clang/unittests/Format/FormatTest.cpp


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -14881,6 +14881,7 @@
   FormatStyle Alignment = getLLVMStyle();
   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_None;
+  Alignment.PointerAlignment = FormatStyle::PAS_Right;
   verifyFormat("float const a = 5;\n"
"int oneTwoThree = 123;",
Alignment);
@@ -14916,8 +14917,8 @@
   verifyFormat("int  oneTwoThree{0}; // comment\n"
"unsigned oneTwo; // comment",
Alignment);
-  verifyFormat("unsigned int *  a;\n"
-   "int *   b;\n"
+  verifyFormat("unsigned int   *a;\n"
+   "int*b;\n"
"unsigned int Const *c;\n"
"unsigned int const *d;\n"
"unsigned int Const &e;\n"
@@ -15231,7 +15232,7 @@
Alignment);
   verifyFormat("void SomeFunction(int parameter = 0) {\n"
"  int const i = 1;\n"
-   "  int * j = 2;\n"
+   "  int  *j = 2;\n"
"  int   big = 1;\n"
"}",
Alignment);
@@ -15334,7 +15335,7 @@
" float b,\n"
" int   c,\n"
" uint32_t *d) {\n"
-   "  int *  e = 0;\n"
+   "  int   *e = 0;\n"
"  float  f = 0;\n"
"  double g = 0;\n"
"}\n"


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -14881,6 +14881,7 @@
   FormatStyle Alignment = getLLVMStyle();
   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_None;
+  Alignment.PointerAlignment = FormatStyle::PAS_Right;
   verifyFormat("float const a = 5;\n"
"int oneTwoThree = 123;",
Alignment);
@@ -14916,8 +14917,8 @@
   verifyFormat("int  oneTwoThree{0}; // comment\n"
"unsigned oneTwo; // comment",
Alignment);
-  verifyFormat("unsigned int *  a;\n"
-   "int *   b;\n"
+  verifyFormat("unsigned int   *a;\n"
+   "int*b;\n"
"unsigned int Const *c;\n"
"unsigned int const *d;\n"
"unsigned int Const &e;\n"
@@ -15231,7 +15232,7 @@
Alignment);
   verifyFormat("void SomeFunction(int parameter = 0) {\n"
"  int const i = 1;\n"
-   "  int * j = 2;\n"
+   "  int  *j = 2;\n"
"  int   big = 1;\n"
"}",
Alignment);
@@ -15334,7 +15335,7 @@
" float b,\n"
" int   c,\n"
" uint32_t *d) {\n"
-   "  int *  e = 0;\n"
+   "  int   *e = 0;\n"
"  float  f = 0;\n"
"  double g = 0;\n"
"}\n"
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] eba69b5 - Reimplement __builtin_unique_stable_name-

2021-05-27 Thread Erich Keane via cfe-commits

Author: Erich Keane
Date: 2021-05-27T07:12:20-07:00
New Revision: eba69b59d1a30dead07da2c279c8ecfd2b62ba9f

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

LOG: Reimplement __builtin_unique_stable_name-

The original version of this was reverted, and @rjmcall provided some
advice to architect a new solution.  This is that solution.

This implements a builtin to provide a unique name that is stable across
compilations of this TU for the purposes of implementing the library
component of the unnamed kernel feature of SYCL.  It does this by
running the Itanium mangler with a few modifications.

Because it is somewhat common to wrap non-kernel-related lambdas in
macros that aren't present on the device (such as for logging), this
uniquely generates an ID for all lambdas involved in the naming of a
kernel. It uses the lambda-mangling number to do this, except replaces
this with its own number (starting at 1 for readabililty reasons)
for lambdas used to name a kernel.

Additionally, this implements itself as constexpr with a slight catch:
if a name would be invalidated by the use of this lambda in a later
kernel invocation, it is diagnosed as an error (see the Sema tests).

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

Added: 
clang/test/AST/ast-print-sycl-unique-stable-name.cpp
clang/test/CodeGenSYCL/unique_stable_name.cpp
clang/test/ParserSYCL/unique_stable_name.cpp
clang/test/ParserSYCL/unique_stable_name_sycl_only.cpp
clang/test/SemaSYCL/unique_stable_name.cpp

Modified: 
clang/docs/LanguageExtensions.rst
clang/include/clang/AST/ASTContext.h
clang/include/clang/AST/ComputeDependence.h
clang/include/clang/AST/Expr.h
clang/include/clang/AST/JSONNodeDumper.h
clang/include/clang/AST/Mangle.h
clang/include/clang/AST/RecursiveASTVisitor.h
clang/include/clang/AST/TextNodeDumper.h
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/include/clang/Basic/LangOptions.h
clang/include/clang/Basic/StmtNodes.td
clang/include/clang/Basic/TokenKinds.def
clang/include/clang/Parse/Parser.h
clang/include/clang/Sema/Sema.h
clang/include/clang/Serialization/ASTBitCodes.h
clang/lib/AST/ASTContext.cpp
clang/lib/AST/ComputeDependence.cpp
clang/lib/AST/Expr.cpp
clang/lib/AST/ExprClassification.cpp
clang/lib/AST/ExprConstant.cpp
clang/lib/AST/ItaniumMangle.cpp
clang/lib/AST/JSONNodeDumper.cpp
clang/lib/AST/StmtPrinter.cpp
clang/lib/AST/StmtProfile.cpp
clang/lib/AST/TextNodeDumper.cpp
clang/lib/Basic/IdentifierTable.cpp
clang/lib/CodeGen/CGCUDANV.cpp
clang/lib/CodeGen/CGExprScalar.cpp
clang/lib/Parse/ParseExpr.cpp
clang/lib/Sema/SemaExceptionSpec.cpp
clang/lib/Sema/SemaExpr.cpp
clang/lib/Sema/SemaLambda.cpp
clang/lib/Sema/SemaSYCL.cpp
clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
clang/lib/Sema/TreeTransform.h
clang/lib/Serialization/ASTReaderStmt.cpp
clang/lib/Serialization/ASTWriterStmt.cpp
clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
clang/tools/libclang/CXCursor.cpp

Removed: 




diff  --git a/clang/docs/LanguageExtensions.rst 
b/clang/docs/LanguageExtensions.rst
index eb9fe0c0ac0d7..129e73345b2a2 100644
--- a/clang/docs/LanguageExtensions.rst
+++ b/clang/docs/LanguageExtensions.rst
@@ -1794,7 +1794,7 @@ correctly in any circumstances. It can be used if:
   metaprogramming algorithms to be able to specify/detect types generically.
 
 - the generated kernel binary does not contain indirect calls because they
-  are eliminated using compiler optimizations e.g. devirtualization. 
+  are eliminated using compiler optimizations e.g. devirtualization.
 
 - the selected target supports the function pointer like functionality e.g.
   most CPU targets.
@@ -2404,6 +2404,40 @@ argument.
   int *pb =__builtin_preserve_access_index(&v->c[3].b);
   __builtin_preserve_access_index(v->j);
 
+``__builtin_sycl_unique_stable_name``
+-
+
+``__builtin_sycl_unique_stable_name()`` is a builtin that takes a type and
+produces a string literal containing a unique name for the type that is stable
+across split compilations, mainly to support SYCL/Data Parallel C++ language.
+
+In cases where the split compilation needs to share a unique token for a type
+across the boundary (such as in an offloading situation), this name can be used
+for lookup purposes, such as in the SYCL Integration Header.
+
+The value of this builtin is computed entirely at compile time, so it can be
+used in constant expressions. This value encodes lambda functions based on a
+stable numbering order in which they appear in their local declaration 
contexts.
+Once this builtin is evaluated in a constexpr context, it is erroneous to use
+i

[PATCH] D103112: Reimplement __builtin_unique_stable_name as __builtin_sycl_unique_stable_name

2021-05-27 Thread Erich Keane 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 rGeba69b59d1a3: Reimplement __builtin_unique_stable_name- 
(authored by erichkeane).
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103112

Files:
  clang/docs/LanguageExtensions.rst
  clang/include/clang/AST/ASTContext.h
  clang/include/clang/AST/ComputeDependence.h
  clang/include/clang/AST/Expr.h
  clang/include/clang/AST/JSONNodeDumper.h
  clang/include/clang/AST/Mangle.h
  clang/include/clang/AST/RecursiveASTVisitor.h
  clang/include/clang/AST/TextNodeDumper.h
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Basic/LangOptions.h
  clang/include/clang/Basic/StmtNodes.td
  clang/include/clang/Basic/TokenKinds.def
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/Sema.h
  clang/include/clang/Serialization/ASTBitCodes.h
  clang/lib/AST/ASTContext.cpp
  clang/lib/AST/ComputeDependence.cpp
  clang/lib/AST/Expr.cpp
  clang/lib/AST/ExprClassification.cpp
  clang/lib/AST/ExprConstant.cpp
  clang/lib/AST/ItaniumMangle.cpp
  clang/lib/AST/JSONNodeDumper.cpp
  clang/lib/AST/StmtPrinter.cpp
  clang/lib/AST/StmtProfile.cpp
  clang/lib/AST/TextNodeDumper.cpp
  clang/lib/Basic/IdentifierTable.cpp
  clang/lib/CodeGen/CGCUDANV.cpp
  clang/lib/CodeGen/CGExprScalar.cpp
  clang/lib/Parse/ParseExpr.cpp
  clang/lib/Sema/SemaExceptionSpec.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaLambda.cpp
  clang/lib/Sema/SemaSYCL.cpp
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
  clang/lib/Sema/TreeTransform.h
  clang/lib/Serialization/ASTReaderStmt.cpp
  clang/lib/Serialization/ASTWriterStmt.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
  clang/test/AST/ast-print-sycl-unique-stable-name.cpp
  clang/test/CodeGenSYCL/unique_stable_name.cpp
  clang/test/ParserSYCL/unique_stable_name.cpp
  clang/test/ParserSYCL/unique_stable_name_sycl_only.cpp
  clang/test/SemaSYCL/unique_stable_name.cpp
  clang/tools/libclang/CXCursor.cpp

Index: clang/tools/libclang/CXCursor.cpp
===
--- clang/tools/libclang/CXCursor.cpp
+++ clang/tools/libclang/CXCursor.cpp
@@ -336,6 +336,7 @@
   case Stmt::ObjCBoxedExprClass:
   case Stmt::ObjCSubscriptRefExprClass:
   case Stmt::RecoveryExprClass:
+  case Stmt::SYCLUniqueStableNameExprClass:
 K = CXCursor_UnexposedExpr;
 break;
 
Index: clang/test/SemaSYCL/unique_stable_name.cpp
===
--- /dev/null
+++ clang/test/SemaSYCL/unique_stable_name.cpp
@@ -0,0 +1,215 @@
+// RUN: %clang_cc1 %s -std=c++17 -triple x86_64-pc-windows-msvc -fsycl-is-device -verify -fsyntax-only -Wno-unused
+// RUN: %clang_cc1 %s -std=c++17 -triple x86_64-linux-gnu -fsycl-is-device -verify -fsyntax-only -Wno-unused
+
+template 
+[[clang::sycl_kernel]] void kernel_single_task(KernelType kernelFunc) { // #kernelSingleTask
+  kernelFunc();
+}
+
+// kernel1 - expect error
+// The current function is named with a lambda (i.e., takes a lambda as a
+// template parameter. Call the builtin on the current function then it is
+// passed to a kernel. Test that passing the given function to the unique
+// stable name builtin and then to the kernel throws an error because the
+// latter causes its name mangling to change.
+template 
+void kernel1func(const Func &F1) {
+  constexpr const char *F1_output = __builtin_sycl_unique_stable_name(Func); // #USN_F1
+  // expected-error@#kernelSingleTask{{kernel instantiation changes the result of an evaluated '__builtin_sycl_unique_stable_name'}}
+  // expected-note@#kernel1func_call{{in instantiation of function template specialization}}
+  // expected-note@#USN_F1{{'__builtin_sycl_unique_stable_name' evaluated here}}
+  // expected-note@+1{{in instantiation of function template specialization}}
+  kernel_single_task(F1); // #kernel1_call
+}
+
+void callkernel1() {
+  kernel1func([]() {}); // #kernel1func_call
+}
+
+// kernel2 - expect error
+// The current function is named with a lambda (i.e., takes a lambda as a
+// template parameter). Call the builtin on the given function,
+// then an empty lambda is passed to kernel.
+// Test that passing the given function to the unique stable name builtin and
+// then passing a different lambda to the kernel still throws an error because
+// the calling context is part of naming the kernel. Even though the given
+// function (F2) is not passed to the kernel, its mangling changes due to
+// kernel call with the unrelated lambda.
+template 
+void kernel2func(const Func &F2) {
+  constexpr const char *F2_output = __builtin_sycl_unique_stable_name(Func); // #USN_F2
+  // expected-error@#kernelSingleTask{{kernel instantiation changes the result of an evaluated '__builtin_sycl_unique_stable_name'}}
+  // expected-note@#kernel2func_call{{in

[PATCH] D103245: [clang-format] Fix PointerAlignmentRight with AlignConsecutiveDeclarations

2021-05-27 Thread Gerhard Gappmeier via Phabricator via cfe-commits
gergap updated this revision to Diff 348257.
gergap added a comment.

arc diff again because previous diff didn't contain all changes


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103245

Files:
  clang/lib/Format/WhitespaceManager.cpp
  clang/unittests/Format/FormatTest.cpp

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -14881,6 +14881,7 @@
   FormatStyle Alignment = getLLVMStyle();
   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_None;
+  Alignment.PointerAlignment = FormatStyle::PAS_Right;
   verifyFormat("float const a = 5;\n"
"int oneTwoThree = 123;",
Alignment);
@@ -14916,8 +14917,8 @@
   verifyFormat("int  oneTwoThree{0}; // comment\n"
"unsigned oneTwo; // comment",
Alignment);
-  verifyFormat("unsigned int *  a;\n"
-   "int *   b;\n"
+  verifyFormat("unsigned int   *a;\n"
+   "int*b;\n"
"unsigned int Const *c;\n"
"unsigned int const *d;\n"
"unsigned int Const &e;\n"
@@ -15039,9 +15040,11 @@
"  doublebar();\n"
"};\n",
Alignment);
+
+  // PAS_RIGHT
   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
 "  int const i   = 1;\n"
-"  int * j   = 2;\n"
+"  int  *j   = 2;\n"
 "  int   big = 1;\n"
 "\n"
 "  unsigned oneTwoThree = 123;\n"
@@ -15062,6 +15065,140 @@
"int ll=1;\n"
"}",
Alignment));
+  EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
+"  int const i   = 1;\n"
+"  int **j   = 2, ***k;\n"
+"  int  &k   = i;\n"
+"  int &&l   = i + j;\n"
+"  int   big = 1;\n"
+"\n"
+"  unsigned oneTwoThree = 123;\n"
+"  int  oneTwo  = 12;\n"
+"  method();\n"
+"  float k  = 2;\n"
+"  int   ll = 1;\n"
+"}",
+format("void SomeFunction(int parameter= 0) {\n"
+   " int const  i= 1;\n"
+   "  int **j=2,***k;\n"
+   "int &k=i;\n"
+   "int &&l=i+j;\n"
+   " int big  =  1;\n"
+   "\n"
+   "unsigned oneTwoThree  =123;\n"
+   "int oneTwo = 12;\n"
+   "  method();\n"
+   "float k= 2;\n"
+   "int ll=1;\n"
+   "}",
+   Alignment));
+
+  // PAS_LEFT
+  FormatStyle AlignmentLeft = Alignment;
+  AlignmentLeft.PointerAlignment = FormatStyle::PAS_Left;
+  EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
+"  int const i   = 1;\n"
+"  int*  j   = 2;\n"
+"  int   big = 1;\n"
+"\n"
+"  unsigned oneTwoThree = 123;\n"
+"  int  oneTwo  = 12;\n"
+"  method();\n"
+"  float k  = 2;\n"
+"  int   ll = 1;\n"
+"}",
+format("void SomeFunction(int parameter= 0) {\n"
+   " int const  i= 1;\n"
+   "  int *j=2;\n"
+   " int big  =  1;\n"
+   "\n"
+   "unsigned oneTwoThree  =123;\n"
+   "int oneTwo = 12;\n"
+   "  method();\n"
+   "float k= 2;\n"
+   "int ll=1;\n"
+   "}",
+   AlignmentLeft));
+  EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
+"  int const i   = 1;\n"
+"  int** j   = 2;\n"
+"  int&  k   = i;\n"
+"  int&& l   = i + j;\n"
+"  int   big = 1;\n"
+"\n"
+"  unsigned oneTwoThree = 123;\n"
+"  int  oneTwo  = 12;\n"
+"  method();\n"
+"  float k  = 2;\n"
+"  int   ll = 1;\n"
+"}",
+format("void SomeFunction(int parameter= 0) {\n"
+   " int const  i= 1;\n"
+   "  int **j=2;\n"
+   "int &k=i;\n"
+   "int &&l=i+j;\n"
+   " int big  =  1;\n"
+   "\n"
+   "unsigned oneTwoThree  =123;\n"
+   "int oneTwo = 12;\n"
+   "  method();\n"
+   "float k= 2;\n"
+   "int ll=1;\n"
+   "}",
+   AlignmentLeft));
+  // PAS_MI

[clang] 023fbf3 - Correct the 'KEYALL' mask.

2021-05-27 Thread Erich Keane via cfe-commits

Author: Erich Keane
Date: 2021-05-27T07:20:32-07:00
New Revision: 023fbf3df32d4100b57597a4e748c94931c1b936

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

LOG: Correct the 'KEYALL' mask.

It should technically be a 1, since we are only setting the first bit.

Added: 


Modified: 
clang/lib/Basic/IdentifierTable.cpp

Removed: 




diff  --git a/clang/lib/Basic/IdentifierTable.cpp 
b/clang/lib/Basic/IdentifierTable.cpp
index dafacaf88502..d811aeec84a0 100644
--- a/clang/lib/Basic/IdentifierTable.cpp
+++ b/clang/lib/Basic/IdentifierTable.cpp
@@ -109,7 +109,7 @@ namespace {
 KEYMSCOMPAT   = 0x80,
 KEYSYCL   = 0x100,
 KEYALLCXX = KEYCXX | KEYCXX11 | KEYCXX20,
-KEYALL = (0xfff & ~KEYNOMS18 &
+KEYALL = (0x1ff & ~KEYNOMS18 &
   ~KEYNOOPENCL) // KEYNOMS18 and KEYNOOPENCL are used to exclude.
   };
 



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


[PATCH] D103241: [OpenCL] Add memory_scope_all_devices

2021-05-27 Thread Anton Zabaznov via Phabricator via cfe-commits
azabaznov added inline comments.



Comment at: clang/include/clang/Basic/OpenCLExtensions.def:113
 OPENCL_OPTIONALCOREFEATURE(__opencl_c_atomic_order_seq_cst, false, 300, 
OCL_C_30)
+OPENCL_OPTIONALCOREFEATURE(__opencl_c_atomic_scope_all_devices, false, 300, 
OCL_C_30)
 OPENCL_OPTIONALCOREFEATURE(__opencl_c_subgroups, false, 300, OCL_C_30)

Anastasia wrote:
> svenvh wrote:
> > Anastasia wrote:
> > > azabaznov wrote:
> > > > This feature is header only. We had a lot of discussions on that and 
> > > > the main idea was not to declare header only features/extensions in 
> > > > `OpenCLExtensions.def` and use 
> > > > `-D__opencl_c_atomic_scope_all_devices=1` instead, @Anastasia can 
> > > > comment on this.
> > > > 
> > > > I personally would like to introduce new flag for OpenCL options in 
> > > > `OpenCLExtensions.def` which will indicate that feature/extension is 
> > > > header-only, and thus all of such options can be declared in 
> > > > `OpenCLExtensions.def`: if flag is set to true it can be stripped out 
> > > > from the parser. What do you think about this?
> > > Yes, I agree the idea is to align with C/C++ directions for scalability 
> > > i.e. we should only add what is absolutely necessary to the compiler and 
> > > implement the rest using libraries - just like regular C and C++. We 
> > > won't be able to scale if we keep adding everything in the compiler. In 
> > > fact, we already have a huge scalability issue with our builtin 
> > > functions. If we look at modern C++ - more than 70% of features are not 
> > > in the compiler at all.
> > > 
> > > Would it be possible to do something like suggested here: 
> > > https://reviews.llvm.org/D91531#change-AKXhB4ko4nAO for 
> > > `cl_khr_depth_images`?
> > > 
> > > > I personally would like to introduce new flag for OpenCL options in 
> > > > OpenCLExtensions.def which will indicate that feature/extension is 
> > > > header-only, and thus all of such options can be declared in 
> > > > OpenCLExtensions.def: if flag is set to true it can be stripped out 
> > > > from the parser. What do you think about this?
> > > 
> > > Hmm, I think the macros should either be declared in the headers or using 
> > > a flag `-D`. I don't know why would adding them in `OpenCLExtensions.def` 
> > > be beneficial if we can use conventional approaches? This allows avoiding 
> > > the complexity and makes things more modular. If we look at the OpenCL 
> > > vendor extensions for example - we probably don't want them all in one 
> > > place?
> > > This feature is header only.
> > 
> > Good catch!  I have updated the patch to define the feature macro in the 
> > header instead.  Currently that definition is not optional, since we don't 
> > have finalized the solution for handling this yet (though the __undef 
> > proposal seems to be compatible with this change).
> > 
> > > I personally would like to introduce new flag for OpenCL options in 
> > > OpenCLExtensions.def which will indicate that feature/extension is 
> > > header-only
> > 
> > If we still need to add header-only features to OpenCLExtensions.def, then 
> > they aren't really header-only anymore I'd argue (as @Anastasia pointed out 
> > above).  So I'm not sure we need it either, or perhaps I missed something.
> FYI we have already added extended subgroups extension macros for SPIR in 
> `opencl-c-base.h` without the `__undef<...>` trick.
> 
> ```
> #if defined(__SPIR__)
> #define cl_khr_subgroup_extended_types 1
> #define cl_khr_subgroup_non_uniform_vote 1
> #define cl_khr_subgroup_ballot 1
> #define cl_khr_subgroup_non_uniform_arithmetic 1
> #define cl_khr_subgroup_shuffle 1
> #define cl_khr_subgroup_shuffle_relative 1
> #define cl_khr_subgroup_clustered_reduce 1
> #endif // defined(__SPIR__)
> ```
> 
> But extra conditions can be added any time if we get the agreement on the 
> route forward. 
> Hmm, I think the macros should either be declared in the headers or using a 
> flag -D. I don't know why would adding them in OpenCLExtensions.def be 
> beneficial if we can use conventional approaches? This allows avoiding the 
> complexity and makes things more modular. If we look at the OpenCL vendor 
> extensions for example - we probably don't want them all in one place?

Well, IMO separating extensions/features into two classes of options exactly 
brings new complexities :) I'm not sure why do we need to have a separate 
interface for them if there already exists unified one. For example, Intel 
compute-runtime uses `-cl-ext` flag to forward options : 
https://github.com/intel/compute-runtime/blob/master/opencl/source/platform/extensions.cpp#L156.
 

Can we use this header  mechanism  to define header-only features/extensions 
while `-cl-ext`interface is preserved?


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

https://reviews.llvm.org/D103241

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://list

[clang] 96ef4f4 - Hopefully fix the Clang sphinx doc build.

2021-05-27 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2021-05-27T10:27:01-04:00
New Revision: 96ef4f4a24918642f2133522c8c686bd5cf8dc63

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

LOG: Hopefully fix the Clang sphinx doc build.

This was broken several days ago in 826905787ae4c8540bb8a2384fac59c606c7eaff.

Added: 


Modified: 
clang/docs/OpenCLSupport.rst

Removed: 




diff  --git a/clang/docs/OpenCLSupport.rst b/clang/docs/OpenCLSupport.rst
index 2a6b9a0b73461..047c73f2834a5 100644
--- a/clang/docs/OpenCLSupport.rst
+++ b/clang/docs/OpenCLSupport.rst
@@ -2,12 +2,12 @@
 
   
 .none { background-color: #FF }
-.partial { background-color: #99 }
+.part { background-color: #99 }
 .good { background-color: #CCFF99 }
   
 
 .. role:: none
-.. role:: partial
+.. role:: part
 .. role:: good
 
 .. contents::
@@ -327,7 +327,7 @@ Limited support of experimental C++ libraries is described 
in the :ref:`experime
 
 Bugzilla bugs for this functionality are typically prefixed
 with '[C++4OpenCL]' - click `here
-`_
+`__
 to view the full bug list.
 
 
@@ -344,7 +344,7 @@ OpenCL C 3.0 Usage
 
 OpenCL C 3.0 language standard makes most OpenCL C 2.0 features optional. 
Optional
 functionality in OpenCL C 3.0 is indicated with the presence of feature-test 
macros
-(list of feature-test macros is `here 
`_).
+(list of feature-test macros is `here 
`__).
 Command-line flag :ref:`-cl-ext ` can be used to override 
features supported by a target.
 
 For cases when there is an associated extension for a specific feature (fp64 
and 3d image writes)



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


[PATCH] D102507: [HIP] Support in device code

2021-05-27 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added a comment.

In D102507#2760025 , @tra wrote:

> In effect this patch applies `__host__ __device__` to a subset of the 
> standard library headers and whatever headers *they* happen to include. While 
> it may happen to work, I'm not at all confident that it does not create 
> interesting issues.
>
> Considering that the patch only works with libc++ anyways, perhaps it's time 
> to make (parts) of libc++ itself usable from CUDA/HIP, instead of hacking 
> around it in the wrappers?
>
> @rsmith Richard, who would be the right person to discuss the standard 
> library changes we may need?

ping.

If we are allowed to make changes to libc++ we may have cleaner implementation 
for supporting libc++ in HIP device functions.

Currently by default libc++ functions are host functions except constexpr 
functions. Except constexpr functions, we can't call libc++ host functions in 
HIP device functions. Our goal is to make libc++ functions `__host__ 
__device__` functions so that they can be called in HIP device functions. We 
may not be able to support all libc++ functions, e.g. file I/O, threads, but at 
least we should be able to support some of them, e.g. type_traits, functional, 
containers. We do this by supporting the underlying functions e.g. malloc/free 
on device.

The change will be NFC for other languages.


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

https://reviews.llvm.org/D102507

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


[PATCH] D103252: [C++4OpenCL] Fix missing address space on implicit move assignment operator

2021-05-27 Thread Ole Strohm via Phabricator via cfe-commits
olestrohm created this revision.
olestrohm added reviewers: Anastasia, svenvh.
olestrohm added a project: clang.
Herald added subscribers: ldrumm, yaxunl.
olestrohm requested review of this revision.
Herald added a subscriber: cfe-commits.

This fixes the missing address space on `this` in the implicit move assignment 
operator.
The function called here is an abstraction around the lines that have been 
removed, and also sets the address space correctly.
This is copied from CopyConstructor, CopyAssignment and MoveConstructor, all of 
which use this new function, and now
MoveAssignment is has been aligned to use the same method.

I also added a new test file to check the output AST. If there's a better place 
for this test I will move it there.

Fixes: PR50259


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D103252

Files:
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/test/SemaOpenCLCXX/addrspace-assignment.clcpp


Index: clang/test/SemaOpenCLCXX/addrspace-assignment.clcpp
===
--- /dev/null
+++ clang/test/SemaOpenCLCXX/addrspace-assignment.clcpp
@@ -0,0 +1,16 @@
+// RUN: %clang_cc1 %s -ast-dump -pedantic -verify | FileCheck %s
+
+
+// CHECK: CXXConstructorDecl {{.*}} implicit {{.*}} Implicit 'void (const 
__generic Implicit &) __generic'
+// CHECK: CXXConstructorDecl {{.*}} implicit {{.*}} Implicit 'void (__generic 
Implicit &&) __generic'
+// CHECK: CXXMethodDecl {{.*}} implicit {{.*}} operator= '__generic Implicit 
&(const __generic Implicit &) __generic'
+// CHECK: CXXMethodDecl {{.*}} implicit {{.*}} operator= '__generic Implicit 
&(__generic Implicit &&) __generic'
+// expected-note@+2{{candidate function (the implicit copy assignment 
operator) not viable: no known conversion from 'int' to 'const __generic 
Implicit' for 1st argument}}
+// expected-note@+1{{candidate function (the implicit move assignment 
operator) not viable: no known conversion from 'int' to '__generic Implicit' 
for 1st argument}}
+struct Implicit {};
+
+void f() {
+Implicit i;
+i = 10; // expected-error{{no viable overloaded '='}}
+}
+
Index: clang/lib/Sema/SemaDeclCXX.cpp
===
--- clang/lib/Sema/SemaDeclCXX.cpp
+++ clang/lib/Sema/SemaDeclCXX.cpp
@@ -14299,10 +14299,7 @@
 /* Diagnose */ false);
   }
 
-  // Build an exception specification pointing back at this member.
-  FunctionProtoType::ExtProtoInfo EPI =
-  getImplicitMethodEPI(*this, MoveAssignment);
-  MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
+  setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);
 
   // Add the parameter to the operator.
   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,


Index: clang/test/SemaOpenCLCXX/addrspace-assignment.clcpp
===
--- /dev/null
+++ clang/test/SemaOpenCLCXX/addrspace-assignment.clcpp
@@ -0,0 +1,16 @@
+// RUN: %clang_cc1 %s -ast-dump -pedantic -verify | FileCheck %s
+
+
+// CHECK: CXXConstructorDecl {{.*}} implicit {{.*}} Implicit 'void (const __generic Implicit &) __generic'
+// CHECK: CXXConstructorDecl {{.*}} implicit {{.*}} Implicit 'void (__generic Implicit &&) __generic'
+// CHECK: CXXMethodDecl {{.*}} implicit {{.*}} operator= '__generic Implicit &(const __generic Implicit &) __generic'
+// CHECK: CXXMethodDecl {{.*}} implicit {{.*}} operator= '__generic Implicit &(__generic Implicit &&) __generic'
+// expected-note@+2{{candidate function (the implicit copy assignment operator) not viable: no known conversion from 'int' to 'const __generic Implicit' for 1st argument}}
+// expected-note@+1{{candidate function (the implicit move assignment operator) not viable: no known conversion from 'int' to '__generic Implicit' for 1st argument}}
+struct Implicit {};
+
+void f() {
+Implicit i;
+i = 10; // expected-error{{no viable overloaded '='}}
+}
+
Index: clang/lib/Sema/SemaDeclCXX.cpp
===
--- clang/lib/Sema/SemaDeclCXX.cpp
+++ clang/lib/Sema/SemaDeclCXX.cpp
@@ -14299,10 +14299,7 @@
 /* Diagnose */ false);
   }
 
-  // Build an exception specification pointing back at this member.
-  FunctionProtoType::ExtProtoInfo EPI =
-  getImplicitMethodEPI(*this, MoveAssignment);
-  MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
+  setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);
 
   // Add the parameter to the operator.
   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 767d34e - Disable misc-no-recursion checking in Clang

2021-05-27 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2021-05-27T10:39:04-04:00
New Revision: 767d34e3bdddef6c1871006dd0a2d06a4e1bcd5d

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

LOG: Disable misc-no-recursion checking in Clang

We currently enable misc-no-recursion, but Clang uses recursion
intentionally in a fair number of places (like RecursiveASTVisitor).
Disabling this check reduces a noise in reviews that add new AST nodes,
like https://reviews.llvm.org/D103112#2780747 which has five CI
warnings that the author can do nothing about.

Added: 


Modified: 
clang/.clang-tidy

Removed: 




diff  --git a/clang/.clang-tidy b/clang/.clang-tidy
index 5b425a712023..f517e9246cf8 100644
--- a/clang/.clang-tidy
+++ b/clang/.clang-tidy
@@ -1,4 +1,4 @@
-Checks: 
'-*,clang-diagnostic-*,llvm-*,misc-*,-misc-unused-parameters,-misc-non-private-member-variables-in-classes,-readability-identifier-naming'
+Checks: 
'-*,clang-diagnostic-*,llvm-*,misc-*,-misc-unused-parameters,-misc-non-private-member-variables-in-classes,-readability-identifier-naming,-misc-no-recursion'
 # Note that the readability-identifier-naming check is disabled, there are too
 # many violations in the codebase and they create too much noise in clang-tidy
 # results.



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


[PATCH] D103157: Disable misc-no-recursion checking in Clang

2021-05-27 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman closed this revision.
aaron.ballman added a comment.

Thanks! I've committed in 767d34e3bdddef6c1871006dd0a2d06a4e1bcd5d 
.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103157

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


[PATCH] D103142: [clang][clangd] Use reverse header map lookup in suggestPathToFileForDiagnostics

2021-05-27 Thread Dmitry Polukhin via Phabricator via cfe-commits
DmitryPolukhin updated this revision to Diff 348264.
DmitryPolukhin added a comment.

Fix forgotten comment


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103142

Files:
  clang/include/clang/Lex/HeaderMap.h
  clang/lib/Lex/HeaderMap.cpp
  clang/lib/Lex/HeaderSearch.cpp
  clang/unittests/Lex/HeaderSearchTest.cpp

Index: clang/unittests/Lex/HeaderSearchTest.cpp
===
--- clang/unittests/Lex/HeaderSearchTest.cpp
+++ clang/unittests/Lex/HeaderSearchTest.cpp
@@ -7,6 +7,7 @@
 //===--===//
 
 #include "clang/Lex/HeaderSearch.h"
+#include "HeaderMapTestUtils.h"
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/DiagnosticOptions.h"
 #include "clang/Basic/FileManager.h"
@@ -45,6 +46,21 @@
 Search.AddSearchPath(DL, /*isAngled=*/false);
   }
 
+  void addHeaderMap(llvm::StringRef Filename,
+std::unique_ptr Buf) {
+VFS->addFile(Filename, 0, std::move(Buf), /*User=*/None, /*Group=*/None,
+ llvm::sys::fs::file_type::regular_file);
+auto FE = FileMgr.getFile(Filename, true);
+assert(FE);
+
+// Test class supports only one HMap at a time.
+assert(!HMap);
+HMap = HeaderMap::Create(*FE, FileMgr);
+auto DL =
+DirectoryLookup(HMap.get(), SrcMgr::C_User, /*isFramework=*/false);
+Search.AddSearchPath(DL, /*isAngled=*/false);
+  }
+
   IntrusiveRefCntPtr VFS;
   FileSystemOptions FileMgrOpts;
   FileManager FileMgr;
@@ -55,6 +71,7 @@
   std::shared_ptr TargetOpts;
   IntrusiveRefCntPtr Target;
   HeaderSearch Search;
+  std::unique_ptr HMap;
 };
 
 TEST_F(HeaderSearchTest, NoSearchDir) {
@@ -136,5 +153,31 @@
 "y/z/t.h");
 }
 
+// Helper struct with null terminator character to make MemoryBuffer happy.
+template 
+struct NullTerminatedFile : public FileTy {
+  PaddingTy Padding = 0;
+};
+
+TEST_F(HeaderSearchTest, HeaderMapReverseLookup) {
+  typedef NullTerminatedFile, char> FileTy;
+  FileTy File;
+  File.init();
+
+  test::HMapFileMockMaker Maker(File);
+  auto a = Maker.addString("d.h");
+  auto b = Maker.addString("b/");
+  auto c = Maker.addString("c.h");
+  Maker.addBucket("d.h", a, b, c);
+
+  addHeaderMap("/x/y/z.hmap", File.getBuffer());
+  addSearchDir("/a");
+
+  EXPECT_EQ(Search.suggestPathToFileForDiagnostics("/a/b/c.h",
+   /*WorkingDir=*/"",
+   /*MainFile=*/""),
+"d.h");
+}
+
 } // namespace
 } // namespace clang
Index: clang/lib/Lex/HeaderSearch.cpp
===
--- clang/lib/Lex/HeaderSearch.cpp
+++ clang/lib/Lex/HeaderSearch.cpp
@@ -1834,7 +1834,7 @@
   };
 
   for (unsigned I = 0; I != SearchDirs.size(); ++I) {
-// FIXME: Support this search within frameworks and header maps.
+// FIXME: Support this search within frameworks.
 if (!SearchDirs[I].isNormalDir())
   continue;
 
@@ -1848,6 +1848,18 @@
   if (!BestPrefixLength && CheckDir(path::parent_path(MainFile)) && IsSystem)
 *IsSystem = false;
 
-
-  return path::convert_to_slash(File.drop_front(BestPrefixLength));
+  // Try resolving resulting filename via reverse search in header maps,
+  // key from header name is user prefered name for the include file.
+  StringRef Filename = File.drop_front(BestPrefixLength);
+  for (unsigned I = 0; I != SearchDirs.size(); ++I) {
+if (SearchDirs[I].isHeaderMap()) {
+  StringRef SpelledFilename =
+  SearchDirs[I].getHeaderMap()->reverseLookupFilename(Filename);
+  if (!SpelledFilename.empty()) {
+Filename = SpelledFilename;
+break;
+  }
+}
+  }
+  return path::convert_to_slash(Filename);
 }
Index: clang/lib/Lex/HeaderMap.cpp
===
--- clang/lib/Lex/HeaderMap.cpp
+++ clang/lib/Lex/HeaderMap.cpp
@@ -240,3 +240,26 @@
 return StringRef(DestPath.begin(), DestPath.size());
   }
 }
+
+StringRef HeaderMapImpl::reverseLookupFilename(StringRef DestPath) const {
+  if (ReverseMap.empty()) {
+const HMapHeader &Hdr = getHeader();
+unsigned NumBuckets = getEndianAdjustedWord(Hdr.NumBuckets);
+for (unsigned i = 0; i != NumBuckets; ++i) {
+  HMapBucket B = getBucket(i);
+  if (B.Key == HMAP_EmptyBucketKey)
+continue;
+
+  Optional Key = getString(B.Key);
+  Optional Prefix = getString(B.Prefix);
+  Optional Suffix = getString(B.Suffix);
+  if (Key && Prefix && Suffix) {
+SmallVector Buf;
+Buf.append(Prefix->begin(), Prefix->end());
+Buf.append(Suffix->begin(), Suffix->end());
+ReverseMap[StringRef(Buf.begin(), Buf.size())] = *Key;
+  }
+}
+  }
+  return ReverseMap.lookup(DestPath);
+}
Index: clang/include/clang/Lex/HeaderMap.h
===

[PATCH] D102839: [RISCV][Clang] Add -mno-div option to disable hardware int division

2021-05-27 Thread Alex Bradbury via Phabricator via cfe-commits
asb added a comment.

In D102839#2784585 , @kito-cheng 
wrote:

> Personally I prefer to deprecate `-mno-div` soon, but based on the rule for 
> RISC-V GNU toolchain, it need to wait `Zmmul` extension frozen.
> My plan is deprecate the `-mno-div` and emit warning to tell user should use 
> `Zmmul` instead once it frozen.

Thanks for clarifying Kito. In that case, I think having clang support -mno-div 
in order to match the GNU toolchain makes sense, and we can later follow GCC in 
deprecating it if they do. Given how long it can take to ratify extensions, I'm 
wary of making assumptions about when zmmul may be ratified.


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

https://reviews.llvm.org/D102839

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


[clang] 85f5272 - [OpenCL][NFC] Fix typos in test

2021-05-27 Thread Sven van Haastregt via cfe-commits

Author: Sven van Haastregt
Date: 2021-05-27T16:06:33+01:00
New Revision: 85f5272ffc58d73089bf77f0451b37176aa6b64f

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

LOG: [OpenCL][NFC] Fix typos in test

Added: 


Modified: 
clang/test/Headers/opencl-c-header.cl

Removed: 




diff  --git a/clang/test/Headers/opencl-c-header.cl 
b/clang/test/Headers/opencl-c-header.cl
index f97a089e744a4..2ab5c5af1facb 100644
--- a/clang/test/Headers/opencl-c-header.cl
+++ b/clang/test/Headers/opencl-c-header.cl
@@ -190,46 +190,46 @@ global atomic_int z = ATOMIC_VAR_INIT(99);
 #elif (__OPENCL_C_VERSION__ < 200)
 
 #ifdef  __opencl_c_pipes
-#error "Incorret feature macro __opencl_c_pipes define"
+#error "Incorrect feature macro __opencl_c_pipes define"
 #endif
 #ifdef __opencl_c_generic_address_space
-#error "Incorret feature macro __opencl_c_generic_address_space define"
+#error "Incorrect feature macro __opencl_c_generic_address_space define"
 #endif
 #ifdef __opencl_c_work_group_collective_functions
-#error "Incorret feature macro __opencl_c_work_group_collective_functions 
define"
+#error "Incorrect feature macro __opencl_c_work_group_collective_functions 
define"
 #endif
 #ifdef __opencl_c_atomic_order_acq_rel
-#error "Incorret feature macro __opencl_c_atomic_order_acq_rel define"
+#error "Incorrect feature macro __opencl_c_atomic_order_acq_rel define"
 #endif
 #ifdef __opencl_c_atomic_order_seq_cst
-#error "Incorret feature macro __opencl_c_atomic_order_seq_cst define"
+#error "Incorrect feature macro __opencl_c_atomic_order_seq_cst define"
 #endif
 #ifdef __opencl_c_atomic_scope_device
-#error "Incorret feature macro __opencl_c_atomic_scope_device define"
+#error "Incorrect feature macro __opencl_c_atomic_scope_device define"
 #endif
 #ifdef __opencl_c_atomic_scope_all_devices
-#error "Incorret feature macro __opencl_c_atomic_scope_all_devices define"
+#error "Incorrect feature macro __opencl_c_atomic_scope_all_devices define"
 #endif
 #ifdef __opencl_c_device_enqueue
-#error "Incorret feature macro __opencl_c_device_enqueue define"
+#error "Incorrect feature macro __opencl_c_device_enqueue define"
 #endif
 #ifdef __opencl_c_read_write_images
-#error "Incorret feature macro __opencl_c_read_write_images define"
+#error "Incorrect feature macro __opencl_c_read_write_images define"
 #endif
 #ifdef __opencl_c_program_scope_global_variables
-#error "Incorret feature macro __opencl_c_program_scope_global_variables 
define"
+#error "Incorrect feature macro __opencl_c_program_scope_global_variables 
define"
 #endif
 #ifdef __opencl_c_images
-#error "Incorret feature macro __opencl_c_images define"
+#error "Incorrect feature macro __opencl_c_images define"
 #endif
 #ifdef __opencl_c_3d_image_writes
-#error "Incorret feature macro __opencl_c_3d_image_writes define"
+#error "Incorrect feature macro __opencl_c_3d_image_writes define"
 #endif
 #ifdef __opencl_c_fp64
-#error "Incorret feature macro __opencl_c_fp64 define"
+#error "Incorrect feature macro __opencl_c_fp64 define"
 #endif
 #ifdef __opencl_c_subgroups
-#error "Incorret feature macro __opencl_c_subgroups define"
+#error "Incorrect feature macro __opencl_c_subgroups define"
 #endif
 
 #endif //(defined(__OPENCL_CPP_VERSION__) || __OPENCL_C_VERSION__ == 200)



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


[PATCH] D103159: [Clang] Enable __has_feature(coverage_sanitizer)

2021-05-27 Thread Marco Elver via Phabricator via cfe-commits
melver marked 3 inline comments as done.
melver added a comment.

Ping.

To reviewers: Do note the `feature` vs. `extension` discussion.
Summary: We think to be consistent with other sanitizers and avoid confusion, 
we must make this a `feature`, too.

Thanks.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103159

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


[PATCH] D103188: [clang-tidy] modernize-loop-convert: limit use of auto

2021-05-27 Thread Edward O via Phabricator via cfe-commits
eddy-geek added a subscriber: sammccall.
eddy-geek added a comment.

Builds ok, ready for review. I can't edit reviewers now, can someone help? 
@sammccall ?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103188

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


[PATCH] D102736: Fix tmp files being left on Windows builds.

2021-05-27 Thread Adrian McCarthy via Phabricator via cfe-commits
amccarth accepted this revision.
amccarth added a comment.
This revision is now accepted and ready to land.

LGTM.

Yeah, this is good.  My remaining comments are all speculations about how to 
improve this further in the future, but they aren't directly applicable to the 
goal here.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D102736

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


[PATCH] D97388: [analyzer] Replace StoreManager::evalIntegralCast with SValBuilder::evalCast

2021-05-27 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov updated this revision to Diff 348283.
ASDenysPetrov added a comment.
Herald added a subscriber: manas.

@vsavchenko 
Reworked the algorithm.

I hope this is the final version. Honestly, I also have the most optimized 
version but it has twice more similar(but different) code and `goto`s. I 
decided not to present it. Let it be less micro-optimized but much readable 
version.


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

https://reviews.llvm.org/D97388

Files:
  
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
@@ -41,6 +41,23 @@
 
 namespace {
 
+template  struct TestValues {
+  static constexpr T MIN = std::numeric_limits::min();
+  static constexpr T MAX = std::numeric_limits::max();
+  // MID is a value in the middle of the range
+  // 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));
+  static constexpr T A = MID - (MAX - MID) / 3 * 2;
+  static constexpr T B = MID - (MAX - MID) / 3;
+  static constexpr T C = -B;
+  static constexpr T D = -A;
+
+  static_assert(MIN < A && A < B && B < MID && MID < C && C < D && D < MAX,
+"Values shall be in an ascending order");
+};
+
 template  class RangeSetTest : public testing::Test {
 public:
   // Init block
@@ -55,24 +72,11 @@
   using RawRange = std::pair;
   using RawRangeSet = std::initializer_list;
 
-  static constexpr BaseType getMin() {
-return std::numeric_limits::min();
-  }
-  static constexpr BaseType getMax() {
-return std::numeric_limits::max();
-  }
-  static constexpr BaseType getMid() {
-return isSigned() ? 0 : ~(fromInt(-1) / fromInt(2));
-  }
-
-  static constexpr bool isSigned() { return std::is_signed::value; }
-  static constexpr BaseType fromInt(int X) { return static_cast(X); }
-
-  static llvm::APSInt Base;
   const llvm::APSInt &from(BaseType X) {
-llvm::APSInt Dummy = Base;
-Dummy = X;
-return BVF.getValue(Dummy);
+static llvm::APSInt Base{sizeof(BaseType) * 8,
+ std::is_unsigned::value};
+Base = X;
+return BVF.getValue(Base);
   }
 
   Range from(const RawRange &Init) {
@@ -160,7 +164,7 @@
 
   void checkAdd(RawRangeSet RawLHS, RawRangeSet RawRHS,
 RawRangeSet RawExpected) {
-wrap(&Self::checkAddImpl, RawRHS, RawLHS, RawExpected);
+wrap(&Self::checkAddImpl, RawLHS, RawRHS, RawExpected);
   }
 
   void checkAdd(RawRangeSet RawLHS, BaseType RawRHS, RawRangeSet RawExpected) {
@@ -168,6 +172,29 @@
  RawExpected);
   }
 
+  template 
+  void checkUniteImpl(RangeSet LHS, RHSType RHS, RangeSet Expected) {
+RangeSet Result = F.unite(LHS, RHS);
+EXPECT_EQ(Result, Expected)
+<< "while uniting " << toString(LHS) << " and " << toString(RHS);
+  }
+
+  void checkUnite(RawRangeSet RawLHS, RawRange RawRHS,
+  RawRangeSet RawExpected) {
+wrap(&Self::checkUniteImpl, RawLHS, RawRHS, RawExpected);
+  }
+
+  void checkUnite(RawRangeSet RawLHS, RawRangeSet RawRHS,
+  RawRangeSet RawExpected) {
+wrap(&Self::checkUniteImpl, RawLHS, RawRHS, RawExpected);
+  }
+
+  void checkUnite(RawRangeSet RawLHS, BaseType RawRHS,
+  RawRangeSet RawExpected) {
+wrap(&Self::checkUniteImpl, RawLHS, RawRHS,
+ RawExpected);
+  }
+
   void checkDeleteImpl(const llvm::APSInt &Point, RangeSet From,
RangeSet Expected) {
 RangeSet Result = F.deletePoint(From, Point);
@@ -183,29 +210,19 @@
 
 } // namespace
 
-template 
-llvm::APSInt RangeSetTest::Base{sizeof(BaseType) * 8, !isSigned()};
-
 using IntTypes = ::testing::Types;
 TYPED_TEST_CASE(RangeSetTest, IntTypes);
 
 TYPED_TEST(RangeSetTest, RangeSetNegateTest) {
-  // Use next values of the range {MIN, A, B, MID, C, D, MAX}.
-
-  constexpr TypeParam MIN = TestFixture::getMin();
-  constexpr TypeParam MAX = TestFixture::getMax();
-  // MID is a value in the middle of the range
-  // which unary minus does not affect on,
-  // e.g. int8/int32(0), uint8(128), uint32(2147483648).
-  constexpr TypeParam MID = TestFixture::getMid();
-  constexpr TypeParam A = MID - TestFixture::fromInt(42 + 42);
-  constexpr TypeParam B = MID - TestFixture::fromInt(42);
-  constexpr TypeParam C = -B;
-  constexpr TypeParam D = -A;
-
-  static_assert(MIN < A && A < B && B < MID && MID < C && C < D && D < MAX,
-"Values shall be in an ascending order");
+  using TV = TestValues;
+  constexpr auto MIN = TV::MIN;
+  constexpr auto MAX = TV::MAX;
+  constexpr auto MID = TV::MID;
+  co

[PATCH] D99797: [analyzer] Implemented RangeSet::Factory::unite function to handle intersections and adjacency

2021-05-27 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov updated this revision to Diff 348284.
ASDenysPetrov added a comment.

@vsavchenko
Reworked the algorithm.

I hope this is the final version. Honestly, I also have the most optimized 
version but it has twice more similar(but different) code and gotos. I decided 
not to present it. Let it be less micro-optimized but much readable version.


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

https://reviews.llvm.org/D99797

Files:
  
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
@@ -41,6 +41,23 @@
 
 namespace {
 
+template  struct TestValues {
+  static constexpr T MIN = std::numeric_limits::min();
+  static constexpr T MAX = std::numeric_limits::max();
+  // MID is a value in the middle of the range
+  // 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));
+  static constexpr T A = MID - (MAX - MID) / 3 * 2;
+  static constexpr T B = MID - (MAX - MID) / 3;
+  static constexpr T C = -B;
+  static constexpr T D = -A;
+
+  static_assert(MIN < A && A < B && B < MID && MID < C && C < D && D < MAX,
+"Values shall be in an ascending order");
+};
+
 template  class RangeSetTest : public testing::Test {
 public:
   // Init block
@@ -55,24 +72,11 @@
   using RawRange = std::pair;
   using RawRangeSet = std::initializer_list;
 
-  static constexpr BaseType getMin() {
-return std::numeric_limits::min();
-  }
-  static constexpr BaseType getMax() {
-return std::numeric_limits::max();
-  }
-  static constexpr BaseType getMid() {
-return isSigned() ? 0 : ~(fromInt(-1) / fromInt(2));
-  }
-
-  static constexpr bool isSigned() { return std::is_signed::value; }
-  static constexpr BaseType fromInt(int X) { return static_cast(X); }
-
-  static llvm::APSInt Base;
   const llvm::APSInt &from(BaseType X) {
-llvm::APSInt Dummy = Base;
-Dummy = X;
-return BVF.getValue(Dummy);
+static llvm::APSInt Base{sizeof(BaseType) * 8,
+ std::is_unsigned::value};
+Base = X;
+return BVF.getValue(Base);
   }
 
   Range from(const RawRange &Init) {
@@ -160,7 +164,7 @@
 
   void checkAdd(RawRangeSet RawLHS, RawRangeSet RawRHS,
 RawRangeSet RawExpected) {
-wrap(&Self::checkAddImpl, RawRHS, RawLHS, RawExpected);
+wrap(&Self::checkAddImpl, RawLHS, RawRHS, RawExpected);
   }
 
   void checkAdd(RawRangeSet RawLHS, BaseType RawRHS, RawRangeSet RawExpected) {
@@ -168,6 +172,29 @@
  RawExpected);
   }
 
+  template 
+  void checkUniteImpl(RangeSet LHS, RHSType RHS, RangeSet Expected) {
+RangeSet Result = F.unite(LHS, RHS);
+EXPECT_EQ(Result, Expected)
+<< "while uniting " << toString(LHS) << " and " << toString(RHS);
+  }
+
+  void checkUnite(RawRangeSet RawLHS, RawRange RawRHS,
+  RawRangeSet RawExpected) {
+wrap(&Self::checkUniteImpl, RawLHS, RawRHS, RawExpected);
+  }
+
+  void checkUnite(RawRangeSet RawLHS, RawRangeSet RawRHS,
+  RawRangeSet RawExpected) {
+wrap(&Self::checkUniteImpl, RawLHS, RawRHS, RawExpected);
+  }
+
+  void checkUnite(RawRangeSet RawLHS, BaseType RawRHS,
+  RawRangeSet RawExpected) {
+wrap(&Self::checkUniteImpl, RawLHS, RawRHS,
+ RawExpected);
+  }
+
   void checkDeleteImpl(const llvm::APSInt &Point, RangeSet From,
RangeSet Expected) {
 RangeSet Result = F.deletePoint(From, Point);
@@ -183,29 +210,19 @@
 
 } // namespace
 
-template 
-llvm::APSInt RangeSetTest::Base{sizeof(BaseType) * 8, !isSigned()};
-
 using IntTypes = ::testing::Types;
 TYPED_TEST_CASE(RangeSetTest, IntTypes);
 
 TYPED_TEST(RangeSetTest, RangeSetNegateTest) {
-  // Use next values of the range {MIN, A, B, MID, C, D, MAX}.
-
-  constexpr TypeParam MIN = TestFixture::getMin();
-  constexpr TypeParam MAX = TestFixture::getMax();
-  // MID is a value in the middle of the range
-  // which unary minus does not affect on,
-  // e.g. int8/int32(0), uint8(128), uint32(2147483648).
-  constexpr TypeParam MID = TestFixture::getMid();
-  constexpr TypeParam A = MID - TestFixture::fromInt(42 + 42);
-  constexpr TypeParam B = MID - TestFixture::fromInt(42);
-  constexpr TypeParam C = -B;
-  constexpr TypeParam D = -A;
-
-  static_assert(MIN < A && A < B && B < MID && MID < C && C < D && D < MAX,
-"Values shall be in an ascending order");
+  using TV = TestValues;
+  constexpr auto MIN = TV::MIN;
+  constexpr auto MAX = TV::MAX;
+  constexpr auto MID = TV::MID;
+  constexpr auto A = TV::A;
+  constexpr a

[PATCH] D102026: Thread safety analysis: Allow exlusive/shared joins for managed and asserted capabilities

2021-05-27 Thread Aaron Puchert via Phabricator via cfe-commits
aaronpuchert added a comment.

In D102026#2780384 , @delesley wrote:

> Thanks for taking the time to discuss things with me.  :-)

Thank you as well!

> Wrt. to the TEST_LOCKED_FUNCTION, I agree that you can simulate the behavior 
> using Assert and Lock.  But that pattern is too general/powerful, because it 
> also allows you to write nonsensical and unsound code.  Philosophically, 
> static analysis is concerned with allowing things that are sound, but 
> preventing things that are not, so I would prefer to allow the valid case, 
> but warn on the nonsensical/unsound code. The goal is not to provide powerful 
> back doors so that you can squeeze anything past the checker -- doing so kind 
> of defeats the point.  :-)

You're right, it does allow nonsensical code. But in some sense it's just a 
combination of two backdoors that we already have:

- Without `-Wthread-safety-negative` you don't have to declare preconditions of 
the kind "mutex should not be locked". We're basically assuming that locking is 
fine by default, thereby risking double locks.
- The `assert_capability` attribute is also a bit of a backdoor. Instead of 
statically propagating through the code that a mutex is held, we can just get 
that fact "out of thin air".

> That being said, I'm not certainly no asking you to implement TEST_LOCKED 
> functionality in this particular patch, and I totally understand that it may 
> simply not be worth the effort.

It certainly is appealing, especially because in our code we don't really have 
`AssertHeld`-like functions, but only `isLocked`-like functions, so our 
assertions are typically of the form `assert(mu.isLocked())`. But I haven't 
made up my mind yet.

Either way I think this change is just a consistent extension of the current 
behavior.

> Wrt. to unlocking an Assert, I see no problem.  It makes perfect sense to 
> dynamically assert that a mutex is held, then do something, and then unlock 
> the mutex afterwards; after all, the caller asserted that it was held before 
> unlocking.  You shouldn't disallow that.

Let's discuss this when I put forward the change, I'll add you as reviewer as 
usual. I think I have good arguments why we shouldn't be allowing it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D102026

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


[PATCH] D97388: [analyzer] Replace StoreManager::evalIntegralCast with SValBuilder::evalCast

2021-05-27 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov updated this revision to Diff 348286.
ASDenysPetrov added a comment.

Mistakenly erased with another patch. Restored. But anyway this revision should 
be //abandoned //as irrelevant any more.


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

https://reviews.llvm.org/D97388

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

Index: clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
@@ -493,44 +493,6 @@
   return true;
 }
 
-// Handles casts of type CK_IntegralCast.
-// At the moment, this function will redirect to evalCast, except when the range
-// of the original value is known to be greater than the max of the target type.
-SVal SValBuilder::evalIntegralCast(ProgramStateRef state, SVal val,
-   QualType castTy, QualType originalTy) {
-  // No truncations if target type is big enough.
-  if (getContext().getTypeSize(castTy) >= getContext().getTypeSize(originalTy))
-return evalCast(state, val, castTy, originalTy);
-
-  SymbolRef se = val.getAsSymbol();
-  if (!se) // Let evalCast handle non symbolic expressions.
-return evalCast(state, val, castTy, originalTy);
-
-  // Find the maximum value of the target type.
-  APSIntType ToType(getContext().getTypeSize(castTy),
-castTy->isUnsignedIntegerType());
-  llvm::APSInt ToTypeMax = ToType.getMaxValue();
-  NonLoc ToTypeMaxVal =
-  makeIntVal(ToTypeMax.isUnsigned() ? ToTypeMax.getZExtValue()
-: ToTypeMax.getSExtValue(),
- castTy)
-  .castAs();
-  // Check the range of the symbol being casted against the maximum value of the
-  // target type.
-  NonLoc FromVal = val.castAs();
-  QualType CmpTy = getConditionType();
-  NonLoc CompVal =
-  evalBinOpNN(state, BO_LE, FromVal, ToTypeMaxVal, CmpTy).castAs();
-  ProgramStateRef IsNotTruncated, IsTruncated;
-  std::tie(IsNotTruncated, IsTruncated) = state->assume(CompVal);
-  if (!IsNotTruncated && IsTruncated) {
-// Symbol is truncated so we evaluate it as a cast.
-NonLoc CastVal = makeNonLoc(se, originalTy, castTy);
-return CastVal;
-  }
-  return evalCast(state, val, castTy, originalTy);
-}
-
 //===--===//
 // Cast methods.
 // `evalCast` is the main method
@@ -917,6 +879,37 @@
   return makeNonLoc(SE, BO_NE, BVF.getValue(0, SE->getType()), CastTy);
 }
   } else {
+// Symbol to integer.
+if (!OriginalTy.isNull() && CastTy->isIntegralOrEnumerationType()) {
+  // Symbolic integer to integer.
+  if (OriginalTy->isIntegralOrEnumerationType()) {
+// Truncation.
+if (getContext().getTypeSize(CastTy) <
+getContext().getTypeSize(OriginalTy)) {
+  // Find the maximum value of the target type.
+  llvm::APSInt ToTypeMax =
+  llvm::APSInt::getMaxValue(getContext().getTypeSize(CastTy),
+CastTy->isUnsignedIntegerType());
+  NonLoc ToTypeMaxVal =
+  makeIntVal(ToTypeMax.getExtValue(), CastTy).castAs();
+  // Check the range of the symbol being casted against the maximum
+  // value of the target type.
+  NonLoc FromVal = V.castAs();
+  QualType CmpTy = getConditionType();
+  NonLoc CompVal =
+  evalBinOpNN(State, BO_LE, FromVal, ToTypeMaxVal, CmpTy)
+  .castAs();
+  ProgramStateRef IsNotTruncated, IsTruncated;
+  std::tie(IsNotTruncated, IsTruncated) = State->assume(CompVal);
+  if (!IsNotTruncated && IsTruncated) {
+// Symbol is truncated so we evaluate it as a cast.
+NonLoc CastVal = makeNonLoc(SE, OriginalTy, CastTy);
+return CastVal;
+  }
+}
+  }
+}
+
 // Symbol to integer, float.
 QualType T = Context.getCanonicalType(SE->getType());
 // If types are the same or both are integers, ignore the cast.
Index: clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
===
--- clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
+++ clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
@@ -431,7 +431,7 @@
   case CK_IntegralCast: {
 // Delegate to SValBuilder to process.
 SVal V = state->getSVal(Ex, LCtx);
-V = svalBuilder.evalIntegralCast(state, V, T, ExTy);
+V = svalBuilder.evalCast(state, V, T, ExTy);
 state = state->BindExpr(CastE, LCtx, V);
 Bldr.generateNode(CastE, Pred, state);
 continue;
Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h
=

[PATCH] D103159: [Clang] Enable __has_feature(coverage_sanitizer)

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

In D103159#2784845 , @melver wrote:

> Ping.

FWIW, the usual practice is to ping after no activity on the review for about a 
week.

That said, LGTM!




Comment at: clang/include/clang/Basic/Features.def:52
 LangOpts.Sanitize.hasOneOf(SanitizerKind::Undefined))
+FEATURE(coverage_sanitizer, LangOpts.SanitizeCoverage)
 FEATURE(assume_nonnull, true)

ojeda wrote:
> melver wrote:
> > ojeda wrote:
> > > melver wrote:
> > > > aaron.ballman wrote:
> > > > > I think this is likely fine, but wanted to call it out explicitly in 
> > > > > case others had opinions.
> > > > > 
> > > > > `FEATURE` is supposed to be used for standard features and 
> > > > > `EXTENSION` used for Clang extensions. This is an extension, not a 
> > > > > standard feature, so it's wrong in that way. However, it's following 
> > > > > the same pattern as the other sanitizers which is consistent. I think 
> > > > > consistently wrong is better than inconsistently right for this case, 
> > > > > but I have no idea how others feel.
> > > > Yes, you are correct of course, and I was pondering the same thing.
> > > > 
> > > > In the end I'd like all sanitizers be queryable via `__has_feature()` 
> > > > and not have this be the odd one out requiring `__has_extension()` as 
> > > > that's also going to lead to confusion/errors on the user side. 
> > > Perhaps add both, deprecate `__has_feature()` for non-standard features 
> > > like these ones, and remove them after a couple releases? :)
> > > 
> > > Regardless of the way, //any// is better than a version check, so thanks!
> > I think realistically we have to pick one, and that's the one we keep for 
> > all eternity. :-)
> > 
> > Because if we deprecate/remove something, some codebases would require 
> > version checks, which is a non-starter again. Not every project is on top 
> > of what their compilers deprecates/removes. (And, unlike the Linux kernel, 
> > some codebases just never upgrade their compiler requirements, but still 
> > expect newer compilers to work.)
> > 
> > So if we want consistency with other sanitizers, it has to be 
> > `__has_feature()`.
> Agreed, any friction on updates is bad for users and will annoy someone 
> somewhere.
> 
> Having said that, any serious project migrating to a new toolchain needs to 
> revalidate regardless. And, after all, these are non-standard features. So in 
> practice I do not think it would matter too much if the deprecation notice is 
> long enough (several years).
> 
> But I may be saying something completely stupid, since I do not even know if 
> Clang promises forever-stability for options, like `rustc` does.
I agree with @melver that it'd be worse to deprecate the feature testing macro. 
Then you have to use compiler version checks to decide which way to spell the 
feature testing macro, which largely defeats the entire purpose of having 
feature testing macros in the first place. I think we're basically stuck with a 
policy that all the sanitizers can be tested as features rather than extensions.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103159

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


[clang] 3d64677 - Thread safety analysis: Factor out function for merging locks (NFC)

2021-05-27 Thread Aaron Puchert via cfe-commits

Author: Aaron Puchert
Date: 2021-05-27T17:44:48+02:00
New Revision: 3d64677c28072867ea6025a22805977386b767f8

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

LOG: Thread safety analysis: Factor out function for merging locks (NFC)

It's going to become a bit more complicated, so let's have it separate.

Reviewed By: aaron.ballman

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

Added: 


Modified: 
clang/lib/Analysis/ThreadSafety.cpp

Removed: 




diff  --git a/clang/lib/Analysis/ThreadSafety.cpp 
b/clang/lib/Analysis/ThreadSafety.cpp
index 83410ebc2cae3..c65e9f307f114 100644
--- a/clang/lib/Analysis/ThreadSafety.cpp
+++ b/clang/lib/Analysis/ThreadSafety.cpp
@@ -1050,6 +1050,8 @@ class ThreadSafetyAnalyzer {
   const CFGBlock* PredBlock,
   const CFGBlock *CurrBlock);
 
+  bool join(const FactEntry &a, const FactEntry &b);
+
   void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
 SourceLocation JoinLoc, LockErrorKind LEK1,
 LockErrorKind LEK2);
@@ -2186,6 +2188,21 @@ void BuildLockset::VisitDeclStmt(const DeclStmt *S) {
   }
 }
 
+/// Given two facts merging on a join point, decide whether to warn and which
+/// one to keep.
+///
+/// \return  false if we should keep \p A, true if we should keep \p B.
+bool ThreadSafetyAnalyzer::join(const FactEntry &A, const FactEntry &B) {
+  if (A.kind() != B.kind()) {
+Handler.handleExclusiveAndShared("mutex", B.toString(), B.loc(), A.loc());
+// Take the exclusive capability to reduce further warnings.
+return B.kind() == LK_Exclusive;
+  } else {
+// The non-asserted capability is the one we want to track.
+return A.asserted() && !B.asserted();
+  }
+}
+
 /// Compute the intersection of two locksets and issue warnings for any
 /// locks in the symmetric 
diff erence.
 ///
@@ -2213,20 +2230,8 @@ void ThreadSafetyAnalyzer::intersectAndWarn(FactSet 
&FSet1,
 
 FactSet::iterator Iter1 = FSet1.findLockIter(FactMan, LDat2);
 if (Iter1 != FSet1.end()) {
-  const FactEntry &LDat1 = FactMan[*Iter1];
-  if (LDat1.kind() != LDat2.kind()) {
-Handler.handleExclusiveAndShared("mutex", LDat2.toString(), 
LDat2.loc(),
- LDat1.loc());
-if (LEK1 == LEK_LockedSomePredecessors &&
-LDat1.kind() != LK_Exclusive) {
-  // Take the exclusive lock, which is the one in FSet2.
-  *Iter1 = Fact;
-}
-  } else if (LEK1 == LEK_LockedSomePredecessors && LDat1.asserted() &&
- !LDat2.asserted()) {
-// The non-asserted lock in FSet2 is the one we want to track.
+  if (join(FactMan[*Iter1], LDat2) && LEK1 == LEK_LockedSomePredecessors)
 *Iter1 = Fact;
-  }
 } else {
   LDat2.handleRemovalFromIntersection(FSet2, FactMan, JoinLoc, LEK1,
   Handler);



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


[clang] cf0b337 - Thread safety analysis: Allow exlusive/shared joins for managed and asserted capabilities

2021-05-27 Thread Aaron Puchert via cfe-commits

Author: Aaron Puchert
Date: 2021-05-27T17:46:04+02:00
New Revision: cf0b337c1b1f064c81fe40124ddba178572778d6

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

LOG: Thread safety analysis: Allow exlusive/shared joins for managed and 
asserted capabilities

Similar to how we allow managed and asserted locks to be held and not
held in joining branches, we also allow them to be held shared and
exclusive. The scoped lock should restore the original state at the end
of the scope in any event, and asserted locks need not be released.

We should probably only allow asserted locks to be subsumed by managed,
not by (directly) acquired locks, but that's for another change.

Reviewed By: delesley

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

Added: 


Modified: 
clang/lib/Analysis/ThreadSafety.cpp
clang/test/SemaCXX/warn-thread-safety-analysis.cpp

Removed: 




diff  --git a/clang/lib/Analysis/ThreadSafety.cpp 
b/clang/lib/Analysis/ThreadSafety.cpp
index c65e9f307f114..6727e1315b5f5 100644
--- a/clang/lib/Analysis/ThreadSafety.cpp
+++ b/clang/lib/Analysis/ThreadSafety.cpp
@@ -2194,9 +2194,16 @@ void BuildLockset::VisitDeclStmt(const DeclStmt *S) {
 /// \return  false if we should keep \p A, true if we should keep \p B.
 bool ThreadSafetyAnalyzer::join(const FactEntry &A, const FactEntry &B) {
   if (A.kind() != B.kind()) {
-Handler.handleExclusiveAndShared("mutex", B.toString(), B.loc(), A.loc());
-// Take the exclusive capability to reduce further warnings.
-return B.kind() == LK_Exclusive;
+// For managed capabilities, the destructor should unlock in the right mode
+// anyway. For asserted capabilities no unlocking is needed.
+if ((A.managed() || A.asserted()) && (B.managed() || B.asserted())) {
+  // The shared capability subsumes the exclusive capability.
+  return B.kind() == LK_Shared;
+} else {
+  Handler.handleExclusiveAndShared("mutex", B.toString(), B.loc(), 
A.loc());
+  // Take the exclusive capability to reduce further warnings.
+  return B.kind() == LK_Exclusive;
+}
   } else {
 // The non-asserted capability is the one we want to track.
 return A.asserted() && !B.asserted();

diff  --git a/clang/test/SemaCXX/warn-thread-safety-analysis.cpp 
b/clang/test/SemaCXX/warn-thread-safety-analysis.cpp
index 369952eb397a2..8e8bb6f45dde4 100644
--- a/clang/test/SemaCXX/warn-thread-safety-analysis.cpp
+++ b/clang/test/SemaCXX/warn-thread-safety-analysis.cpp
@@ -2773,6 +2773,67 @@ void unlockJoin() {
   x = 2; // expected-warning {{writing variable 'x' requires holding mutex 
'mu' exclusively}}
 }
 
+void exclusiveSharedJoin() {
+  RelockableMutexLock scope(&mu, DeferTraits{});
+  if (b)
+scope.Lock();
+  else
+scope.ReaderLock();
+  // No warning on join point because the lock will be released by the scope 
object anyway.
+  print(x);
+  x = 2; // expected-warning {{writing variable 'x' requires holding mutex 
'mu' exclusively}}
+}
+
+void sharedExclusiveJoin() {
+  RelockableMutexLock scope(&mu, DeferTraits{});
+  if (b)
+scope.ReaderLock();
+  else
+scope.Lock();
+  // No warning on join point because the lock will be released by the scope 
object anyway.
+  print(x);
+  x = 2; // expected-warning {{writing variable 'x' requires holding mutex 
'mu' exclusively}}
+}
+
+void assertJoin() {
+  RelockableMutexLock scope(&mu, DeferTraits{});
+  if (b)
+scope.Lock();
+  else
+mu.AssertHeld();
+  x = 2;
+}
+
+void assertSharedJoin() {
+  RelockableMutexLock scope(&mu, DeferTraits{});
+  if (b)
+scope.ReaderLock();
+  else
+mu.AssertReaderHeld();
+  print(x);
+  x = 2; // expected-warning {{writing variable 'x' requires holding mutex 
'mu' exclusively}}
+}
+
+void assertStrongerJoin() {
+  RelockableMutexLock scope(&mu, DeferTraits{});
+  if (b)
+scope.ReaderLock();
+  else
+mu.AssertHeld();
+  print(x);
+  x = 2; // expected-warning {{writing variable 'x' requires holding mutex 
'mu' exclusively}}
+}
+
+void assertWeakerJoin() {
+  RelockableMutexLock scope(&mu, DeferTraits{});
+  if (b)
+scope.Lock();
+  else
+mu.AssertReaderHeld();
+  print(x);
+  x = 2; // expected-warning {{writing variable 'x' requires holding mutex 
'mu' exclusively}}
+}
+
 void directUnlock() {
   RelockableExclusiveMutexLock scope(&mu);
   mu.Unlock();
@@ -4506,8 +4567,8 @@ class Foo {
 
   void test6() {
 mu_.AssertHeld();
-mu_.Unlock();
-  }  // should this be a warning?
+mu_.Unlock(); // should this be a warning?
+  }
 
   void test7() {
 if (c) {
@@ -4528,9 +4589,10 @@ class Foo {
 else {
   mu_.AssertHeld();
 }
+// FIXME: should warn, because it's unclear whether we need to release or 
not.
 int b = a;
 a = 0;
-mu_.Unlock();
+mu_.Unlock(); //

[PATCH] D97388: [analyzer] Replace StoreManager::evalIntegralCast with SValBuilder::evalCast

2021-05-27 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov abandoned this revision.
ASDenysPetrov added a comment.




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

https://reviews.llvm.org/D97388

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


[PATCH] D102025: Thread safety analysis: Factor out function for merging locks (NFC)

2021-05-27 Thread Aaron Puchert via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG3d64677c2807: Thread safety analysis: Factor out function 
for merging locks (NFC) (authored by aaronpuchert).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D102025

Files:
  clang/lib/Analysis/ThreadSafety.cpp


Index: clang/lib/Analysis/ThreadSafety.cpp
===
--- clang/lib/Analysis/ThreadSafety.cpp
+++ clang/lib/Analysis/ThreadSafety.cpp
@@ -1050,6 +1050,8 @@
   const CFGBlock* PredBlock,
   const CFGBlock *CurrBlock);
 
+  bool join(const FactEntry &a, const FactEntry &b);
+
   void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
 SourceLocation JoinLoc, LockErrorKind LEK1,
 LockErrorKind LEK2);
@@ -2186,6 +2188,21 @@
   }
 }
 
+/// Given two facts merging on a join point, decide whether to warn and which
+/// one to keep.
+///
+/// \return  false if we should keep \p A, true if we should keep \p B.
+bool ThreadSafetyAnalyzer::join(const FactEntry &A, const FactEntry &B) {
+  if (A.kind() != B.kind()) {
+Handler.handleExclusiveAndShared("mutex", B.toString(), B.loc(), A.loc());
+// Take the exclusive capability to reduce further warnings.
+return B.kind() == LK_Exclusive;
+  } else {
+// The non-asserted capability is the one we want to track.
+return A.asserted() && !B.asserted();
+  }
+}
+
 /// Compute the intersection of two locksets and issue warnings for any
 /// locks in the symmetric difference.
 ///
@@ -2213,20 +2230,8 @@
 
 FactSet::iterator Iter1 = FSet1.findLockIter(FactMan, LDat2);
 if (Iter1 != FSet1.end()) {
-  const FactEntry &LDat1 = FactMan[*Iter1];
-  if (LDat1.kind() != LDat2.kind()) {
-Handler.handleExclusiveAndShared("mutex", LDat2.toString(), 
LDat2.loc(),
- LDat1.loc());
-if (LEK1 == LEK_LockedSomePredecessors &&
-LDat1.kind() != LK_Exclusive) {
-  // Take the exclusive lock, which is the one in FSet2.
-  *Iter1 = Fact;
-}
-  } else if (LEK1 == LEK_LockedSomePredecessors && LDat1.asserted() &&
- !LDat2.asserted()) {
-// The non-asserted lock in FSet2 is the one we want to track.
+  if (join(FactMan[*Iter1], LDat2) && LEK1 == LEK_LockedSomePredecessors)
 *Iter1 = Fact;
-  }
 } else {
   LDat2.handleRemovalFromIntersection(FSet2, FactMan, JoinLoc, LEK1,
   Handler);


Index: clang/lib/Analysis/ThreadSafety.cpp
===
--- clang/lib/Analysis/ThreadSafety.cpp
+++ clang/lib/Analysis/ThreadSafety.cpp
@@ -1050,6 +1050,8 @@
   const CFGBlock* PredBlock,
   const CFGBlock *CurrBlock);
 
+  bool join(const FactEntry &a, const FactEntry &b);
+
   void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
 SourceLocation JoinLoc, LockErrorKind LEK1,
 LockErrorKind LEK2);
@@ -2186,6 +2188,21 @@
   }
 }
 
+/// Given two facts merging on a join point, decide whether to warn and which
+/// one to keep.
+///
+/// \return  false if we should keep \p A, true if we should keep \p B.
+bool ThreadSafetyAnalyzer::join(const FactEntry &A, const FactEntry &B) {
+  if (A.kind() != B.kind()) {
+Handler.handleExclusiveAndShared("mutex", B.toString(), B.loc(), A.loc());
+// Take the exclusive capability to reduce further warnings.
+return B.kind() == LK_Exclusive;
+  } else {
+// The non-asserted capability is the one we want to track.
+return A.asserted() && !B.asserted();
+  }
+}
+
 /// Compute the intersection of two locksets and issue warnings for any
 /// locks in the symmetric difference.
 ///
@@ -2213,20 +2230,8 @@
 
 FactSet::iterator Iter1 = FSet1.findLockIter(FactMan, LDat2);
 if (Iter1 != FSet1.end()) {
-  const FactEntry &LDat1 = FactMan[*Iter1];
-  if (LDat1.kind() != LDat2.kind()) {
-Handler.handleExclusiveAndShared("mutex", LDat2.toString(), LDat2.loc(),
- LDat1.loc());
-if (LEK1 == LEK_LockedSomePredecessors &&
-LDat1.kind() != LK_Exclusive) {
-  // Take the exclusive lock, which is the one in FSet2.
-  *Iter1 = Fact;
-}
-  } else if (LEK1 == LEK_LockedSomePredecessors && LDat1.asserted() &&
- !LDat2.asserted()) {
-// The non-asserted lock in FSet2 is the one we want to track.
+  if (join(FactMan[*Iter1], LDat2) && LEK1 == LEK_LockedSomePredecessors)
 *Iter1 = Fact;
-  }
 } else {
   LDat2.handleRemovalFromIntersection(FSet2, FactMan, JoinLoc, LEK1,
   Handler);

[PATCH] D102026: Thread safety analysis: Allow exlusive/shared joins for managed and asserted capabilities

2021-05-27 Thread Aaron Puchert via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
aaronpuchert marked 2 inline comments as done.
Closed by commit rGcf0b337c1b1f: Thread safety analysis: Allow exlusive/shared 
joins for managed and asserted… (authored by aaronpuchert).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D102026

Files:
  clang/lib/Analysis/ThreadSafety.cpp
  clang/test/SemaCXX/warn-thread-safety-analysis.cpp

Index: clang/test/SemaCXX/warn-thread-safety-analysis.cpp
===
--- clang/test/SemaCXX/warn-thread-safety-analysis.cpp
+++ clang/test/SemaCXX/warn-thread-safety-analysis.cpp
@@ -2773,6 +2773,67 @@
   x = 2; // expected-warning {{writing variable 'x' requires holding mutex 'mu' exclusively}}
 }
 
+void exclusiveSharedJoin() {
+  RelockableMutexLock scope(&mu, DeferTraits{});
+  if (b)
+scope.Lock();
+  else
+scope.ReaderLock();
+  // No warning on join point because the lock will be released by the scope object anyway.
+  print(x);
+  x = 2; // expected-warning {{writing variable 'x' requires holding mutex 'mu' exclusively}}
+}
+
+void sharedExclusiveJoin() {
+  RelockableMutexLock scope(&mu, DeferTraits{});
+  if (b)
+scope.ReaderLock();
+  else
+scope.Lock();
+  // No warning on join point because the lock will be released by the scope object anyway.
+  print(x);
+  x = 2; // expected-warning {{writing variable 'x' requires holding mutex 'mu' exclusively}}
+}
+
+void assertJoin() {
+  RelockableMutexLock scope(&mu, DeferTraits{});
+  if (b)
+scope.Lock();
+  else
+mu.AssertHeld();
+  x = 2;
+}
+
+void assertSharedJoin() {
+  RelockableMutexLock scope(&mu, DeferTraits{});
+  if (b)
+scope.ReaderLock();
+  else
+mu.AssertReaderHeld();
+  print(x);
+  x = 2; // expected-warning {{writing variable 'x' requires holding mutex 'mu' exclusively}}
+}
+
+void assertStrongerJoin() {
+  RelockableMutexLock scope(&mu, DeferTraits{});
+  if (b)
+scope.ReaderLock();
+  else
+mu.AssertHeld();
+  print(x);
+  x = 2; // expected-warning {{writing variable 'x' requires holding mutex 'mu' exclusively}}
+}
+
+void assertWeakerJoin() {
+  RelockableMutexLock scope(&mu, DeferTraits{});
+  if (b)
+scope.Lock();
+  else
+mu.AssertReaderHeld();
+  print(x);
+  x = 2; // expected-warning {{writing variable 'x' requires holding mutex 'mu' exclusively}}
+}
+
 void directUnlock() {
   RelockableExclusiveMutexLock scope(&mu);
   mu.Unlock();
@@ -4506,8 +4567,8 @@
 
   void test6() {
 mu_.AssertHeld();
-mu_.Unlock();
-  }  // should this be a warning?
+mu_.Unlock(); // should this be a warning?
+  }
 
   void test7() {
 if (c) {
@@ -4528,9 +4589,10 @@
 else {
   mu_.AssertHeld();
 }
+// FIXME: should warn, because it's unclear whether we need to release or not.
 int b = a;
 a = 0;
-mu_.Unlock();
+mu_.Unlock(); // should this be a warning?
   }
 
   void test9() {
@@ -4558,6 +4620,28 @@
 int b = a;
 a = 0;
   }
+
+  void test12() {
+if (c)
+  mu_.ReaderLock(); // expected-warning {{mutex 'mu_' is acquired exclusively and shared in the same scope}}
+else
+  mu_.AssertHeld(); // expected-note {{the other acquisition of mutex 'mu_' is here}}
+// FIXME: should instead warn because it's unclear whether we need to release or not.
+int b = a;
+a = 0;
+mu_.Unlock();
+  }
+
+  void test13() {
+if (c)
+  mu_.Lock(); // expected-warning {{mutex 'mu_' is acquired exclusively and shared in the same scope}}
+else
+  mu_.AssertReaderHeld(); // expected-note {{the other acquisition of mutex 'mu_' is here}}
+// FIXME: should instead warn because it's unclear whether we need to release or not.
+int b = a;
+a = 0;
+mu_.Unlock();
+  }
 };
 
 }  // end namespace AssertHeldTest
Index: clang/lib/Analysis/ThreadSafety.cpp
===
--- clang/lib/Analysis/ThreadSafety.cpp
+++ clang/lib/Analysis/ThreadSafety.cpp
@@ -2194,9 +2194,16 @@
 /// \return  false if we should keep \p A, true if we should keep \p B.
 bool ThreadSafetyAnalyzer::join(const FactEntry &A, const FactEntry &B) {
   if (A.kind() != B.kind()) {
-Handler.handleExclusiveAndShared("mutex", B.toString(), B.loc(), A.loc());
-// Take the exclusive capability to reduce further warnings.
-return B.kind() == LK_Exclusive;
+// For managed capabilities, the destructor should unlock in the right mode
+// anyway. For asserted capabilities no unlocking is needed.
+if ((A.managed() || A.asserted()) && (B.managed() || B.asserted())) {
+  // The shared capability subsumes the exclusive capability.
+  return B.kind() == LK_Shared;
+} else {
+  Handler.handleExclusiveAndShared("mutex", B.toString(), B.loc(), A.loc());
+  // Take the exclusive c

[clang] 7922ff6 - [AIX] Add -lc++abi and -lunwind for linking

2021-05-27 Thread via cfe-commits

Author: jasonliu
Date: 2021-05-27T15:48:53Z
New Revision: 7922ff601094585c4b46b2640b7d07986f722c1b

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

LOG: [AIX] Add -lc++abi and -lunwind for linking

Summary:
We are going to have libc++abi.a and libunwind.a on AIX.
Add the necessary linking command to pick the libraries up.

Reviewed By: daltenty

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

Added: 


Modified: 
clang/lib/Driver/ToolChain.cpp
clang/lib/Driver/ToolChains/AIX.cpp
clang/lib/Driver/ToolChains/CommonArgs.cpp
clang/test/Driver/aix-ld.c

Removed: 




diff  --git a/clang/lib/Driver/ToolChain.cpp b/clang/lib/Driver/ToolChain.cpp
index 3342de85fc302..5791805a6711b 100644
--- a/clang/lib/Driver/ToolChain.cpp
+++ b/clang/lib/Driver/ToolChain.cpp
@@ -788,7 +788,7 @@ ToolChain::UnwindLibType ToolChain::GetUnwindLibType(
   else if (LibName == "platform" || LibName == "") {
 ToolChain::RuntimeLibType RtLibType = GetRuntimeLibType(Args);
 if (RtLibType == ToolChain::RLT_CompilerRT) {
-  if (getTriple().isAndroid())
+  if (getTriple().isAndroid() || getTriple().isOSAIX())
 unwindLibType = ToolChain::UNW_CompilerRT;
   else
 unwindLibType = ToolChain::UNW_None;

diff  --git a/clang/lib/Driver/ToolChains/AIX.cpp 
b/clang/lib/Driver/ToolChains/AIX.cpp
index 6cd12e16ec021..ca3fc5af76895 100644
--- a/clang/lib/Driver/ToolChains/AIX.cpp
+++ b/clang/lib/Driver/ToolChains/AIX.cpp
@@ -221,6 +221,7 @@ void AIX::AddCXXStdlibLibArgs(const llvm::opt::ArgList 
&Args,
   switch (GetCXXStdlibType(Args)) {
   case ToolChain::CST_Libcxx:
 CmdArgs.push_back("-lc++");
+CmdArgs.push_back("-lc++abi");
 return;
   case ToolChain::CST_Libstdcxx:
 llvm::report_fatal_error("linking libstdc++ unimplemented on AIX");

diff  --git a/clang/lib/Driver/ToolChains/CommonArgs.cpp 
b/clang/lib/Driver/ToolChains/CommonArgs.cpp
index b74a9fe3eb927..a1aab21c944ba 100644
--- a/clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ b/clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -1444,17 +1444,23 @@ static void AddUnwindLibrary(const ToolChain &TC, const 
Driver &D,
 break;
   }
   case ToolChain::UNW_CompilerRT:
-if (LGT == LibGccType::StaticLibGcc)
+if (TC.getTriple().isOSAIX()) {
+  // AIX only has libunwind as a shared library. So do not pass
+  // anything in if -static is specified.
+  if (LGT != LibGccType::StaticLibGcc)
+CmdArgs.push_back("-lunwind");
+} else if (LGT == LibGccType::StaticLibGcc) {
   CmdArgs.push_back("-l:libunwind.a");
-else if (TC.getTriple().isOSCygMing()) {
+} else if (TC.getTriple().isOSCygMing()) {
   if (LGT == LibGccType::SharedLibGcc)
 CmdArgs.push_back("-l:libunwind.dll.a");
   else
 // Let the linker choose between libunwind.dll.a and libunwind.a
 // depending on what's available, and depending on the -static flag
 CmdArgs.push_back("-lunwind");
-} else
+} else {
   CmdArgs.push_back("-l:libunwind.so");
+}
 break;
   }
 

diff  --git a/clang/test/Driver/aix-ld.c b/clang/test/Driver/aix-ld.c
index 467374b937207..62f152fd0eb69 100644
--- a/clang/test/Driver/aix-ld.c
+++ b/clang/test/Driver/aix-ld.c
@@ -18,7 +18,9 @@
 // CHECK-LD32: "[[SYSROOT]]/usr/lib{{/|}}crt0.o"
 // CHECK-LD32: "[[SYSROOT]]/usr/lib{{/|}}crti.o"
 // CHECK-LD32-NOT: "-lc++"
+// CHECK-LD32-NOT: "-lc++abi"
 // CHECK-LD32: 
"[[RESOURCE_DIR]]{{/|}}lib{{/|}}aix{{/|}}libclang_rt.builtins-powerpc.a"
+// CHECK-LD32: "-lunwind"
 // CHECK-LD32-NOT: "-lm"
 // CHECK-LD32: "-lc"
 
@@ -39,7 +41,9 @@
 // CHECK-LD64: "[[SYSROOT]]/usr/lib{{/|}}crt0_64.o"
 // CHECK-LD64: "[[SYSROOT]]/usr/lib{{/|}}crti_64.o"
 // CHECK-LD64-NOT: "-lc++"
+// CHECK-LD64-NOT: "-lc++abi"
 // CHECK-LD64: 
"[[RESOURCE_DIR]]{{/|}}lib{{/|}}aix{{/|}}libclang_rt.builtins-powerpc64.a"
+// CHECK-LD64: "-lunwind"
 // CHECK-LD64-NOT: "-lm"
 // CHECK-LD64: "-lc"
 
@@ -61,7 +65,9 @@
 // CHECK-LD32-PTHREAD: "[[SYSROOT]]/usr/lib{{/|}}crt0.o"
 // CHECK-LD32-PTHREAD: "[[SYSROOT]]/usr/lib{{/|}}crti.o"
 // CHECK-LD32-PTHREAD-NOT: "-lc++"
+// CHECK-LD32-PTHREAD-NOT: "-lc++abi"
 // CHECK-LD32-PTHREAD: 
"[[RESOURCE_DIR]]{{/|}}lib{{/|}}aix{{/|}}libclang_rt.builtins-powerpc.a"
+// CHECK-LD32-PTHREAD: "-lunwind"
 // CHECK-LD32-PTHREAD: "-lpthreads"
 // CHECK-LD32-PTHREAD-NOT: "-lm"
 // CHECK-LD32-PTHREAD: "-lc"
@@ -84,7 +90,9 @@
 // CHECK-LD64-PTHREAD: "[[SYSROOT]]/usr/lib{{/|}}crt0_64.o"
 // CHECK-LD64-PTHREAD: "[[SYSROOT]]/usr/lib{{/|}}crti_64.o"
 // CHECK-LD64-PTHREAD-NOT: "-lc++"
+// CHECK-LD64-PTHREAD-NOT: "-lc++abi"
 // CHECK-LD64-PTHREAD: 
"[[RESOURCE_DIR]]{{

[PATCH] D102813: [AIX] Add -lc++abi and -lunwind for linking

2021-05-27 Thread Jason Liu 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 rG7922ff601094: [AIX] Add -lc++abi and -lunwind for linking 
(authored by jasonliu).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D102813

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

Index: clang/test/Driver/aix-ld.c
===
--- clang/test/Driver/aix-ld.c
+++ clang/test/Driver/aix-ld.c
@@ -18,7 +18,9 @@
 // CHECK-LD32: "[[SYSROOT]]/usr/lib{{/|}}crt0.o"
 // CHECK-LD32: "[[SYSROOT]]/usr/lib{{/|}}crti.o"
 // CHECK-LD32-NOT: "-lc++"
+// CHECK-LD32-NOT: "-lc++abi"
 // CHECK-LD32: "[[RESOURCE_DIR]]{{/|}}lib{{/|}}aix{{/|}}libclang_rt.builtins-powerpc.a"
+// CHECK-LD32: "-lunwind"
 // CHECK-LD32-NOT: "-lm"
 // CHECK-LD32: "-lc"
 
@@ -39,7 +41,9 @@
 // CHECK-LD64: "[[SYSROOT]]/usr/lib{{/|}}crt0_64.o"
 // CHECK-LD64: "[[SYSROOT]]/usr/lib{{/|}}crti_64.o"
 // CHECK-LD64-NOT: "-lc++"
+// CHECK-LD64-NOT: "-lc++abi"
 // CHECK-LD64: "[[RESOURCE_DIR]]{{/|}}lib{{/|}}aix{{/|}}libclang_rt.builtins-powerpc64.a"
+// CHECK-LD64: "-lunwind"
 // CHECK-LD64-NOT: "-lm"
 // CHECK-LD64: "-lc"
 
@@ -61,7 +65,9 @@
 // CHECK-LD32-PTHREAD: "[[SYSROOT]]/usr/lib{{/|}}crt0.o"
 // CHECK-LD32-PTHREAD: "[[SYSROOT]]/usr/lib{{/|}}crti.o"
 // CHECK-LD32-PTHREAD-NOT: "-lc++"
+// CHECK-LD32-PTHREAD-NOT: "-lc++abi"
 // CHECK-LD32-PTHREAD: "[[RESOURCE_DIR]]{{/|}}lib{{/|}}aix{{/|}}libclang_rt.builtins-powerpc.a"
+// CHECK-LD32-PTHREAD: "-lunwind"
 // CHECK-LD32-PTHREAD: "-lpthreads"
 // CHECK-LD32-PTHREAD-NOT: "-lm"
 // CHECK-LD32-PTHREAD: "-lc"
@@ -84,7 +90,9 @@
 // CHECK-LD64-PTHREAD: "[[SYSROOT]]/usr/lib{{/|}}crt0_64.o"
 // CHECK-LD64-PTHREAD: "[[SYSROOT]]/usr/lib{{/|}}crti_64.o"
 // CHECK-LD64-PTHREAD-NOT: "-lc++"
+// CHECK-LD64-PTHREAD-NOT: "-lc++abi"
 // CHECK-LD64-PTHREAD: "[[RESOURCE_DIR]]{{/|}}lib{{/|}}aix{{/|}}libclang_rt.builtins-powerpc64.a"
+// CHECK-LD64-PTHREAD: "-lunwind"
 // CHECK-LD64-PTHREAD: "-lpthreads"
 // CHECK-LD64-PTHREAD-NOT: "-lm"
 // CHECK-LD64-PTHREAD: "-lc"
@@ -107,7 +115,9 @@
 // CHECK-LD32-PROF: "[[SYSROOT]]/usr/lib{{/|}}mcrt0.o"
 // CHECK-LD32-PROF: "[[SYSROOT]]/usr/lib{{/|}}crti.o"
 // CHECK-LD32-PROF-NOT: "-lc++"
+// CHECK-LD32-PROF-NOT: "-lc++abi"
 // CHECK-LD32-PROF: "[[RESOURCE_DIR]]{{/|}}lib{{/|}}aix{{/|}}libclang_rt.builtins-powerpc.a"
+// CHECK-LD32-PROF: "-lunwind"
 // CHECK-LD32-PROF-NOT: "-lm"
 // CHECK-LD32-PROF: "-lc"
 
@@ -129,7 +139,9 @@
 // CHECK-LD64-GPROF: "[[SYSROOT]]/usr/lib{{/|}}gcrt0_64.o"
 // CHECK-LD64-GPROF: "[[SYSROOT]]/usr/lib{{/|}}crti_64.o"
 // CHECK-LD64-GPROF-NOT: "-lc++"
+// CHECK-LD64-GPROF-NOT: "-lc++abi"
 // CHECK-LD64-GPROF: "[[RESOURCE_DIR]]{{/|}}lib{{/|}}aix{{/|}}libclang_rt.builtins-powerpc64.a"
+// CHECK-LD64-GPROF: "-lunwind"
 // CHECK-LD64-GPROF-NOT: "-lm"
 // CHECK-LD64-GPROF: "-lc"
 
@@ -151,7 +163,9 @@
 // CHECK-LD32-STATIC: "[[SYSROOT]]/usr/lib{{/|}}crt0.o"
 // CHECK-LD32-STATIC: "[[SYSROOT]]/usr/lib{{/|}}crti.o"
 // CHECK-LD32-STATIC-NOT: "-lc++"
+// CHECK-LD32-STATIC-NOT: "-lc++abi"
 // CHECK-LD32-STATIC: "[[RESOURCE_DIR]]{{/|}}lib{{/|}}aix{{/|}}libclang_rt.builtins-powerpc.a"
+// CHECK-LD32-STATIC-NOT: "-lunwind"
 // CHECK-LD32-STATIC-NOT: "-lm"
 // CHECK-LD32-STATIC: "-lc"
 
@@ -174,7 +188,9 @@
 // CHECK-LD32-LIBP: "[[SYSROOT]]/usr/lib{{/|}}crti.o"
 // CHECK-LD32-LIBP: "-L[[SYSROOT]]/powerpc-ibm-aix7.1.0.0"
 // CHECK-LD32-LIBP-NOT: "-lc++"
+// CHECK-LD32-LIBP-NOT: "-lc++abi"
 // CHECK-LD32-LIBP: "[[RESOURCE_DIR]]{{/|}}lib{{/|}}aix{{/|}}libclang_rt.builtins-powerpc.a"
+// CHECK-LD32-LIBP: "-lunwind"
 // CHECK-LD32-LIBP-NOT: "-lm"
 // CHECK-LD32-LIBP: "-lc"
 
@@ -197,7 +213,9 @@
 // CHECK-LD32-NO-STD-LIB-NOT: "[[SYSROOT]]/usr/lib{{/|}}crt0.o"
 // CHECK-LD32-NO-STD-LIB-NOT: "[[SYSROOT]]/usr/lib{{/|}}crti.o"
 // CHECK-LD32-NO-STD-LIB-NOT: "-lc++"
+// CHECK-LD32-NO-STD-LIB-NOT: "-lc++abi"
 // CHECK-LD32-NO-STD-LIB-NOT: "[[RESOURCE_DIR]]{{/|}}lib{{/|}}aix{{/|}}libclang_rt.builtins-powerpc.a"
+// CHECK-LD32-NO-STD-LIB-NOT: "-lunwind"
 // CHECK-LD32-NO-STD-LIB-NOT: "-lpthreads"
 // CHECK-LD32-NO-STD-LIB-NOT: "-lm"
 // CHECK-LD32-NO-STD-LIB-NOT: "-lc"
@@ -221,7 +239,9 @@
 // CHECK-LD64-NO-DEFAULT-LIBS: "[[SYSROOT]]/usr/lib{{/|}}crt0_64.o"
 // CHECK-LD64-NO-DEFAULT-LIBS: "[[SYSROOT]]/usr/lib{{/|}}crti_64.o"
 // CHECK-LD64-NO-DEFAULT-LIBS-NOT: "-lc++"
+// CHECK-LD64-N

[PATCH] D97340: [HIP] Support Spack packages

2021-05-27 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added a comment.

In D97340#2778073 , @haampie wrote:

> Hi Yaxunl,
>
>> The patch should not cause circular dependency on HIP or device library.
>
> I'm not saying this patch introduces a circular dependency, I'm saying you 
> are trying to solve an already existing circular dependency (clang needs 
> device libs at runtime, but device libs need llvm to compile).
>
> Let's talk about my PR here: https://github.com/spack/spack/pull/23859. It's 
> building rocm-device-libs as part of llvm-amdgpu by configuring llvm with 
> `-DLLVM_EXTERNAL_PROJECTS=device-libs`.
>
> If you checkout that pr, run `spack install hip@4.2.0`, what you get is get 
> is:
>
>   $ spack find -p llvm-amdgpu@4.2.0
>   llvm-amdgpu@4.2.0  
> /spack/opt/spack/linux-ubuntu20.04-zen2/gcc-10.2.0/llvm-amdgpu-4.2.0-a7jwajhh2cmn7p5djyx42lpcdfluk7wi
>
> And indeed the bitcode is there:
>
>   $ find 
> /spack/opt/spack/linux-ubuntu20.04-zen2/gcc-10.2.0/llvm-amdgpu-4.2.0-a7jwajhh2cmn7p5djyx42lpcdfluk7wi
>  -iname '*.bc'
>   
> /spack/opt/spack/linux-ubuntu20.04-zen2/gcc-10.2.0/llvm-amdgpu-4.2.0-a7jwajhh2cmn7p5djyx42lpcdfluk7wi/amdgcn/bitcode/oclc_isa_version_1033.bc
>   
> /spack/opt/spack/linux-ubuntu20.04-zen2/gcc-10.2.0/llvm-amdgpu-4.2.0-a7jwajhh2cmn7p5djyx42lpcdfluk7wi/amdgcn/bitcode/ocml.bc
>   
> /spack/opt/spack/linux-ubuntu20.04-zen2/gcc-10.2.0/llvm-amdgpu-4.2.0-a7jwajhh2cmn7p5djyx42lpcdfluk7wi/amdgcn/bitcode/hip.bc
>   ...
>
> Now when I used this `--print-rocm-search-dirs` flag on clang without other 
> flags, what I see is:
>
>   $ 
> /spack/opt/spack/linux-ubuntu20.04-zen2/gcc-10.2.0/llvm-amdgpu-4.2.0-a7jwajhh2cmn7p5djyx42lpcdfluk7wi/bin/clang++
>  --print-rocm-search-dirs -x hip hi.cc 
>   ROCm installation search path (Spack 4.2.0): 
> /spack/opt/spack/linux-ubuntu20.04-zen2/gcc-10.2.0
>   ROCm installation search path: 
> /spack/opt/spack/linux-ubuntu20.04-zen2/gcc-10.2.0/llvm-amdgpu-4.2.0-a7jwajhh2cmn7p5djyx42lpcdfluk7wi/lib/clang/12.0.0
>   ROCm installation search path: /opt/rocm
>   ...
>   clang-12: error: cannot find ROCm device library. Provide its path via 
> --rocm-path or --rocm-device-lib-path, or pass -nogpulib to build without 
> ROCm device library.
>
> Now can you make it such that clang will search the llvm prefix itself?

Yes I can make clang to search that path for device libs. I will open a review 
for that and remove the old detection of device libs for spack.

I still think auto detection of HIP path is a desirable feature, especially for 
interactive use of clang in a shell. This also allows clang to maintain certain 
level of backward compatibility with old HIP runtime by detecting HIP version.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D97340

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


[PATCH] D103229: [clang] NFC: split HeaderMapTest to have re-usable header map implementation for testing

2021-05-27 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith accepted this revision.
dexonsmith added a comment.
This revision is now accepted and ready to land.

LGTM; thanks for splitting this out.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103229

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


[PATCH] D99797: [analyzer] Implemented RangeSet::Factory::unite function to handle intersections and adjacency

2021-05-27 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov updated this revision to Diff 348294.
ASDenysPetrov added a comment.

Fixed the issue. Added more unit tests.


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

https://reviews.llvm.org/D99797

Files:
  
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
@@ -41,6 +41,23 @@
 
 namespace {
 
+template  struct TestValues {
+  static constexpr T MIN = std::numeric_limits::min();
+  static constexpr T MAX = std::numeric_limits::max();
+  // MID is a value in the middle of the range
+  // 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));
+  static constexpr T A = MID - (MAX - MID) / 3 * 2;
+  static constexpr T B = MID - (MAX - MID) / 3;
+  static constexpr T C = -B;
+  static constexpr T D = -A;
+
+  static_assert(MIN < A && A < B && B < MID && MID < C && C < D && D < MAX,
+"Values shall be in an ascending order");
+};
+
 template  class RangeSetTest : public testing::Test {
 public:
   // Init block
@@ -55,24 +72,11 @@
   using RawRange = std::pair;
   using RawRangeSet = std::initializer_list;
 
-  static constexpr BaseType getMin() {
-return std::numeric_limits::min();
-  }
-  static constexpr BaseType getMax() {
-return std::numeric_limits::max();
-  }
-  static constexpr BaseType getMid() {
-return isSigned() ? 0 : ~(fromInt(-1) / fromInt(2));
-  }
-
-  static constexpr bool isSigned() { return std::is_signed::value; }
-  static constexpr BaseType fromInt(int X) { return static_cast(X); }
-
-  static llvm::APSInt Base;
   const llvm::APSInt &from(BaseType X) {
-llvm::APSInt Dummy = Base;
-Dummy = X;
-return BVF.getValue(Dummy);
+static llvm::APSInt Base{sizeof(BaseType) * 8,
+ std::is_unsigned::value};
+Base = X;
+return BVF.getValue(Base);
   }
 
   Range from(const RawRange &Init) {
@@ -160,7 +164,7 @@
 
   void checkAdd(RawRangeSet RawLHS, RawRangeSet RawRHS,
 RawRangeSet RawExpected) {
-wrap(&Self::checkAddImpl, RawRHS, RawLHS, RawExpected);
+wrap(&Self::checkAddImpl, RawLHS, RawRHS, RawExpected);
   }
 
   void checkAdd(RawRangeSet RawLHS, BaseType RawRHS, RawRangeSet RawExpected) {
@@ -168,6 +172,29 @@
  RawExpected);
   }
 
+  template 
+  void checkUniteImpl(RangeSet LHS, RHSType RHS, RangeSet Expected) {
+RangeSet Result = F.unite(LHS, RHS);
+EXPECT_EQ(Result, Expected)
+<< "while uniting " << toString(LHS) << " and " << toString(RHS);
+  }
+
+  void checkUnite(RawRangeSet RawLHS, RawRange RawRHS,
+  RawRangeSet RawExpected) {
+wrap(&Self::checkUniteImpl, RawLHS, RawRHS, RawExpected);
+  }
+
+  void checkUnite(RawRangeSet RawLHS, RawRangeSet RawRHS,
+  RawRangeSet RawExpected) {
+wrap(&Self::checkUniteImpl, RawLHS, RawRHS, RawExpected);
+  }
+
+  void checkUnite(RawRangeSet RawLHS, BaseType RawRHS,
+  RawRangeSet RawExpected) {
+wrap(&Self::checkUniteImpl, RawLHS, RawRHS,
+ RawExpected);
+  }
+
   void checkDeleteImpl(const llvm::APSInt &Point, RangeSet From,
RangeSet Expected) {
 RangeSet Result = F.deletePoint(From, Point);
@@ -183,29 +210,19 @@
 
 } // namespace
 
-template 
-llvm::APSInt RangeSetTest::Base{sizeof(BaseType) * 8, !isSigned()};
-
 using IntTypes = ::testing::Types;
 TYPED_TEST_CASE(RangeSetTest, IntTypes);
 
 TYPED_TEST(RangeSetTest, RangeSetNegateTest) {
-  // Use next values of the range {MIN, A, B, MID, C, D, MAX}.
-
-  constexpr TypeParam MIN = TestFixture::getMin();
-  constexpr TypeParam MAX = TestFixture::getMax();
-  // MID is a value in the middle of the range
-  // which unary minus does not affect on,
-  // e.g. int8/int32(0), uint8(128), uint32(2147483648).
-  constexpr TypeParam MID = TestFixture::getMid();
-  constexpr TypeParam A = MID - TestFixture::fromInt(42 + 42);
-  constexpr TypeParam B = MID - TestFixture::fromInt(42);
-  constexpr TypeParam C = -B;
-  constexpr TypeParam D = -A;
-
-  static_assert(MIN < A && A < B && B < MID && MID < C && C < D && D < MAX,
-"Values shall be in an ascending order");
+  using TV = TestValues;
+  constexpr auto MIN = TV::MIN;
+  constexpr auto MAX = TV::MAX;
+  constexpr auto MID = TV::MID;
+  constexpr auto A = TV::A;
+  constexpr auto B = TV::B;
+  constexpr auto C = TV::C;
+  constexpr auto D = TV::D;
 
   this->checkNegate({{MIN, A}}, {{MIN, MIN}, {D, MAX}});
   this->checkNegate({{MIN, C}}, {{MIN, MIN}, {B, MAX}});
@@ -234,8 +251,9 @@
 }
 
 TYPED_TEST(Ra

[clang] 6d2c095 - [HIP] Check compatibility of -fgpu-sanitize with offload arch

2021-05-27 Thread Yaxun Liu via cfe-commits

Author: Yaxun (Sam) Liu
Date: 2021-05-27T12:06:42-04:00
New Revision: 6d2c0950205f50f926ba5e362e845faff22582b7

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

LOG: [HIP] Check compatibility of -fgpu-sanitize with offload arch

-fgpu-sanitize is incompatible with offload arch containing xnack-.

This patch checks that.

Reviewed by: Artem Belevich

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

Added: 


Modified: 
clang/lib/Driver/ToolChains/AMDGPU.cpp
clang/lib/Driver/ToolChains/AMDGPU.h
clang/lib/Driver/ToolChains/HIP.cpp
clang/lib/Driver/ToolChains/HIP.h
clang/test/Driver/hip-sanitize-options.hip

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/AMDGPU.cpp 
b/clang/lib/Driver/ToolChains/AMDGPU.cpp
index 639f3598a1d9..09ee3b2abfb7 100644
--- a/clang/lib/Driver/ToolChains/AMDGPU.cpp
+++ b/clang/lib/Driver/ToolChains/AMDGPU.cpp
@@ -707,16 +707,26 @@ AMDGPUToolChain::getGPUArch(const llvm::opt::ArgList 
&DriverArgs) const {
   getTriple(), DriverArgs.getLastArgValue(options::OPT_mcpu_EQ));
 }
 
-void AMDGPUToolChain::checkTargetID(
-const llvm::opt::ArgList &DriverArgs) const {
+AMDGPUToolChain::ParsedTargetIDType
+AMDGPUToolChain::getParsedTargetID(const llvm::opt::ArgList &DriverArgs) const 
{
   StringRef TargetID = DriverArgs.getLastArgValue(options::OPT_mcpu_EQ);
   if (TargetID.empty())
-return;
+return {None, None, None};
 
   llvm::StringMap FeatureMap;
   auto OptionalGpuArch = parseTargetID(getTriple(), TargetID, &FeatureMap);
-  if (!OptionalGpuArch) {
-getDriver().Diag(clang::diag::err_drv_bad_target_id) << TargetID;
+  if (!OptionalGpuArch)
+return {TargetID.str(), None, None};
+
+  return {TargetID.str(), OptionalGpuArch.getValue().str(), FeatureMap};
+}
+
+void AMDGPUToolChain::checkTargetID(
+const llvm::opt::ArgList &DriverArgs) const {
+  auto PTID = getParsedTargetID(DriverArgs);
+  if (PTID.OptionalTargetID && !PTID.OptionalGPUArch) {
+getDriver().Diag(clang::diag::err_drv_bad_target_id)
+<< PTID.OptionalTargetID.getValue();
   }
 }
 

diff  --git a/clang/lib/Driver/ToolChains/AMDGPU.h 
b/clang/lib/Driver/ToolChains/AMDGPU.h
index cb95db6e66bc..50ed3b3ded9a 100644
--- a/clang/lib/Driver/ToolChains/AMDGPU.h
+++ b/clang/lib/Driver/ToolChains/AMDGPU.h
@@ -107,7 +107,19 @@ class LLVM_LIBRARY_VISIBILITY AMDGPUToolChain : public 
Generic_ELF {
 
 protected:
   /// Check and diagnose invalid target ID specified by -mcpu.
-  void checkTargetID(const llvm::opt::ArgList &DriverArgs) const;
+  virtual void checkTargetID(const llvm::opt::ArgList &DriverArgs) const;
+
+  /// The struct type returned by getParsedTargetID.
+  struct ParsedTargetIDType {
+Optional OptionalTargetID;
+Optional OptionalGPUArch;
+Optional> OptionalFeatures;
+  };
+
+  /// Get target ID, GPU arch, and target ID features if the target ID is
+  /// specified and valid.
+  ParsedTargetIDType
+  getParsedTargetID(const llvm::opt::ArgList &DriverArgs) const;
 
   /// Get GPU arch from -mcpu without checking.
   StringRef getGPUArch(const llvm::opt::ArgList &DriverArgs) const;

diff  --git a/clang/lib/Driver/ToolChains/HIP.cpp 
b/clang/lib/Driver/ToolChains/HIP.cpp
index 80df2466a5da..28d4e5ddad10 100644
--- a/clang/lib/Driver/ToolChains/HIP.cpp
+++ b/clang/lib/Driver/ToolChains/HIP.cpp
@@ -459,3 +459,28 @@ HIPToolChain::getHIPDeviceLibs(const llvm::opt::ArgList 
&DriverArgs) const {
 
   return BCLibs;
 }
+
+void HIPToolChain::checkTargetID(const llvm::opt::ArgList &DriverArgs) const {
+  auto PTID = getParsedTargetID(DriverArgs);
+  if (PTID.OptionalTargetID && !PTID.OptionalGPUArch) {
+getDriver().Diag(clang::diag::err_drv_bad_target_id)
+<< PTID.OptionalTargetID.getValue();
+return;
+  }
+
+  assert(PTID.OptionalFeatures && "Invalid return from getParsedTargetID");
+  auto &FeatureMap = PTID.OptionalFeatures.getValue();
+  // Sanitizer is not supported with xnack-.
+  if (DriverArgs.hasFlag(options::OPT_fgpu_sanitize,
+ options::OPT_fno_gpu_sanitize, false)) {
+auto Loc = FeatureMap.find("xnack");
+if (Loc != FeatureMap.end() && !Loc->second) {
+  auto &Diags = getDriver().getDiags();
+  auto DiagID = Diags.getCustomDiagID(
+  DiagnosticsEngine::Error,
+  "'-fgpu-sanitize' is not compatible with offload arch '%0'. "
+  "Use an offload arch without 'xnack-' instead");
+  Diags.Report(DiagID) << PTID.OptionalTargetID.getValue();
+}
+  }
+}

diff  --git a/clang/lib/Driver/ToolChains/HIP.h 
b/clang/lib/Driver/ToolChains/HIP.h
index a9e1ed9a4656..3cced0a320dc 100644
--- a/clang/lib/Driver/ToolChains/HIP.h
+++ b/clang/lib/Driver/ToolChains/HIP.h
@@ -95,6 +95,7 @@ class LLVM_LIBRARY_VISIBILITY HIPToolChain final : public 
ROCMToolCha

[PATCH] D102975: [HIP] Check compatibility of -fgpu-sanitize with offload arch

2021-05-27 Thread Yaxun Liu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG6d2c0950205f: [HIP] Check compatibility of -fgpu-sanitize 
with offload arch (authored by yaxunl).
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D102975

Files:
  clang/lib/Driver/ToolChains/AMDGPU.cpp
  clang/lib/Driver/ToolChains/AMDGPU.h
  clang/lib/Driver/ToolChains/HIP.cpp
  clang/lib/Driver/ToolChains/HIP.h
  clang/test/Driver/hip-sanitize-options.hip

Index: clang/test/Driver/hip-sanitize-options.hip
===
--- clang/test/Driver/hip-sanitize-options.hip
+++ clang/test/Driver/hip-sanitize-options.hip
@@ -25,6 +25,11 @@
 // RUN:   -nogpuinc --rocm-path=%S/Inputs/rocm-invalid \
 // RUN:   %s 2>&1 | FileCheck -check-prefixes=FAIL %s
 
+// RUN: %clang -### -target x86_64-unknown-linux-gnu --offload-arch=gfx900:xnack- \
+// RUN:   -fsanitize=address -fgpu-sanitize \
+// RUN:   -nogpuinc --rocm-path=%S/Inputs/rocm \
+// RUN:   %s 2>&1 | FileCheck -check-prefix=XNACK %s
+
 // CHECK-NOT: {{"[^"]*clang[^"]*".* "-fcuda-is-device".* "-fsanitize=address"}}
 // CHECK-NOT: {{"[^"]*lld(\.exe){0,1}".* ".*hip.bc"}}
 // CHECK: {{"[^"]*clang[^"]*".* "-triple" "x86_64-unknown-linux-gnu".* "-fsanitize=address"}}
@@ -38,3 +43,5 @@
 // RDC: {{"[^"]*lld(\.exe){0,1}".*}} "[[OUT]]" {{".*asanrtl.bc" ".*hip.bc"}}
 
 // FAIL: AMDGPU address sanitizer runtime library (asanrtl) is not found. Please install ROCm device library which supports address sanitizer
+
+// XNACK: error: '-fgpu-sanitize' is not compatible with offload arch 'gfx900:xnack-'. Use an offload arch without 'xnack-' instead
Index: clang/lib/Driver/ToolChains/HIP.h
===
--- clang/lib/Driver/ToolChains/HIP.h
+++ clang/lib/Driver/ToolChains/HIP.h
@@ -95,6 +95,7 @@
   unsigned GetDefaultDwarfVersion() const override { return 4; }
 
   const ToolChain &HostTC;
+  void checkTargetID(const llvm::opt::ArgList &DriverArgs) const override;
 
 protected:
   Tool *buildLinker() const override;
Index: clang/lib/Driver/ToolChains/HIP.cpp
===
--- clang/lib/Driver/ToolChains/HIP.cpp
+++ clang/lib/Driver/ToolChains/HIP.cpp
@@ -459,3 +459,28 @@
 
   return BCLibs;
 }
+
+void HIPToolChain::checkTargetID(const llvm::opt::ArgList &DriverArgs) const {
+  auto PTID = getParsedTargetID(DriverArgs);
+  if (PTID.OptionalTargetID && !PTID.OptionalGPUArch) {
+getDriver().Diag(clang::diag::err_drv_bad_target_id)
+<< PTID.OptionalTargetID.getValue();
+return;
+  }
+
+  assert(PTID.OptionalFeatures && "Invalid return from getParsedTargetID");
+  auto &FeatureMap = PTID.OptionalFeatures.getValue();
+  // Sanitizer is not supported with xnack-.
+  if (DriverArgs.hasFlag(options::OPT_fgpu_sanitize,
+ options::OPT_fno_gpu_sanitize, false)) {
+auto Loc = FeatureMap.find("xnack");
+if (Loc != FeatureMap.end() && !Loc->second) {
+  auto &Diags = getDriver().getDiags();
+  auto DiagID = Diags.getCustomDiagID(
+  DiagnosticsEngine::Error,
+  "'-fgpu-sanitize' is not compatible with offload arch '%0'. "
+  "Use an offload arch without 'xnack-' instead");
+  Diags.Report(DiagID) << PTID.OptionalTargetID.getValue();
+}
+  }
+}
Index: clang/lib/Driver/ToolChains/AMDGPU.h
===
--- clang/lib/Driver/ToolChains/AMDGPU.h
+++ clang/lib/Driver/ToolChains/AMDGPU.h
@@ -107,7 +107,19 @@
 
 protected:
   /// Check and diagnose invalid target ID specified by -mcpu.
-  void checkTargetID(const llvm::opt::ArgList &DriverArgs) const;
+  virtual void checkTargetID(const llvm::opt::ArgList &DriverArgs) const;
+
+  /// The struct type returned by getParsedTargetID.
+  struct ParsedTargetIDType {
+Optional OptionalTargetID;
+Optional OptionalGPUArch;
+Optional> OptionalFeatures;
+  };
+
+  /// Get target ID, GPU arch, and target ID features if the target ID is
+  /// specified and valid.
+  ParsedTargetIDType
+  getParsedTargetID(const llvm::opt::ArgList &DriverArgs) const;
 
   /// Get GPU arch from -mcpu without checking.
   StringRef getGPUArch(const llvm::opt::ArgList &DriverArgs) const;
Index: clang/lib/Driver/ToolChains/AMDGPU.cpp
===
--- clang/lib/Driver/ToolChains/AMDGPU.cpp
+++ clang/lib/Driver/ToolChains/AMDGPU.cpp
@@ -707,16 +707,26 @@
   getTriple(), DriverArgs.getLastArgValue(options::OPT_mcpu_EQ));
 }
 
-void AMDGPUToolChain::checkTargetID(
-const llvm::opt::ArgList &DriverArgs) const {
+AMDGPUToolChain::ParsedTargetIDType
+AMDGPUToolChain::getParsedTargetID(const llvm::opt::ArgList &DriverArgs) const {
   StringRef TargetID = DriverArgs.getLastArgValue(options::OPT_mcpu_EQ);
   if (TargetID

[PATCH] D92639: [analyzer] Add control flow arrows to the analyzer's HTML reports

2021-05-27 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov added a comment.
Herald added a subscriber: manas.

@vsavchenko How about this?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92639

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


[clang] 5c18d11 - [SPE] Disable strict-fp for SPE by default

2021-05-27 Thread Qiu Chaofan via cfe-commits

Author: Qiu Chaofan
Date: 2021-05-28T00:14:35+08:00
New Revision: 5c18d1136665f74b15c0df599f56ac3e2e947fb8

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

LOG: [SPE] Disable strict-fp for SPE by default

As discussed in PR50385, strict-fp on PowerPC SPE has not been handled
well. This patch disables it by default for SPE.

Reviewed By: nemanjai, vit9696, jhibbits

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

Added: 


Modified: 
clang/lib/Basic/Targets/PPC.cpp
clang/test/CodeGen/builtins-ppc-fpconstrained.c

Removed: 




diff  --git a/clang/lib/Basic/Targets/PPC.cpp b/clang/lib/Basic/Targets/PPC.cpp
index cc16934292203..5de66aa19438e 100644
--- a/clang/lib/Basic/Targets/PPC.cpp
+++ b/clang/lib/Basic/Targets/PPC.cpp
@@ -59,6 +59,7 @@ bool 
PPCTargetInfo::handleTargetFeatures(std::vector &Features,
 } else if (Feature == "+prefix-instrs") {
   HasPrefixInstrs = true;
 } else if (Feature == "+spe" || Feature == "+efpu2") {
+  HasStrictFP = false;
   HasSPE = true;
   LongDoubleWidth = LongDoubleAlign = 64;
   LongDoubleFormat = &llvm::APFloat::IEEEdouble();

diff  --git a/clang/test/CodeGen/builtins-ppc-fpconstrained.c 
b/clang/test/CodeGen/builtins-ppc-fpconstrained.c
index 880c0c339ef33..909210996064c 100644
--- a/clang/test/CodeGen/builtins-ppc-fpconstrained.c
+++ b/clang/test/CodeGen/builtins-ppc-fpconstrained.c
@@ -11,6 +11,9 @@
 // RUN: -fallow-half-arguments-and-returns -S -ffp-exception-behavior=strict \
 // RUN: -o - %s | FileCheck --check-prefix=CHECK-ASM \
 // RUN: --check-prefix=FIXME-CHECK  %s
+// RUN: %clang_cc1 -triple powerpcspe -S -ffp-exception-behavior=strict \
+// RUN: -target-feature +spe -fexperimental-strict-floating-point -emit-llvm \
+// RUN: %s -o - | FileCheck --check-prefix=CHECK-CONSTRAINED %s
 
 typedef __attribute__((vector_size(4 * sizeof(float float vec_float;
 typedef __attribute__((vector_size(2 * sizeof(double double vec_double;



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


[PATCH] D103235: [SPE] Disable strict-fp for SPE by default

2021-05-27 Thread Qiu Chaofan 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 rG5c18d1136665: [SPE] Disable strict-fp for SPE by default 
(authored by qiucf).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103235

Files:
  clang/lib/Basic/Targets/PPC.cpp
  clang/test/CodeGen/builtins-ppc-fpconstrained.c


Index: clang/test/CodeGen/builtins-ppc-fpconstrained.c
===
--- clang/test/CodeGen/builtins-ppc-fpconstrained.c
+++ clang/test/CodeGen/builtins-ppc-fpconstrained.c
@@ -11,6 +11,9 @@
 // RUN: -fallow-half-arguments-and-returns -S -ffp-exception-behavior=strict \
 // RUN: -o - %s | FileCheck --check-prefix=CHECK-ASM \
 // RUN: --check-prefix=FIXME-CHECK  %s
+// RUN: %clang_cc1 -triple powerpcspe -S -ffp-exception-behavior=strict \
+// RUN: -target-feature +spe -fexperimental-strict-floating-point -emit-llvm \
+// RUN: %s -o - | FileCheck --check-prefix=CHECK-CONSTRAINED %s
 
 typedef __attribute__((vector_size(4 * sizeof(float float vec_float;
 typedef __attribute__((vector_size(2 * sizeof(double double vec_double;
Index: clang/lib/Basic/Targets/PPC.cpp
===
--- clang/lib/Basic/Targets/PPC.cpp
+++ clang/lib/Basic/Targets/PPC.cpp
@@ -59,6 +59,7 @@
 } else if (Feature == "+prefix-instrs") {
   HasPrefixInstrs = true;
 } else if (Feature == "+spe" || Feature == "+efpu2") {
+  HasStrictFP = false;
   HasSPE = true;
   LongDoubleWidth = LongDoubleAlign = 64;
   LongDoubleFormat = &llvm::APFloat::IEEEdouble();


Index: clang/test/CodeGen/builtins-ppc-fpconstrained.c
===
--- clang/test/CodeGen/builtins-ppc-fpconstrained.c
+++ clang/test/CodeGen/builtins-ppc-fpconstrained.c
@@ -11,6 +11,9 @@
 // RUN: -fallow-half-arguments-and-returns -S -ffp-exception-behavior=strict \
 // RUN: -o - %s | FileCheck --check-prefix=CHECK-ASM \
 // RUN: --check-prefix=FIXME-CHECK  %s
+// RUN: %clang_cc1 -triple powerpcspe -S -ffp-exception-behavior=strict \
+// RUN: -target-feature +spe -fexperimental-strict-floating-point -emit-llvm \
+// RUN: %s -o - | FileCheck --check-prefix=CHECK-CONSTRAINED %s
 
 typedef __attribute__((vector_size(4 * sizeof(float float vec_float;
 typedef __attribute__((vector_size(2 * sizeof(double double vec_double;
Index: clang/lib/Basic/Targets/PPC.cpp
===
--- clang/lib/Basic/Targets/PPC.cpp
+++ clang/lib/Basic/Targets/PPC.cpp
@@ -59,6 +59,7 @@
 } else if (Feature == "+prefix-instrs") {
   HasPrefixInstrs = true;
 } else if (Feature == "+spe" || Feature == "+efpu2") {
+  HasStrictFP = false;
   HasSPE = true;
   LongDoubleWidth = LongDoubleAlign = 64;
   LongDoubleFormat = &llvm::APFloat::IEEEdouble();
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D103159: [Clang] Enable __has_feature(coverage_sanitizer)

2021-05-27 Thread Marco Elver 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 rG4fbc66cd6d90: [Clang] Enable 
__has_feature(coverage_sanitizer) (authored by melver).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103159

Files:
  clang/docs/SanitizerCoverage.rst
  clang/include/clang/Basic/Features.def
  clang/include/clang/Basic/LangOptions.h
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/test/Lexer/has_feature_coverage_sanitizer.cpp


Index: clang/test/Lexer/has_feature_coverage_sanitizer.cpp
===
--- /dev/null
+++ clang/test/Lexer/has_feature_coverage_sanitizer.cpp
@@ -0,0 +1,15 @@
+// RUN: %clang -E -fsanitize-coverage=indirect-calls %s -o - | FileCheck 
--check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E -fsanitize-coverage=inline-8bit-counters %s -o - | FileCheck 
--check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E -fsanitize-coverage=trace-cmp %s -o - | FileCheck 
--check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E -fsanitize-coverage=trace-pc %s -o - | FileCheck 
--check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E -fsanitize-coverage=trace-pc-guard %s -o - | FileCheck 
--check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E  %s -o - | FileCheck --check-prefix=CHECK-NO-SANCOV %s
+
+#if __has_feature(coverage_sanitizer)
+int SancovEnabled();
+#else
+int SancovDisabled();
+#endif
+
+// CHECK-SANCOV: SancovEnabled
+// CHECK-NO-SANCOV: SancovDisabled
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -453,7 +453,7 @@
   CodeGenOpts.XRayAlwaysEmitTypedEvents = LangOpts.XRayAlwaysEmitTypedEvents;
   CodeGenOpts.DisableFree = FrontendOpts.DisableFree;
   FrontendOpts.GenerateGlobalModuleIndex = FrontendOpts.UseGlobalModuleIndex;
-
+  LangOpts.SanitizeCoverage = CodeGenOpts.hasSanitizeCoverage();
   LangOpts.ForceEmitVTables = CodeGenOpts.ForceEmitVTables;
   LangOpts.SpeculativeLoadHardening = CodeGenOpts.SpeculativeLoadHardening;
   LangOpts.CurrentModule = LangOpts.ModuleName;
Index: clang/include/clang/Basic/LangOptions.h
===
--- clang/include/clang/Basic/LangOptions.h
+++ clang/include/clang/Basic/LangOptions.h
@@ -280,6 +280,8 @@
 
   /// Set of enabled sanitizers.
   SanitizerSet Sanitize;
+  /// Is at least one coverage instrumentation type enabled.
+  bool SanitizeCoverage = false;
 
   /// Paths to files specifying which objects
   /// (files, functions, variables) should not be instrumented.
Index: clang/include/clang/Basic/Features.def
===
--- clang/include/clang/Basic/Features.def
+++ clang/include/clang/Basic/Features.def
@@ -49,6 +49,7 @@
 FEATURE(xray_instrument, LangOpts.XRayInstrument)
 FEATURE(undefined_behavior_sanitizer,
 LangOpts.Sanitize.hasOneOf(SanitizerKind::Undefined))
+FEATURE(coverage_sanitizer, LangOpts.SanitizeCoverage)
 FEATURE(assume_nonnull, true)
 FEATURE(attribute_analyzer_noreturn, true)
 FEATURE(attribute_availability, true)
Index: clang/docs/SanitizerCoverage.rst
===
--- clang/docs/SanitizerCoverage.rst
+++ clang/docs/SanitizerCoverage.rst
@@ -316,7 +316,9 @@
 ===
 
 It is possible to disable coverage instrumentation for select functions via the
-function attribute ``__attribute__((no_sanitize("coverage")))``.
+function attribute ``__attribute__((no_sanitize("coverage")))``. Because this
+attribute may not be supported by other compilers, it is recommended to use it
+together with ``__has_feature(coverage_sanitizer)``.
 
 Disabling instrumentation without source modification
 =


Index: clang/test/Lexer/has_feature_coverage_sanitizer.cpp
===
--- /dev/null
+++ clang/test/Lexer/has_feature_coverage_sanitizer.cpp
@@ -0,0 +1,15 @@
+// RUN: %clang -E -fsanitize-coverage=indirect-calls %s -o - | FileCheck --check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E -fsanitize-coverage=inline-8bit-counters %s -o - | FileCheck --check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E -fsanitize-coverage=trace-cmp %s -o - | FileCheck --check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E -fsanitize-coverage=trace-pc %s -o - | FileCheck --check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E -fsanitize-coverage=trace-pc-guard %s -o - | FileCheck --check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E  %s -o - | FileCheck --check-prefix=CHECK-NO-SANCOV %s
+
+#if __has_feature(coverage_sanitizer)
+int SancovEnabled();
+#else
+int SancovDisabled();
+#endif
+
+// CHECK-SANCO

[clang] 4fbc66c - [Clang] Enable __has_feature(coverage_sanitizer)

2021-05-27 Thread Marco Elver via cfe-commits

Author: Marco Elver
Date: 2021-05-27T18:24:21+02:00
New Revision: 4fbc66cd6d90d8d5169c43fcc1b1e26e8a98d3a9

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

LOG: [Clang] Enable __has_feature(coverage_sanitizer)

Like other sanitizers, enable __has_feature(coverage_sanitizer) if clang
has enabled at least one SanitizerCoverage instrumentation type.

Because coverage instrumentation selection is not handled via normal
-fsanitize= (and thus not in SanitizeSet), passing this information
through to LangOptions required propagating the already parsed
-fsanitize-coverage= options from CodeGenOptions through to LangOptions
in FixupInvocation().

Reviewed By: aaron.ballman

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

Added: 
clang/test/Lexer/has_feature_coverage_sanitizer.cpp

Modified: 
clang/docs/SanitizerCoverage.rst
clang/include/clang/Basic/Features.def
clang/include/clang/Basic/LangOptions.h
clang/lib/Frontend/CompilerInvocation.cpp

Removed: 




diff  --git a/clang/docs/SanitizerCoverage.rst 
b/clang/docs/SanitizerCoverage.rst
index b0bb9823eb043..ebd5d72127aaa 100644
--- a/clang/docs/SanitizerCoverage.rst
+++ b/clang/docs/SanitizerCoverage.rst
@@ -316,7 +316,9 @@ Disabling instrumentation with 
``__attribute__((no_sanitize("coverage")))``
 ===
 
 It is possible to disable coverage instrumentation for select functions via the
-function attribute ``__attribute__((no_sanitize("coverage")))``.
+function attribute ``__attribute__((no_sanitize("coverage")))``. Because this
+attribute may not be supported by other compilers, it is recommended to use it
+together with ``__has_feature(coverage_sanitizer)``.
 
 Disabling instrumentation without source modification
 =

diff  --git a/clang/include/clang/Basic/Features.def 
b/clang/include/clang/Basic/Features.def
index 4f7e2db7683d0..a7a5e06a937e0 100644
--- a/clang/include/clang/Basic/Features.def
+++ b/clang/include/clang/Basic/Features.def
@@ -49,6 +49,7 @@ FEATURE(memtag_sanitizer, 
LangOpts.Sanitize.has(SanitizerKind::MemTag))
 FEATURE(xray_instrument, LangOpts.XRayInstrument)
 FEATURE(undefined_behavior_sanitizer,
 LangOpts.Sanitize.hasOneOf(SanitizerKind::Undefined))
+FEATURE(coverage_sanitizer, LangOpts.SanitizeCoverage)
 FEATURE(assume_nonnull, true)
 FEATURE(attribute_analyzer_noreturn, true)
 FEATURE(attribute_availability, true)

diff  --git a/clang/include/clang/Basic/LangOptions.h 
b/clang/include/clang/Basic/LangOptions.h
index f5975d89a299e..d618daf3d23c2 100644
--- a/clang/include/clang/Basic/LangOptions.h
+++ b/clang/include/clang/Basic/LangOptions.h
@@ -280,6 +280,8 @@ class LangOptions : public LangOptionsBase {
 
   /// Set of enabled sanitizers.
   SanitizerSet Sanitize;
+  /// Is at least one coverage instrumentation type enabled.
+  bool SanitizeCoverage = false;
 
   /// Paths to files specifying which objects
   /// (files, functions, variables) should not be instrumented.

diff  --git a/clang/lib/Frontend/CompilerInvocation.cpp 
b/clang/lib/Frontend/CompilerInvocation.cpp
index 809492a36d3fa..28cd8391e32e2 100644
--- a/clang/lib/Frontend/CompilerInvocation.cpp
+++ b/clang/lib/Frontend/CompilerInvocation.cpp
@@ -453,7 +453,7 @@ static bool FixupInvocation(CompilerInvocation &Invocation,
   CodeGenOpts.XRayAlwaysEmitTypedEvents = LangOpts.XRayAlwaysEmitTypedEvents;
   CodeGenOpts.DisableFree = FrontendOpts.DisableFree;
   FrontendOpts.GenerateGlobalModuleIndex = FrontendOpts.UseGlobalModuleIndex;
-
+  LangOpts.SanitizeCoverage = CodeGenOpts.hasSanitizeCoverage();
   LangOpts.ForceEmitVTables = CodeGenOpts.ForceEmitVTables;
   LangOpts.SpeculativeLoadHardening = CodeGenOpts.SpeculativeLoadHardening;
   LangOpts.CurrentModule = LangOpts.ModuleName;

diff  --git a/clang/test/Lexer/has_feature_coverage_sanitizer.cpp 
b/clang/test/Lexer/has_feature_coverage_sanitizer.cpp
new file mode 100644
index 0..dfbe3973be043
--- /dev/null
+++ b/clang/test/Lexer/has_feature_coverage_sanitizer.cpp
@@ -0,0 +1,15 @@
+// RUN: %clang -E -fsanitize-coverage=indirect-calls %s -o - | FileCheck 
--check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E -fsanitize-coverage=inline-8bit-counters %s -o - | FileCheck 
--check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E -fsanitize-coverage=trace-cmp %s -o - | FileCheck 
--check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E -fsanitize-coverage=trace-pc %s -o - | FileCheck 
--check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E -fsanitize-coverage=trace-pc-guard %s -o - | FileCheck 
--check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E  %s -o - | FileCheck --check-prefix=CHECK-NO-SANCOV %s
+
+#if __has_feature(coverage_sanitizer)
+int SancovEnabled();
+#e

[PATCH] D103218: [Fuchsia][CMake] Add missing include path.

2021-05-27 Thread Mitch Phillips via Phabricator via cfe-commits
hctim added a comment.

Thanks for the keen eye on the Fuchsia bots, I didn't see this!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103218

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


[PATCH] D103241: [OpenCL] Add memory_scope_all_devices

2021-05-27 Thread Sven van Haastregt via Phabricator via cfe-commits
svenvh updated this revision to Diff 348309.
svenvh added a comment.

Restrict feature macro definition to SPIR target only.


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

https://reviews.llvm.org/D103241

Files:
  clang/lib/Headers/opencl-c-base.h
  clang/test/Headers/opencl-c-header.cl
  clang/test/SemaOpenCL/atomic-ops.cl


Index: clang/test/SemaOpenCL/atomic-ops.cl
===
--- clang/test/SemaOpenCL/atomic-ops.cl
+++ clang/test/SemaOpenCL/atomic-ops.cl
@@ -2,6 +2,7 @@
 // RUN:   -fsyntax-only -triple=spir64 -fdeclare-opencl-builtins 
-finclude-default-header
 // RUN: %clang_cc1 %s -cl-std=CL2.0 -verify -fsyntax-only \
 // RUN:   -triple=amdgcn-amd-amdhsa -fdeclare-opencl-builtins 
-finclude-default-header
+// TODO: add -cl-std=CL3.0 line when generic and psv are supported.
 
 // Basic parsing/Sema tests for __opencl_atomic_*
 
@@ -161,6 +162,11 @@
   (void)__opencl_atomic_load(Ap, memory_order_relaxed, 
memory_scope_work_group);
   (void)__opencl_atomic_load(Ap, memory_order_relaxed, memory_scope_device);
   (void)__opencl_atomic_load(Ap, memory_order_relaxed, 
memory_scope_all_svm_devices);
+  (void)__opencl_atomic_load(Ap, memory_order_relaxed, 
memory_scope_all_devices);
+#if __OPENCL_C_VERSION__ < CL_VERSION_3_0
+  // expected-error@-2{{use of undeclared identifier 
'memory_scope_all_devices'}}
+  // expected-note@* {{'memory_scope_all_svm_devices' declared here}}
+#endif
   (void)__opencl_atomic_load(Ap, memory_order_relaxed, memory_scope_sub_group);
   (void)__opencl_atomic_load(Ap, memory_order_relaxed, scope);
   (void)__opencl_atomic_load(Ap, memory_order_relaxed, 10);
//expected-error{{synchronization scope argument to atomic operation is 
invalid}}
Index: clang/test/Headers/opencl-c-header.cl
===
--- clang/test/Headers/opencl-c-header.cl
+++ clang/test/Headers/opencl-c-header.cl
@@ -151,7 +151,13 @@
 #endif //(defined(__OPENCL_CPP_VERSION__) || __OPENCL_C_VERSION__ >= 200)
 
 // OpenCL C features.
-#if (defined(__OPENCL_CPP_VERSION__) || __OPENCL_C_VERSION__ == 200)
+#if (__OPENCL_C_VERSION__ == 300)
+
+#if __opencl_c_atomic_scope_all_devices != 1
+#error "Incorrectly defined feature macro __opencl_c_atomic_scope_all_devices"
+#endif
+
+#elif (defined(__OPENCL_CPP_VERSION__) || __OPENCL_C_VERSION__ == 200)
 
 #ifndef  __opencl_c_pipes
 #error "Feature macro __opencl_c_pipes should be defined"
Index: clang/lib/Headers/opencl-c-base.h
===
--- clang/lib/Headers/opencl-c-base.h
+++ clang/lib/Headers/opencl-c-base.h
@@ -39,6 +39,14 @@
 #define __opencl_c_images 1
 #endif
 
+// Define header-only feature macros for OpenCL C 3.0.
+#if (__OPENCL_C_VERSION__ == 300)
+// For the SPIR target all features are supported.
+#if defined(__SPIR__)
+#define __opencl_c_atomic_scope_all_devices 1
+#endif // defined(__SPIR__)
+#endif // (__OPENCL_C_VERSION__ == 300)
+
 // built-in scalar data types:
 
 /**
@@ -312,7 +320,12 @@
   memory_scope_work_item = __OPENCL_MEMORY_SCOPE_WORK_ITEM,
   memory_scope_work_group = __OPENCL_MEMORY_SCOPE_WORK_GROUP,
   memory_scope_device = __OPENCL_MEMORY_SCOPE_DEVICE,
+#if defined(__opencl_c_atomic_scope_all_devices)
   memory_scope_all_svm_devices = __OPENCL_MEMORY_SCOPE_ALL_SVM_DEVICES,
+#if (__OPENCL_C_VERSION__ >= CL_VERSION_3_0)
+  memory_scope_all_devices = memory_scope_all_svm_devices,
+#endif // __OPENCL_C_VERSION__ >= CL_VERSION_3_0
+#endif // defined(__opencl_c_atomic_scope_all_devices)
 #if defined(cl_intel_subgroups) || defined(cl_khr_subgroups)
   memory_scope_sub_group = __OPENCL_MEMORY_SCOPE_SUB_GROUP
 #endif


Index: clang/test/SemaOpenCL/atomic-ops.cl
===
--- clang/test/SemaOpenCL/atomic-ops.cl
+++ clang/test/SemaOpenCL/atomic-ops.cl
@@ -2,6 +2,7 @@
 // RUN:   -fsyntax-only -triple=spir64 -fdeclare-opencl-builtins -finclude-default-header
 // RUN: %clang_cc1 %s -cl-std=CL2.0 -verify -fsyntax-only \
 // RUN:   -triple=amdgcn-amd-amdhsa -fdeclare-opencl-builtins -finclude-default-header
+// TODO: add -cl-std=CL3.0 line when generic and psv are supported.
 
 // Basic parsing/Sema tests for __opencl_atomic_*
 
@@ -161,6 +162,11 @@
   (void)__opencl_atomic_load(Ap, memory_order_relaxed, memory_scope_work_group);
   (void)__opencl_atomic_load(Ap, memory_order_relaxed, memory_scope_device);
   (void)__opencl_atomic_load(Ap, memory_order_relaxed, memory_scope_all_svm_devices);
+  (void)__opencl_atomic_load(Ap, memory_order_relaxed, memory_scope_all_devices);
+#if __OPENCL_C_VERSION__ < CL_VERSION_3_0
+  // expected-error@-2{{use of undeclared identifier 'memory_scope_all_devices'}}
+  // expected-note@* {{'memory_scope_all_svm_devices' declared here}}
+#endif
   (void)__opencl_atomic_load(Ap, memory_order_relaxed, memory_scope_sub_group);
   (void)__opencl_atomic_load(Ap, memory_order_relaxed, sco

  1   2   >