[PATCH] D75591: [OpenMP] Add firstprivate as a default data-sharing attribute to clang

2020-03-23 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

In D75591#1936116 , @jdoerfert wrote:

> Did you add the warning @lebedev.ri mentioned? (@lebedev.ri I assume/hope a 
> warning is sufficient here?)


It should be handled consistently with how other newer openmp features are 
handled with older openmp version specified.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D75591



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


[PATCH] D76590: [Analyzer] Model `empty()` member function of containers

2020-03-23 Thread Balogh, Ádám via Phabricator via cfe-commits
baloghadamsoftware created this revision.
baloghadamsoftware added reviewers: NoQ, Szelethus.
baloghadamsoftware added a project: clang.
Herald added subscribers: ASDenysPetrov, martong, steakhal, Charusso, 
gamesh411, dkrupp, donat.nagy, mikhail.ramalho, a.sidorin, rnkovacs, szepet, 
xazax.hun, whisperity.
baloghadamsoftware added a comment.
baloghadamsoftware marked 3 inline comments as done.

Supersedes D62688 .




Comment at: clang/lib/StaticAnalyzer/Checkers/IteratorModeling.cpp:359
 State = State->BindExpr(CE, LCtx, RetVal);
   }
 

Maybe I should move these lines into a separate function in the library to 
avoid repetition.



Comment at: clang/lib/StaticAnalyzer/Checkers/IteratorModeling.cpp:377
+  C.addTransition(StateNonEqual);
   }
+

This is way longer than the previously used `processComparison()` but I am 
reluctant to pass `CheckerContext` to a non-member function. (And especially 
add transitions there. Even worse, to a function in a common library.)


Modeling the `empty()` method of containers both improves iterator range 
checking and enables the possibility to create new checkers for containers.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D76590

Files:
  clang/lib/StaticAnalyzer/Checkers/ContainerModeling.cpp
  clang/lib/StaticAnalyzer/Checkers/Iterator.cpp
  clang/lib/StaticAnalyzer/Checkers/Iterator.h
  clang/lib/StaticAnalyzer/Checkers/IteratorModeling.cpp
  clang/test/Analysis/Inputs/system-header-simulator-cxx.h
  clang/test/Analysis/container-modeling.cpp
  clang/test/Analysis/diagnostics/explicit-suppression.cpp

Index: clang/test/Analysis/diagnostics/explicit-suppression.cpp
===
--- clang/test/Analysis/diagnostics/explicit-suppression.cpp
+++ clang/test/Analysis/diagnostics/explicit-suppression.cpp
@@ -19,6 +19,6 @@
 void testCopyNull(C *I, C *E) {
   std::copy(I, E, (C *)0);
 #ifndef SUPPRESSED
-  // expected-warning@../Inputs/system-header-simulator-cxx.h:698 {{Called C++ object pointer is null}}
+  // expected-warning@../Inputs/system-header-simulator-cxx.h:706 {{Called C++ object pointer is null}}
 #endif
 }
Index: clang/test/Analysis/container-modeling.cpp
===
--- clang/test/Analysis/container-modeling.cpp
+++ clang/test/Analysis/container-modeling.cpp
@@ -16,6 +16,12 @@
 void clang_analyzer_eval(bool);
 void clang_analyzer_warnIfReached();
 
+extern void __assert_fail (__const char *__assertion, __const char *__file,
+unsigned int __line, __const char *__function)
+ __attribute__ ((__noreturn__));
+#define assert(expr) \
+  ((expr)  ? (void)(0)  : __assert_fail (#expr, __FILE__, __LINE__, __func__))
+
 void begin(const std::vector &V) {
   V.begin();
 
@@ -52,6 +58,37 @@
   clang_analyzer_eval(clang_analyzer_container_end(V2) == E2); //expected-warning{{TRUE}}
 }
 
+
+///
+/// C O N T A I N E R   C A P A C I T Y
+///
+
+
+/// empty()
+
+void empty(const std::vector &V) {
+  for (auto n: V) {}
+  clang_analyzer_eval(clang_analyzer_container_begin(V) ==
+  clang_analyzer_container_end(V));
+  // expected-warning@-2{{TRUE}} expected-warning@-2{{FALSE}}
+}
+
+void non_empty1(const std::vector &V) {
+  assert(!V.empty());
+  for (auto n: V) {}
+  clang_analyzer_eval(clang_analyzer_container_begin(V) ==
+  clang_analyzer_container_end(V));
+  // expected-warning@-2{{FALSE}}
+}
+
+void non_empty2(const std::vector &V) {
+  for (auto n: V) {}
+  assert(!V.empty());
+  clang_analyzer_eval(clang_analyzer_container_begin(V) ==
+  clang_analyzer_container_end(V));
+  // expected-warning@-2{{FALSE}}
+}
+
 
 ///
 /// C O N T A I N E R   M O D I F I E R S
Index: clang/test/Analysis/Inputs/system-header-simulator-cxx.h
===
--- clang/test/Analysis/Inputs/system-header-simulator-cxx.h
+++ clang/test/Analysis/Inputs/system-header-simulator-cxx.h
@@ -334,6 +334,8 @@
 const T& front() const { return *begin(); }
 T& back() { return *(end() - 1); }
 const T& back() const { return *(end() - 1); }
+
+bool empty() const;
   };
   
   template
@@ -405,6 +407,8 @@
 const T& front() const { return *begin(); }
 T& back() { return *--end(); }
 const T& back() const { return *--end(); }
+
+bool empty() const;
   };
 
   template
@@ -486,6 +490,8 @@
 const T& front() const { return *begin(); }
 T& back() { return *(end() - 1); }
 const T& back() const { return *(end() - 1); }
+
+bool empty() const;
   };
 
   template
@@ -550,6 +556,8 @@
 
 

[PATCH] D76590: [Analyzer] Model `empty()` member function of containers

2020-03-23 Thread Balogh, Ádám via Phabricator via cfe-commits
baloghadamsoftware added a comment.

Supersedes D62688 .


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76590



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


[PATCH] D76590: [Analyzer] Model `empty()` member function of containers

2020-03-23 Thread Balogh, Ádám via Phabricator via cfe-commits
baloghadamsoftware marked 3 inline comments as done.
baloghadamsoftware added inline comments.



Comment at: clang/lib/StaticAnalyzer/Checkers/IteratorModeling.cpp:359
 State = State->BindExpr(CE, LCtx, RetVal);
   }
 

Maybe I should move these lines into a separate function in the library to 
avoid repetition.



Comment at: clang/lib/StaticAnalyzer/Checkers/IteratorModeling.cpp:377
+  C.addTransition(StateNonEqual);
   }
+

This is way longer than the previously used `processComparison()` but I am 
reluctant to pass `CheckerContext` to a non-member function. (And especially 
add transitions there. Even worse, to a function in a common library.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76590



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


[PATCH] D69560: [clang-tidy] Add 'experimental-cppcoreguidelines-avoid-adjacent-arguments-of-the-same-type' check

2020-03-23 Thread Kim Viggedal via Phabricator via cfe-commits
vingeldal added a comment.

In D69560#1935071 , @whisperity wrote:

> @aaron.ballman I've gone over LLVM (and a few other projects). Some general 
> observations:
>
> - Length of `2` **is vile**. I understand that the C++CG rule says even 
> lengths of 2 should be matched, but that is industrially infeasible unless 
> one introduces such a rule incrementally to their project. Findings of length 
> 2 are **, in general,** an order of magnitude more than... basically the rest 
> of the findings.
>   - On big projects, even the current "default" of "length `3`" seems to be 
> too low. In reality, one should consider (this is likely to be out of scope 
> for Tidy) how often these functions are called, and various other metrics on 
> how serious an offender is.


Not a problem since existing projects can just use the option and change to 
whatever level suits them best. My opinion is still that the default shouldn't 
be set to whatever we think is most useful for the majority of existing 
projects but to what reflects the actual guideline.

Consider how this situation is similar to the guidelines regarding pointers. 
The guidelines assume that a project isn't using old standards of C++. Where 
one has a huge legacy code base it will be impractical at best to try to apply 
the C++ Core Guidelines for pointer handling on the old code.
The expectation is that new projects will use the new libraries and language 
features available to do things differently, in a way that makes it possible  
and practical to follow the guidelines; while legacy code remains unchecked or 
incrementally improved.
For any new code base this guideline shouldn't be a problem and existing 
projects can just adapt the usage of this rule to fit their situation by 
applying it selectively in the code base and/or changing the options.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69560



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


[PATCH] D62688: [Analyzer] Iterator Checkers - Model `empty()` method of containers

2020-03-23 Thread Balogh, Ádám via Phabricator via cfe-commits
baloghadamsoftware abandoned this revision.
baloghadamsoftware added a comment.
Herald added subscribers: ASDenysPetrov, martong, steakhal.

Superseded by D76590 .


Repository:
  rC Clang

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

https://reviews.llvm.org/D62688



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


[PATCH] D76572: Replace `T(x)` with `reinterpret_cast(x)` everywhere it means reinterpret_cast. No functional change

2020-03-23 Thread Noel Grandin via Phabricator via cfe-commits
grandinj added a comment.

Libreoffice has a similar clang-tidy-style cast-checker here:

https://cgit.freedesktop.org/libreoffice/core/tree/compilerplugins/clang/cstylecast.cxx
https://cgit.freedesktop.org/libreoffice/core/tree/compilerplugins/clang/test/cstylecast.cxx


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76572



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


[PATCH] D76592: [Parser] Fix the assertion crash in ActOnStartOfSwitch stmt.

2020-03-23 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: sammccall.
Herald added subscribers: usaxena95, kadircet, ilya-biryukov.
Herald added a project: clang.

After we parse the switch condition, we don't do the type check for
type-dependent expr (e.g. TypoExpr) (in Sema::CheckSwitchCondition), then the
TypoExpr is corrected to an invalid-type expr (in Sema::MakeFullExpr) and passed
to the ActOnStartOfSwitchStmt, which triggers the assertion.

Fix https://github.com/clangd/clangd/issues/311


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D76592

Files:
  clang/lib/Sema/SemaStmt.cpp
  clang/test/Parser/switch-typo-correction.cpp


Index: clang/test/Parser/switch-typo-correction.cpp
===
--- /dev/null
+++ clang/test/Parser/switch-typo-correction.cpp
@@ -0,0 +1,9 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+namespace c { double xxx; }
+namespace d { float xxx; }
+namespace z { namespace xxx {} }
+
+void crash() {
+  switch (xxx) {} // expected-error{{use of undeclared identifier 'xxx'}}
+}
Index: clang/lib/Sema/SemaStmt.cpp
===
--- clang/lib/Sema/SemaStmt.cpp
+++ clang/lib/Sema/SemaStmt.cpp
@@ -706,6 +706,12 @@
   llvm_unreachable("conversion functions are permitted");
 }
   } SwitchDiagnoser(Cond);
+  // The TypoExpr might be corrected to a non-intergral-or-enum type in the
+  // later stage without the proper type check, which is invalid for switch
+  // condition, so we fail the check here (this would avoid emitting incorrect
+  // fixit).
+  if (llvm::isa(Cond))
+return ExprError();
 
   ExprResult CondResult =
   PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);


Index: clang/test/Parser/switch-typo-correction.cpp
===
--- /dev/null
+++ clang/test/Parser/switch-typo-correction.cpp
@@ -0,0 +1,9 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+namespace c { double xxx; }
+namespace d { float xxx; }
+namespace z { namespace xxx {} }
+
+void crash() {
+  switch (xxx) {} // expected-error{{use of undeclared identifier 'xxx'}}
+}
Index: clang/lib/Sema/SemaStmt.cpp
===
--- clang/lib/Sema/SemaStmt.cpp
+++ clang/lib/Sema/SemaStmt.cpp
@@ -706,6 +706,12 @@
   llvm_unreachable("conversion functions are permitted");
 }
   } SwitchDiagnoser(Cond);
+  // The TypoExpr might be corrected to a non-intergral-or-enum type in the
+  // later stage without the proper type check, which is invalid for switch
+  // condition, so we fail the check here (this would avoid emitting incorrect
+  // fixit).
+  if (llvm::isa(Cond))
+return ExprError();
 
   ExprResult CondResult =
   PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D76572: Replace `T(x)` with `reinterpret_cast(x)` everywhere it means reinterpret_cast. No functional change

2020-03-23 Thread James Henderson via Phabricator via cfe-commits
jhenderson added a comment.

@Quuxplusone - did you see that there are several clang-format warnings 
reported against these changes? Please could you fix them.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76572



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


[PATCH] D76594: [clang][AST] User relative offsets inside AST file

2020-03-23 Thread Dmitry Polukhin via Phabricator via cfe-commits
DmitryPolukhin created this revision.
DmitryPolukhin added reviewers: rsmith, dexonsmith.
DmitryPolukhin added a project: clang.
Herald added subscribers: usaxena95, kadircet, ilya-biryukov.

Clang uses 32-bit integers for storing bit offsets from the beginning of
the file that results in 512M limit on AST file. This diff replaces
absolute offsets with relative offsets from the beginning of
corresponding data structure instead of whole file.

This diff breaks AST file format compatibility so VERSION_MAJOR bumped.

Test Plan:
Existing clang AST serialization tests
Tested on clangd with 700M preamble file


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D76594

Files:
  clang/include/clang/Serialization/ASTBitCodes.h
  clang/include/clang/Serialization/ASTReader.h
  clang/include/clang/Serialization/ASTWriter.h
  clang/include/clang/Serialization/ModuleFile.h
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTWriter.cpp

Index: clang/lib/Serialization/ASTWriter.cpp
===
--- clang/lib/Serialization/ASTWriter.cpp
+++ clang/lib/Serialization/ASTWriter.cpp
@@ -1890,6 +1890,7 @@
   // Write out the source location entry table. We skip the first
   // entry, which is always the same dummy entry.
   std::vector SLocEntryOffsets;
+  uint64_t SLocEntryOffsetsBase = Stream.GetCurrentBitNo();
   RecordData PreloadSLocs;
   SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
   for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
@@ -1900,7 +1901,9 @@
 assert(&SourceMgr.getSLocEntry(FID) == SLoc);
 
 // Record the offset of this source-location entry.
-SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
+uint64_t Offset = Stream.GetCurrentBitNo() - SLocEntryOffsetsBase;
+assert((Offset >> 32) == 0 && "SLocEntry offset too large");
+SLocEntryOffsets.push_back(Offset);
 
 // Figure out which record code to use.
 unsigned Code;
@@ -2008,12 +2011,14 @@
   Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
+  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // base offset
   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
   unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
   {
 RecordData::value_type Record[] = {
 SOURCE_LOCATION_OFFSETS, SLocEntryOffsets.size(),
-SourceMgr.getNextLocalOffset() - 1 /* skip dummy */};
+SourceMgr.getNextLocalOffset() - 1 /* skip dummy */,
+SLocEntryOffsetsBase};
 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
   bytes(SLocEntryOffsets));
   }
@@ -2090,9 +2095,11 @@
 /// Writes the block containing the serialized form of the
 /// preprocessor.
 void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
+  uint64_t MacroOffsetsBase = Stream.GetCurrentBitNo();
+
   PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
   if (PPRec)
-WritePreprocessorDetail(*PPRec);
+WritePreprocessorDetail(*PPRec, MacroOffsetsBase);
 
   RecordData Record;
   RecordData ModuleMacroRecord;
@@ -2153,7 +2160,8 @@
   // identifier they belong to.
   for (const IdentifierInfo *Name : MacroIdentifiers) {
 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(Name);
-auto StartOffset = Stream.GetCurrentBitNo();
+uint64_t StartOffset = Stream.GetCurrentBitNo() - MacroOffsetsBase;
+assert((StartOffset >> 32) == 0 && "Macro identifiers offset too large");
 
 // Emit the macro directives in reverse source order.
 for (; MD; MD = MD->getPrevious()) {
@@ -2226,14 +2234,12 @@
 
 // Record the local offset of this macro.
 unsigned Index = ID - FirstMacroID;
-if (Index == MacroOffsets.size())
-  MacroOffsets.push_back(Stream.GetCurrentBitNo());
-else {
-  if (Index > MacroOffsets.size())
-MacroOffsets.resize(Index + 1);
+if (Index >= MacroOffsets.size())
+  MacroOffsets.resize(Index + 1);
 
-  MacroOffsets[Index] = Stream.GetCurrentBitNo();
-}
+uint64_t Offset = Stream.GetCurrentBitNo() - MacroOffsetsBase;
+assert((Offset >> 32) == 0 && "Macro offset too large");
+MacroOffsets[Index] = Offset;
 
 AddIdentifierRef(Name, Record);
 AddSourceLocation(MI->getDefinitionLoc(), Record);
@@ -2284,17 +2290,20 @@
   Abbrev->Add(BitCodeAbbrevOp(MACRO_OFFSET));
   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macros
   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
+  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32));   // base offset
   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
 
   unsigned MacroOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
   {
 RecordData::value_type Record[] = {MACRO_OFFSET, MacroOffsets.size(),
-   

[PATCH] D69330: [AST] Add RecoveryExpr to retain expressions on semantic errors

2020-03-23 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 251966.
hokein marked 7 inline comments as done.
hokein added a comment.

address some comments, add missing tree-transform testcase.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69330

Files:
  clang/include/clang/AST/ComputeDependence.h
  clang/include/clang/AST/Expr.h
  clang/include/clang/AST/RecursiveASTVisitor.h
  clang/include/clang/Basic/StmtNodes.td
  clang/include/clang/Sema/Sema.h
  clang/include/clang/Serialization/ASTBitCodes.h
  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/StmtPrinter.cpp
  clang/lib/AST/StmtProfile.cpp
  clang/lib/Parse/ParseExpr.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaExceptionSpec.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/TreeTransform.h
  clang/lib/Serialization/ASTReaderStmt.cpp
  clang/lib/Serialization/ASTWriterDecl.cpp
  clang/lib/Serialization/ASTWriterStmt.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
  clang/test/AST/ast-dump-expr-errors.cpp
  clang/test/AST/ast-dump-recovery.cpp
  clang/test/Index/getcursor-recovery.cpp
  clang/test/OpenMP/target_update_from_messages.cpp
  clang/test/OpenMP/target_update_to_messages.cpp
  clang/test/Parser/objcxx0x-lambda-expressions.mm
  clang/test/Parser/objcxx11-invalid-lambda.cpp
  clang/test/SemaCXX/builtins.cpp
  clang/test/SemaCXX/cast-conversion.cpp
  clang/test/SemaCXX/cxx1z-copy-omission.cpp
  clang/test/SemaCXX/decltype-crash.cpp
  clang/test/SemaCXX/varargs.cpp
  clang/test/SemaOpenCLCXX/address-space-references.cl
  clang/test/SemaTemplate/instantiate-init.cpp
  clang/test/SemaTemplate/recovery-tree-transform.cpp
  clang/tools/libclang/CXCursor.cpp
  clang/unittests/Sema/CodeCompleteTest.cpp

Index: clang/unittests/Sema/CodeCompleteTest.cpp
===
--- clang/unittests/Sema/CodeCompleteTest.cpp
+++ clang/unittests/Sema/CodeCompleteTest.cpp
@@ -487,6 +487,8 @@
 auto x = decltype(&1)(^);
 auto y = new decltype(&1)(^);
   )cpp";
-  EXPECT_THAT(collectPreferredTypes(Code), Each("NULL TYPE"));
+  EXPECT_THAT(collectPreferredTypes(Code),
+  Each("decltype((1))"));
 }
+
 } // namespace
Index: clang/tools/libclang/CXCursor.cpp
===
--- clang/tools/libclang/CXCursor.cpp
+++ clang/tools/libclang/CXCursor.cpp
@@ -292,6 +292,7 @@
   case Stmt::ObjCDictionaryLiteralClass:
   case Stmt::ObjCBoxedExprClass:
   case Stmt::ObjCSubscriptRefExprClass:
+  case Stmt::RecoveryExprClass:
 K = CXCursor_UnexposedExpr;
 break;
 
Index: clang/test/SemaTemplate/recovery-tree-transform.cpp
===
--- /dev/null
+++ clang/test/SemaTemplate/recovery-tree-transform.cpp
@@ -0,0 +1,4 @@
+// RUN: %clang_cc1 -verify %s
+
+template int *p = &void(T::error); // expected-error{{cannot take the address of an rvalue}} expected-error{{type 'int' cannot be used prior to '::'}}
+int *q = p; // expected-note{{in instantiation of variable template specialization 'p' requested here}}
Index: clang/test/SemaTemplate/instantiate-init.cpp
===
--- clang/test/SemaTemplate/instantiate-init.cpp
+++ clang/test/SemaTemplate/instantiate-init.cpp
@@ -100,7 +100,7 @@
 integral_c<1> ic1 = array_lengthof(Description::data);
 (void)sizeof(array_lengthof(Description::data));
 
-sizeof(array_lengthof( // expected-error{{no matching function for call to 'array_lengthof'}}
+(void)sizeof(array_lengthof( // expected-error{{no matching function for call to 'array_lengthof'}}
   Description::data // expected-note{{in instantiation of static data member 'PR7985::Description::data' requested here}}
   ));
 
Index: clang/test/SemaOpenCLCXX/address-space-references.cl
===
--- clang/test/SemaOpenCLCXX/address-space-references.cl
+++ clang/test/SemaOpenCLCXX/address-space-references.cl
@@ -11,7 +11,7 @@
 int bar(const unsigned int &i);
 
 void foo() {
-  bar(1) // expected-error{{binding reference of type 'const __global unsigned int' to value of type 'int' changes address space}}
+  bar(1); // expected-error{{binding reference of type 'const __global unsigned int' to value of type 'int' changes address space}}
 }
 
 // Test addr space conversion with nested pointers
Index: clang/test/SemaCXX/varargs.cpp
===
--- clang/test/SemaCXX/varargs.cpp
+++ clang/test/SemaCXX/varargs.cpp
@@ -22,7 +22,8 @@
 // default ctor.
 void record_context(int a, ...) {
   struct Foo {
-// expected-error@+1 {{'va_start' cannot be used outside a function}}
+// expect

[PATCH] D76595: [clangd-vscode] NFC; Improve wording in documentation and update VSCode tasks

2020-03-23 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev created this revision.
kbobyrev added a reviewer: hokein.
Herald added subscribers: cfe-commits, usaxena95, kadircet, arphaman, jkorous, 
MaskRay, ilya-biryukov.
Herald added a project: clang.

VSCode tasks are updated to the latest supported versions: deprecated
values are removed and replaced by their new counterparts.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D76595

Files:
  clang-tools-extra/clangd/clients/clangd-vscode/.vscode/launch.json
  clang-tools-extra/clangd/clients/clangd-vscode/.vscode/tasks.json
  clang-tools-extra/clangd/clients/clangd-vscode/DEVELOPING.md
  clang-tools-extra/clangd/clients/clangd-vscode/src/extension.ts
  clang-tools-extra/clangd/clients/clangd-vscode/tsconfig.json

Index: clang-tools-extra/clangd/clients/clangd-vscode/tsconfig.json
===
--- clang-tools-extra/clangd/clients/clangd-vscode/tsconfig.json
+++ clang-tools-extra/clangd/clients/clangd-vscode/tsconfig.json
@@ -26,4 +26,4 @@
 "node_modules",
 ".vscode-test"
 ]
-}
\ No newline at end of file
+}
Index: clang-tools-extra/clangd/clients/clangd-vscode/src/extension.ts
===
--- clang-tools-extra/clangd/clients/clangd-vscode/src/extension.ts
+++ clang-tools-extra/clangd/clients/clangd-vscode/src/extension.ts
@@ -3,7 +3,7 @@
 import * as semanticHighlighting from './semantic-highlighting';
 
 /**
- * Method to get workspace configuration option
+ * Get an option from workspace configuration.
  * @param option name of the option (e.g. for clangd.path should be path)
  * @param defaultValue default value to return if option is not set
  */
@@ -75,8 +75,8 @@
 }
 
 /**
- *  this method is called when your extension is activate
- *  your extension is activated the very first time the command is executed
+ *  This method is called when the extension is activated. The extension is
+ *  activated the very first time a command is executed.
  */
 export function activate(context: vscode.ExtensionContext) {
   const syncFileEvents = getConfig('syncFileEvents', true);
@@ -97,7 +97,7 @@
 documentSelector: [
 { scheme: 'file', language: 'c' },
 { scheme: 'file', language: 'cpp' },
-// cuda is not supported by vscode, but our extension does.
+// CUDA is not supported by vscode, but our extension does supports it.
 { scheme: 'file', language: 'cuda' },
 { scheme: 'file', language: 'objective-c'},
 { scheme: 'file', language: 'objective-cpp'}
@@ -106,7 +106,7 @@
 // FIXME: send sync file events when clangd provides implementations.
 },
 initializationOptions: { clangdFileStatus: true },
-// Do not switch to output window when clangd returns output
+// Do not switch to output window when clangd returns output.
 revealOutputChannelOn: vscodelc.RevealOutputChannelOn.Never,
 
 // We hack up the completion items a bit to prevent VSCode from re-ranking them
@@ -126,7 +126,7 @@
   provideCompletionItem: async (document, position, context, token, next) => {
 let list = await next(document, position, context, token);
 let items = (Array.isArray(list) ? list : list.items).map(item => {
-  // Gets the prefix used by vscode when doing fuzzymatch.
+  // Gets the prefix used by VSCode when doing fuzzymatch.
   let prefix = document.getText(new vscode.Range(item.range.start, position))
   if (prefix)
 item.filterText = prefix + "_" + item.filterText;
Index: clang-tools-extra/clangd/clients/clangd-vscode/DEVELOPING.md
===
--- clang-tools-extra/clangd/clients/clangd-vscode/DEVELOPING.md
+++ clang-tools-extra/clangd/clients/clangd-vscode/DEVELOPING.md
@@ -10,20 +10,20 @@
 ## Steps
 
 1. Make sure you disable the installed `vscode-clangd` extension in VS Code.
-2. Make sure you have clangd in /usr/bin/clangd or edit src/extension.ts to
+2. Make sure you have clangd in `/usr/bin/clangd` or edit `src/extension.ts` to
 point to the binary.
-3. In order to start a development instance of VS code extended with this, run:
+3. To start a development instance of VS code extended with this, run:
 
 ```bash
$ cd /path/to/clang-tools-extra/clangd/clients/clangd-vscode/
$ npm install
$ code .
-   # When VS Code starts, press .
+   # When VSCode starts, press .
 ```
 
 # Contributing
 
-Please follow the exsiting code style when contributing to the extension, we
+Please follow the existing code style when contributing to the extension, we
 recommend to run `npm run format` before sending a patch.
 
 # Publish to VS Code Marketplace
@@ -38,15 +38,15 @@
 * Bump the version in `package.json`, and commit the change to upstream
 
 The extension is published under `llvm-vs-code-extensio

[PATCH] D69330: [AST] Add RecoveryExpr to retain expressions on semantic errors

2020-03-23 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clang/include/clang/AST/Expr.h:5920
+///
+/// RecoveryExpr is type-, value- and instantiation-dependent to take advantage
+/// of existing machinery to deal with dependent code in C++, e.g. RecoveryExpr

sammccall wrote:
> AIUI this should be "for now" with the goal of eliminating the use of 
> template dependence concepts, right?
yeah, I think so. 



Comment at: clang/lib/Sema/SemaExpr.cpp:18401
+  // FIXME: use containsErrors() to suppress unwanted diags in C.
+  if (!Context.getLangOpts().CPlusPlus)
+return ExprError();

sammccall wrote:
> I think we should strongly consider a LangOption with an associated flag. 
> (e.g. LangOptions.RecoveryAST, -f[no]recovery-ast).
> If we're going to pay tho cost of letting expr creation fail, we might as 
> well use it
> Use cases:
>  - Control rollout: we can check this in without (yet) flipping the flag on 
> for all tools at once, if desired. If we flip the default and it causes 
> problems for particular tools, we can turn it off for that tool rather than 
> rolling the whole thing back.
>  - turn on and off in lit tests to precisely test behavior and avoid 
> dependence on defaults
>  - allow incremental work on recovery in !CPlusPlus mode
> 
> If this makes sense to you, I'd suggest setting the default to off in this 
> patch (and including some tests that pass `-frecovery-ast`), and then 
> immediately following up with a patch that flips the default to on-for-C++.
> This separation makes like easier for everyone if turning this on breaks 
> something.
> 
> A bunch of the updates to existing tests would be deferred until that patch.
+1, I think this is a good idea -- particularly letting us incrementally 
working on it without breaking existing tools, I was highly suspected that this 
patch will fail internal tests during build copping.

I will wait for a while for other feedback @rsmith before making the actual 
change.



Comment at: clang/lib/Sema/TreeTransform.h:9470
+ExprResult TreeTransform::TransformRecoveryExpr(RecoveryExpr *E) {
+  return E;
+}

sammccall wrote:
> rsmith wrote:
> > ilya-biryukov wrote:
> > > rsmith wrote:
> > > > We should either transform the subexpressions or just return 
> > > > `ExprError()` here. With this approach, we can violate AST invariants 
> > > > (eg, by having the same `Expr` reachable through two different code 
> > > > paths in the same function body, or by retaining `DeclRefExpr`s 
> > > > referring to declarations from the wrong context, etc).
> > > Thanks, I just blindly copied what TypoExpr was doing without considering 
> > > the consequences here.
> > > 
> > > 
> > > Added the code to rebuild `RecoveryExpr`.
> > > 
> > > Any good way to test this?
> > Hmm, testing that the old failure mode doesn't happen seems a bit tricky; 
> > any test for that is going to be testing second-order effects of the code 
> > under test, so will be fragile. But you can test that we're substituting 
> > into the `RecoveryExpr` easily enough: put some expression for which 
> > substitution will fail into a context where we'll build a `RecoveryExpr` 
> > inside a context that we'll `TreeTransform`. For example, maybe:
> > 
> > ```
> > template int *p = &void(T::error); // should produce "cannot 
> > take address of void"
> > int *q = p; // should produce "'int' cannot be used prior to '::'" in 
> > instantiation
> > ```
> @hokein I don't think this test was added yet.
good catch, done.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69330



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


[PATCH] D76295: [clang][AST] Use 64 bit integers for bit offsets inside AST file

2020-03-23 Thread Dmitry Polukhin via Phabricator via cfe-commits
DmitryPolukhin abandoned this revision.
DmitryPolukhin added a comment.

Relative 32-bit offsets in https://reviews.llvm.org/D76594


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76295



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


[PATCH] D74619: [ARM] Enabling range checks on Neon intrinsics' lane arguments

2020-03-23 Thread Lucas Prates via Phabricator via cfe-commits
pratlucas added a comment.

Hi @leonardchan ,

I've double-checked the Neon intrinsics reference and it indeed confirms that 
the only allowed value for the lane argument for `vdupq_lane_f64` is `0`:

  Argument Preparation
  
  vec → Vn.1D 
  0 << lane << 0

(https://developer.arm.com/architectures/instruction-sets/simd-isas/neon/intrinsics?search=vdupq_lane_f64)

I believe the observed behaviour is expected.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D74619



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


[PATCH] D76355: [Syntax] Build mapping from AST to syntax tree nodes

2020-03-23 Thread Marcel Hlopko via Phabricator via cfe-commits
hlopko updated this revision to Diff 251968.
hlopko added a comment.

Reformat


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76355

Files:
  clang/include/clang/Tooling/Syntax/Tree.h
  clang/lib/Tooling/Syntax/BuildTree.cpp
  clang/lib/Tooling/Syntax/Tree.cpp

Index: clang/lib/Tooling/Syntax/Tree.cpp
===
--- clang/lib/Tooling/Syntax/Tree.cpp
+++ clang/lib/Tooling/Syntax/Tree.cpp
@@ -66,14 +66,20 @@
 bool syntax::Tree::classof(const Node *N) { return N->kind() > NodeKind::Leaf; }
 
 void syntax::Tree::prependChildLowLevel(Node *Child, NodeRole Role) {
-  assert(Child->Parent == nullptr);
-  assert(Child->NextSibling == nullptr);
   assert(Child->role() == NodeRole::Detached);
   assert(Role != NodeRole::Detached);
 
+  Child->Role = static_cast(Role);
+  prependChildLowLevel(Child);
+}
+
+void syntax::Tree::prependChildLowLevel(Node *Child) {
+  assert(Child->Parent == nullptr);
+  assert(Child->NextSibling == nullptr);
+  assert(Child->role() != NodeRole::Detached);
+
   Child->Parent = this;
   Child->NextSibling = this->FirstChild;
-  Child->Role = static_cast(Role);
   this->FirstChild = Child;
 }
 
Index: clang/lib/Tooling/Syntax/BuildTree.cpp
===
--- clang/lib/Tooling/Syntax/BuildTree.cpp
+++ clang/lib/Tooling/Syntax/BuildTree.cpp
@@ -25,6 +25,8 @@
 #include "clang/Tooling/Syntax/Tokens.h"
 #include "clang/Tooling/Syntax/Tree.h"
 #include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/PointerUnion.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/ScopeExit.h"
 #include "llvm/ADT/SmallVector.h"
@@ -34,6 +36,7 @@
 #include "llvm/Support/FormatVariadic.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/raw_ostream.h"
+#include 
 #include 
 
 using namespace clang;
@@ -145,6 +148,31 @@
   return SourceRange(Start, End);
 }
 
+namespace {
+/// All AST hierarchy roots that can be represented as pointers.
+using ASTPtr = llvm::PointerUnion;
+/// Maintains a mapping from AST to syntax tree nodes. This class will get more
+/// complicated as we support more kinds of AST nodes, e.g. TypeLocs.
+/// FIXME: expose this as public API.
+class ASTToSyntaxMapping {
+public:
+  void add(ASTPtr From, syntax::Tree *To) {
+assert(To != nullptr);
+assert(!From.isNull());
+
+bool Added = Nodes.insert({From, To}).second;
+(void)Added;
+assert(Added && "mapping added twice");
+  }
+
+  syntax::Tree *find(ASTPtr P) const { return Nodes.lookup(P); }
+
+private:
+  // Keys are either Stmt* or Decl*.
+  llvm::DenseMap Nodes;
+};
+} // namespace
+
 /// A helper class for constructing the syntax tree while traversing a clang
 /// AST.
 ///
@@ -172,7 +200,18 @@
 
   /// Populate children for \p New node, assuming it covers tokens from \p
   /// Range.
-  void foldNode(llvm::ArrayRef Range, syntax::Tree *New);
+  void foldNode(llvm::ArrayRef Range, syntax::Tree *New,
+ASTPtr From) {
+assert(New);
+Pending.foldChildren(Arena, Range, New);
+if (From)
+  Mapping.add(From, New);
+  }
+  void foldNode(llvm::ArrayRef Range, syntax::Tree *New,
+TypeLoc L) {
+// FIXME: add mapping for TypeLocs
+foldNode(Range, New, nullptr);
+  }
 
   /// Must be called with the range of each `DeclaratorDecl`. Ensures the
   /// corresponding declarator nodes are covered by `SimpleDeclaration`.
@@ -195,8 +234,10 @@
   /// Set role for \p T.
   void markChildToken(const syntax::Token *T, NodeRole R);
 
-  /// Set role for the node that spans exactly \p Range.
-  void markChild(llvm::ArrayRef Range, NodeRole R);
+  /// Set role for \p N.
+  void markChild(syntax::Node *N, NodeRole R);
+  /// Set role for the syntax node matching \p N.
+  void markChild(ASTPtr N, NodeRole R);
   /// Set role for the delayed node that spans exactly \p Range.
   void markDelayedChild(llvm::ArrayRef Range, NodeRole R);
   /// Set role for the node that may or may not be delayed. Node must span
@@ -290,6 +331,11 @@
 return Tokens;
   }
 
+  void setRole(syntax::Node *N, NodeRole R) {
+assert(N->role() == NodeRole::Detached);
+N->Role = static_cast(R);
+  }
+
   /// A collection of trees covering the input tokens.
   /// When created, each tree corresponds to a single token in the file.
   /// Clients call 'foldChildren' to attach one or more subtrees to a parent
@@ -306,7 +352,7 @@
 auto *L = new (A.allocator()) syntax::Leaf(&T);
 L->Original = true;
 L->CanModify = A.tokenBuffer().spelledForExpanded(T).hasValue();
-Trees.insert(Trees.end(), {&T, NodeAndRole{L}});
+Trees.insert(Trees.end(), {&T, L});
   }
 }
 
@@ -338,7 +384,9 @@
   assert((std::next(It) == Trees.end() ||
   std::next(It)->first == Range.end()) &&
  "no child with the specified range");
-  I

Re: [clang] d9b9621 - Reland D73534: [DebugInfo] Enable the debug entry values feature by default

2020-03-23 Thread David Stenberg via cfe-commits
Hi!

On Mon, 2020-03-23 at 08:56 +0100, Djordje wrote:
> (+ CCing some debug info folks as well)
> 
> Hi David,
> 
> OK, I agree, my apologize.
> 
> The patch enables the whole feature by default and removes the experimental
> option that has been used during the implementation.
> We tested the code (and the assertions regarding the feature itself) by using
> the experimental option on some large projects, but since the feature became
> that huge (and new patches regarding the feature are coming every day -- which
> is nice), it is impossible to test everything.

When the issue related to D75036 was reported I probably should have reverted
that commit directly when starting to troubleshoot the issue, so that we didn't
have to end up reverting D73534.

Sorry about that!

> The Debug Entry Values implementation grows these days, and new 
> functionalities
> comes in, but it has all been tested with the experimental option, so
> committing this particular patch imposes all the cases developers oversighted
> during the implementation.
> 
> My impression is that, before adding new functionalities to the feature, we
> should make sure the D73534 is stable and gets stuck. We should have done it
> before, but I think that is the lesson learned here.

That sounds reasonable I think. For how long should we do that? A week? Two
weeks?

> In general, experimental options are very good up to the some point, but if 
> the
> feature being tested grows a lot, a "breakpoint" should be set up and take 
> care
> the experimental option is removed and the code is well tested on the real
> cases out there, and then moving to the next stage of the implementation.
> 
> Besides this, CISCO is using the feature ON by default for some time, and we
> have good experience there. This really improves the debugging user experience
> while debugging the "optimized" code.
> 
> Best regards,
> Djordje

Best regards,
David S

> On 22.3.20. 16:30, David Blaikie wrote:
> > Also, this patch was reverted and recommitted several times (more than I
> > think would be ideal) - please include more details in the commit message
> > about what went wrong, what was fixed, what testing was missed in the first
> > place and done in subsequent precommit validation (& is there anything more
> > broadly we could learn from this patches story to avoid this kind of
> > revert/recommit repetition in the future?)
> > 
> > On Sat, Mar 21, 2020 at 8:13 PM David Blaikie  > dblai...@gmail.com>> wrote:
> > 
> > Please include the "Differential Revision" line so that Phab picks up
> > commits like this and ties them into the review (& also makes it 
> > conveniently
> > clickable to jump from the commit mail to the review)
> > 
> > On Thu, Mar 19, 2020 at 5:58 AM Djordje Todorovic via cfe-commits <
> > cfe-commits@lists.llvm.org > wrote:
> > 
> > 
> > Author: Djordje Todorovic
> > Date: 2020-03-19T13:57:30+01:00
> > New Revision: d9b962100942c71a4c26debaa716f7ab0c4ea8a1
> > 
> > URL: 
> > https://protect2.fireeye.com/v1/url?k=77e8c227-2b3ccf55-77e882bc-86859b2931b3-a6817f347a752f02&q=1&e=88d8925e-f175-4c81-9485-741ddc24573f&u=https%3A%2F%2Fgithub.com%2Fllvm%2Fllvm-project%2Fcommit%2Fd9b962100942c71a4c26debaa716f7ab0c4ea8a1
> > DIFF: 
> > https://protect2.fireeye.com/v1/url?k=3914be57-65c0b325-3914fecc-86859b2931b3-b52b8ad09d192520&q=1&e=88d8925e-f175-4c81-9485-741ddc24573f&u=https%3A%2F%2Fgithub.com%2Fllvm%2Fllvm-project%2Fcommit%2Fd9b962100942c71a4c26debaa716f7ab0c4ea8a1.diff
> > 
> > LOG: Reland D73534: [DebugInfo] Enable the debug entry values 
> > feature
> > by default
> > 
> > The issue that was causing the build failures was fixed with the
> > D76164.
> > 
> > Added:
> > llvm/test/DebugInfo/X86/no-entry-values-with-O0.ll
> > 
> > Modified:
> > clang/include/clang/Basic/CodeGenOptions.def
> > clang/include/clang/Driver/CC1Options.td
> > clang/lib/CodeGen/BackendUtil.cpp
> > clang/lib/CodeGen/CGDebugInfo.cpp
> > clang/lib/Frontend/CompilerInvocation.cpp
> > clang/test/CodeGen/debug-info-extern-call.c
> > clang/test/CodeGenCXX/dbg-info-all-calls-described.cpp
> > lldb/packages/Python/lldbsuite/test/decorators.py
> >
> > lldb/test/API/functionalities/param_entry_vals/basic_entry_values_x86_64/Make
> > file
> > llvm/include/llvm/Target/TargetMachine.h
> > llvm/include/llvm/Target/TargetOptions.h
> > llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp
> > llvm/lib/CodeGen/AsmPrinter/DwarfDebug.h
> > llvm/lib/CodeGen/CommandFlags.cpp
> > llvm/lib/CodeGen/LiveDebugValues.cpp
> > llvm/lib/CodeGen/TargetOptionsImpl.cpp
> > llvm/lib/Target/AArch64/AArch64TargetMachine.cpp
> > llvm/lib/Target/ARM/ARMTargetMachine.cpp
> > llvm/lib/

[clang-tools-extra] df5fa48 - [clang-tidy][NFC] Add missing check group docs and order entries

2020-03-23 Thread via cfe-commits

Author: Whisperity
Date: 2020-03-23T11:05:34+01:00
New Revision: df5fa48739769d6876a56ca35eb350652130f0fc

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

LOG: [clang-tidy][NFC] Add missing check group docs and order entries

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

Added: 


Modified: 
clang-tools-extra/clang-tidy/ClangTidyForceLinker.h
clang-tools-extra/docs/clang-tidy/index.rst

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/ClangTidyForceLinker.h 
b/clang-tools-extra/clang-tidy/ClangTidyForceLinker.h
index 8d29e62c4408..1d6bd2a4fd62 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyForceLinker.h
+++ b/clang-tools-extra/clang-tidy/ClangTidyForceLinker.h
@@ -15,16 +15,16 @@
 namespace clang {
 namespace tidy {
 
-// This anchor is used to force the linker to link the CERTModule.
-extern volatile int CERTModuleAnchorSource;
-static int LLVM_ATTRIBUTE_UNUSED CERTModuleAnchorDestination =
-CERTModuleAnchorSource;
-
 // This anchor is used to force the linker to link the AbseilModule.
 extern volatile int AbseilModuleAnchorSource;
 static int LLVM_ATTRIBUTE_UNUSED AbseilModuleAnchorDestination =
 AbseilModuleAnchorSource;
 
+// This anchor is used to force the linker to link the AndroidModule.
+extern volatile int AndroidModuleAnchorSource;
+static int LLVM_ATTRIBUTE_UNUSED AndroidModuleAnchorDestination =
+AndroidModuleAnchorSource;
+
 // This anchor is used to force the linker to link the BoostModule.
 extern volatile int BoostModuleAnchorSource;
 static int LLVM_ATTRIBUTE_UNUSED BoostModuleAnchorDestination =
@@ -35,20 +35,10 @@ extern volatile int BugproneModuleAnchorSource;
 static int LLVM_ATTRIBUTE_UNUSED BugproneModuleAnchorDestination =
 BugproneModuleAnchorSource;
 
-// This anchor is used to force the linker to link the LinuxKernelModule.
-extern volatile int LinuxKernelModuleAnchorSource;
-static int LLVM_ATTRIBUTE_UNUSED LinuxKernelModuleAnchorDestination =
-LinuxKernelModuleAnchorSource;
-
-// This anchor is used to force the linker to link the LLVMModule.
-extern volatile int LLVMModuleAnchorSource;
-static int LLVM_ATTRIBUTE_UNUSED LLVMModuleAnchorDestination =
-LLVMModuleAnchorSource;
-
-// This anchor is used to force the linker to link the LLVMLibcModule.
-extern volatile int LLVMLibcModuleAnchorSource;
-static int LLVM_ATTRIBUTE_UNUSED LLVMLibcModuleAnchorDestination =
-LLVMLibcModuleAnchorSource;
+// This anchor is used to force the linker to link the CERTModule.
+extern volatile int CERTModuleAnchorSource;
+static int LLVM_ATTRIBUTE_UNUSED CERTModuleAnchorDestination =
+CERTModuleAnchorSource;
 
 // This anchor is used to force the linker to link the CppCoreGuidelinesModule.
 extern volatile int CppCoreGuidelinesModuleAnchorSource;
@@ -70,10 +60,25 @@ extern volatile int GoogleModuleAnchorSource;
 static int LLVM_ATTRIBUTE_UNUSED GoogleModuleAnchorDestination =
 GoogleModuleAnchorSource;
 
-// This anchor is used to force the linker to link the AndroidModule.
-extern volatile int AndroidModuleAnchorSource;
-static int LLVM_ATTRIBUTE_UNUSED AndroidModuleAnchorDestination =
-AndroidModuleAnchorSource;
+// This anchor is used to force the linker to link the HICPPModule.
+extern volatile int HICPPModuleAnchorSource;
+static int LLVM_ATTRIBUTE_UNUSED HICPPModuleAnchorDestination =
+HICPPModuleAnchorSource;
+
+// This anchor is used to force the linker to link the LinuxKernelModule.
+extern volatile int LinuxKernelModuleAnchorSource;
+static int LLVM_ATTRIBUTE_UNUSED LinuxKernelModuleAnchorDestination =
+LinuxKernelModuleAnchorSource;
+
+// This anchor is used to force the linker to link the LLVMModule.
+extern volatile int LLVMModuleAnchorSource;
+static int LLVM_ATTRIBUTE_UNUSED LLVMModuleAnchorDestination =
+LLVMModuleAnchorSource;
+
+// This anchor is used to force the linker to link the LLVMLibcModule.
+extern volatile int LLVMLibcModuleAnchorSource;
+static int LLVM_ATTRIBUTE_UNUSED LLVMLibcModuleAnchorDestination =
+LLVMLibcModuleAnchorSource;
 
 // This anchor is used to force the linker to link the MiscModule.
 extern volatile int MiscModuleAnchorSource;
@@ -93,6 +98,11 @@ static int LLVM_ATTRIBUTE_UNUSED MPIModuleAnchorDestination =
 MPIModuleAnchorSource;
 #endif
 
+// This anchor is used to force the linker to link the ObjCModule.
+extern volatile int ObjCModuleAnchorSource;
+static int LLVM_ATTRIBUTE_UNUSED ObjCModuleAnchorDestination =
+ObjCModuleAnchorSource;
+
 // This anchor is used to force the linker to link the OpenMPModule.
 extern volatile int OpenMPModuleAnchorSource;
 static int LLVM_ATTRIBUTE_UNUSED OpenMPModuleAnchorDestination =
@@ -113,16 +123,6 @@ extern volatile int ReadabilityModuleAnchorSource;
 static int LLVM_ATTRIBUTE_UNUSED Readability

[PATCH] D76545: [clang-tidy] Add a new check group 'experimental-'

2020-03-23 Thread Whisperity via Phabricator via cfe-commits
whisperity added a comment.

In D76545#1935603 , @aaron.ballman 
wrote:

> I think we want to keep the experimental checks grouped to their parent 
> module rather than being in a module of their own.


For this, wouldn't the fact that telling Tidy to enable `cppcoreguidelines-*` 
(i.e. `--checks='-*,cppcoreguidelines-*'`) also enables the 
`cppcoreguidelines-experimental-*` cause a problem? (This is the original 
reason why I tinkered in the "top-level" `experimental-` mode.)

In D76545#1935603 , @aaron.ballman 
wrote:

> I'm not opposed to the idea of experimental checks, but I don't want to see 
> "experimental" become a dumping ground for low-quality checks that we then 
> have to maintain indefinitely.


I think this could (in terms of development, support, etc.) work similarly to 
the `alpha.` group/package of Clang Static Analyser checkers. I'm not too 
knowledgeable about CSA - perhaps @Szelethus could help me out, - but their 
idea of alpha checkers is that they are mature in terms of the general idea, 
but clunky in terms of working. (The official stance is that anything out of 
alpha should not crash, anything within alpha might crash, and if you enable it 
and you crash, you are your own perpetrator.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76545



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


[PATCH] D76355: [Syntax] Build mapping from AST to syntax tree nodes

2020-03-23 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr2 added inline comments.



Comment at: clang/lib/Tooling/Syntax/BuildTree.cpp:173
+private:
+  // Keys are either Stmt* or Decl*.
+  llvm::DenseMap Nodes;

The comment is not needed anymore.



Comment at: clang/lib/Tooling/Syntax/BuildTree.cpp:490
+if (C->role() == NodeRole::Detached)
+  C->Role = static_cast(NodeRole::Unknown);
+Node->prependChildLowLevel(C);

Could you add a private setter that performs this cast? (The cast is repeated 
at least 3 times in this patch.)



Comment at: clang/lib/Tooling/Syntax/BuildTree.cpp:570
+  auto *N = new (allocator()) syntax::SimpleDeclarator;
+  Builder.foldNode(Builder.getRange(R.getBegin(), R.getEnd()), N, D);
+  Builder.markChild(N, syntax::NodeRole::SimpleDeclaration_declarator);

It might make sense to add a helper `Builder.getRange(SourceRange)` and 
simplify these calls to `Builder.getRange(something.getBegin(), 
something.getEnd())` throughout the patch.



Comment at: clang/lib/Tooling/Syntax/BuildTree.cpp:975
+  const syntax::Token *TemplateKW,
+  syntax::SimpleDeclaration *InnerDeclaration) {
 assert(!ExternKW || ExternKW->kind() == tok::kw_extern);

Add a `Decl *From` parameter and pass it through to `Builder.foldNode()` below?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76355



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


[PATCH] D72446: [Syntax] Build mapping from AST to syntax tree nodes

2020-03-23 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr2 closed this revision.
gribozavr2 added a comment.

Superseded by https://reviews.llvm.org/D76355.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D72446



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


[PATCH] D76595: [clangd-vscode] NFC; Improve wording in documentation and update VSCode tasks

2020-03-23 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.

thanks. regarding files in `.vscode`, I think they are just local configs in 
VSCode, we can probably remove the whole directory from git since we already 
ignore them in the `llvm/.gitignore`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76595



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


[PATCH] D76509: [analyzer][NFC] Move the text output type to its own file, move code to PathDiagnosticConsumer creator functions

2020-03-23 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus updated this revision to Diff 251973.
Szelethus added a comment.

Unbreak clang-tidy.


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

https://reviews.llvm.org/D76509

Files:
  clang/include/clang/StaticAnalyzer/Core/Analyses.def
  clang/lib/StaticAnalyzer/Core/CMakeLists.txt
  clang/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp
  clang/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp
  clang/lib/StaticAnalyzer/Core/SarifDiagnostics.cpp
  clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp
  clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp

Index: clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
===
--- clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
+++ clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
@@ -60,115 +60,6 @@
 STATISTIC(PercentReachableBlocks, "The % of reachable basic blocks.");
 STATISTIC(MaxCFGSize, "The maximum number of basic blocks in a function.");
 
-//===--===//
-// Special PathDiagnosticConsumers.
-//===--===//
-
-void ento::createPlistHTMLDiagnosticConsumer(
-AnalyzerOptions &AnalyzerOpts, PathDiagnosticConsumers &C,
-const std::string &prefix, const Preprocessor &PP,
-const cross_tu::CrossTranslationUnitContext &CTU) {
-  createHTMLDiagnosticConsumer(
-  AnalyzerOpts, C, std::string(llvm::sys::path::parent_path(prefix)), PP,
-  CTU);
-  createPlistMultiFileDiagnosticConsumer(AnalyzerOpts, C, prefix, PP, CTU);
-}
-
-void ento::createTextPathDiagnosticConsumer(
-AnalyzerOptions &AnalyzerOpts, PathDiagnosticConsumers &C,
-const std::string &Prefix, const clang::Preprocessor &PP,
-const cross_tu::CrossTranslationUnitContext &CTU) {
-  llvm_unreachable("'text' consumer should be enabled on ClangDiags");
-}
-
-namespace {
-class ClangDiagPathDiagConsumer : public PathDiagnosticConsumer {
-  DiagnosticsEngine &Diag;
-  bool IncludePath = false, ShouldEmitAsError = false, FixitsAsRemarks = false;
-
-public:
-  ClangDiagPathDiagConsumer(DiagnosticsEngine &Diag)
-  : Diag(Diag) {}
-  ~ClangDiagPathDiagConsumer() override {}
-  StringRef getName() const override { return "ClangDiags"; }
-
-  bool supportsLogicalOpControlFlow() const override { return true; }
-  bool supportsCrossFileDiagnostics() const override { return true; }
-
-  PathGenerationScheme getGenerationScheme() const override {
-return IncludePath ? Minimal : None;
-  }
-
-  void enablePaths() { IncludePath = true; }
-  void enableWerror() { ShouldEmitAsError = true; }
-  void enableFixitsAsRemarks() { FixitsAsRemarks = true; }
-
-  void FlushDiagnosticsImpl(std::vector &Diags,
-FilesMade *filesMade) override {
-unsigned WarnID =
-ShouldEmitAsError
-? Diag.getCustomDiagID(DiagnosticsEngine::Error, "%0")
-: Diag.getCustomDiagID(DiagnosticsEngine::Warning, "%0");
-unsigned NoteID = Diag.getCustomDiagID(DiagnosticsEngine::Note, "%0");
-unsigned RemarkID = Diag.getCustomDiagID(DiagnosticsEngine::Remark, "%0");
-
-auto reportPiece =
-[&](unsigned ID, SourceLocation Loc, StringRef String,
-ArrayRef Ranges, ArrayRef Fixits) {
-  if (!FixitsAsRemarks) {
-Diag.Report(Loc, ID) << String << Ranges << Fixits;
-  } else {
-Diag.Report(Loc, ID) << String << Ranges;
-for (const FixItHint &Hint : Fixits) {
-  SourceManager &SM = Diag.getSourceManager();
-  llvm::SmallString<128> Str;
-  llvm::raw_svector_ostream OS(Str);
-  // FIXME: Add support for InsertFromRange and
-  // BeforePreviousInsertion.
-  assert(!Hint.InsertFromRange.isValid() && "Not implemented yet!");
-  assert(!Hint.BeforePreviousInsertions && "Not implemented yet!");
-  OS << SM.getSpellingColumnNumber(Hint.RemoveRange.getBegin())
- << "-" << SM.getSpellingColumnNumber(Hint.RemoveRange.getEnd())
- << ": '" << Hint.CodeToInsert << "'";
-  Diag.Report(Loc, RemarkID) << OS.str();
-}
-  }
-};
-
-for (std::vector::iterator I = Diags.begin(),
- E = Diags.end();
- I != E; ++I) {
-  const PathDiagnostic *PD = *I;
-  reportPiece(WarnID, PD->getLocation().asLocation(),
-  PD->getShortDescription(), PD->path.back()->getRanges(),
-  PD->path.back()->getFixits());
-
-  // First, add extra notes, even if paths should not be included.
-  for (const auto &Piece : PD->path) {
-if (!isa(Piece.get()))
-  continue;
-
-reportPiece(NoteID, Piece->getLocation().asLocation(),
-Piece->getString(), Piece->getRanges(), Piece->getFixits());
-  }
-
-  if (!IncludePath)
-continue;
-
- 

[PATCH] D76541: [clang-tidy][NFC] Add missing check group docs and order entries

2020-03-23 Thread Whisperity via Phabricator via cfe-commits
whisperity added a comment.

In D76541#1935163 , @njames93 wrote:

> Forgive me if I'm wrong, but these kinds of changes typically don't require a 
> review.


Ah, pardon me. This is the first time I'm touching the insides of Tidy.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76541



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


[PATCH] D75747: [clang-format] Correct indentation for `[key] = value,` entries in C++ object initialisers

2020-03-23 Thread Jonathan B Coe via Phabricator via cfe-commits
jbcoe added a comment.

That's right David, this typo was fixed in a reverted and re-applied commit: 
https://reviews.llvm.org/D75856, https://reviews.llvm.org/D75747


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D75747



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


[PATCH] D76541: [clang-tidy][NFC] Add missing check group docs and order entries

2020-03-23 Thread Whisperity via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGdf5fa4873976: [clang-tidy][NFC] Add missing check group docs 
and order entries (authored by whisperity).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76541

Files:
  clang-tools-extra/clang-tidy/ClangTidyForceLinker.h
  clang-tools-extra/docs/clang-tidy/index.rst

Index: clang-tools-extra/docs/clang-tidy/index.rst
===
--- clang-tools-extra/docs/clang-tidy/index.rst
+++ clang-tools-extra/docs/clang-tidy/index.rst
@@ -62,11 +62,13 @@
 ``boost-`` Checks related to Boost library.
 ``bugprone-``  Checks that target bugprone code constructs.
 ``cert-``  Checks related to CERT Secure Coding Guidelines.
-``cppcoreguidelines-`` Checks related to C++ Core Guidelines.
 ``clang-analyzer-``Clang Static Analyzer checks.
+``cppcoreguidelines-`` Checks related to C++ Core Guidelines.
+``darwin-``Checks related to Darwin coding conventions.
 ``fuchsia-``   Checks related to Fuchsia coding conventions.
 ``google-``Checks related to Google coding conventions.
 ``hicpp-`` Checks related to High Integrity C++ Coding Standard.
+``linuxkernel-``   Checks related to the Linux Kernel coding conventions.
 ``llvm-``  Checks related to the LLVM coding conventions.
 ``llvmlibc-``  Checks related to the LLVM-libc coding standards.
 ``misc-``  Checks that we didn't have a better category for.
Index: clang-tools-extra/clang-tidy/ClangTidyForceLinker.h
===
--- clang-tools-extra/clang-tidy/ClangTidyForceLinker.h
+++ clang-tools-extra/clang-tidy/ClangTidyForceLinker.h
@@ -15,16 +15,16 @@
 namespace clang {
 namespace tidy {
 
-// This anchor is used to force the linker to link the CERTModule.
-extern volatile int CERTModuleAnchorSource;
-static int LLVM_ATTRIBUTE_UNUSED CERTModuleAnchorDestination =
-CERTModuleAnchorSource;
-
 // This anchor is used to force the linker to link the AbseilModule.
 extern volatile int AbseilModuleAnchorSource;
 static int LLVM_ATTRIBUTE_UNUSED AbseilModuleAnchorDestination =
 AbseilModuleAnchorSource;
 
+// This anchor is used to force the linker to link the AndroidModule.
+extern volatile int AndroidModuleAnchorSource;
+static int LLVM_ATTRIBUTE_UNUSED AndroidModuleAnchorDestination =
+AndroidModuleAnchorSource;
+
 // This anchor is used to force the linker to link the BoostModule.
 extern volatile int BoostModuleAnchorSource;
 static int LLVM_ATTRIBUTE_UNUSED BoostModuleAnchorDestination =
@@ -35,20 +35,10 @@
 static int LLVM_ATTRIBUTE_UNUSED BugproneModuleAnchorDestination =
 BugproneModuleAnchorSource;
 
-// This anchor is used to force the linker to link the LinuxKernelModule.
-extern volatile int LinuxKernelModuleAnchorSource;
-static int LLVM_ATTRIBUTE_UNUSED LinuxKernelModuleAnchorDestination =
-LinuxKernelModuleAnchorSource;
-
-// This anchor is used to force the linker to link the LLVMModule.
-extern volatile int LLVMModuleAnchorSource;
-static int LLVM_ATTRIBUTE_UNUSED LLVMModuleAnchorDestination =
-LLVMModuleAnchorSource;
-
-// This anchor is used to force the linker to link the LLVMLibcModule.
-extern volatile int LLVMLibcModuleAnchorSource;
-static int LLVM_ATTRIBUTE_UNUSED LLVMLibcModuleAnchorDestination =
-LLVMLibcModuleAnchorSource;
+// This anchor is used to force the linker to link the CERTModule.
+extern volatile int CERTModuleAnchorSource;
+static int LLVM_ATTRIBUTE_UNUSED CERTModuleAnchorDestination =
+CERTModuleAnchorSource;
 
 // This anchor is used to force the linker to link the CppCoreGuidelinesModule.
 extern volatile int CppCoreGuidelinesModuleAnchorSource;
@@ -70,10 +60,25 @@
 static int LLVM_ATTRIBUTE_UNUSED GoogleModuleAnchorDestination =
 GoogleModuleAnchorSource;
 
-// This anchor is used to force the linker to link the AndroidModule.
-extern volatile int AndroidModuleAnchorSource;
-static int LLVM_ATTRIBUTE_UNUSED AndroidModuleAnchorDestination =
-AndroidModuleAnchorSource;
+// This anchor is used to force the linker to link the HICPPModule.
+extern volatile int HICPPModuleAnchorSource;
+static int LLVM_ATTRIBUTE_UNUSED HICPPModuleAnchorDestination =
+HICPPModuleAnchorSource;
+
+// This anchor is used to force the linker to link the LinuxKernelModule.
+extern volatile int LinuxKernelModuleAnchorSource;
+static int LLVM_ATTRIBUTE_UNUSED LinuxKernelModuleAnchorDestination =
+LinuxKernelModuleAnchorSource;
+
+// This anchor is used to force the linker to link the LLVMModule.
+extern volatile int LLVMModuleAnchorSource;
+static int LLVM_ATTRIBUTE_UNUSED LLVMModuleAnchorDestination =
+LLVMModuleAnchorSource;
+
+// This anchor is used to force the linker to link the LLVMLibcModule.
+extern volatile int LLVMLibcMod

[PATCH] D76545: [clang-tidy] Add a new check group 'experimental-'

2020-03-23 Thread Whisperity via Phabricator via cfe-commits
whisperity added a comment.

@aaron.ballman @njames93 Should I write up a pitch mail to cfe-dev about this?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76545



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


[clang] 6081ccf - Apply function attributes through array declarators

2020-03-23 Thread Momchil Velikov via cfe-commits

Author: Momchil Velikov
Date: 2020-03-23T11:03:13Z
New Revision: 6081ccf4a3b6289717c8ae558ac210c36ddcbfbe

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

LOG: Apply function attributes through array declarators

There's inconsistency in handling array types between the
`distributeFunctionTypeAttrXXX` functions and the
`FunctionTypeUnwrapper` in `SemaType.cpp`.

This patch lets `FunctionTypeUnwrapper` apply function type attributes
through array types.

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

Added: 
clang/test/CodeGen/attr-noreturn.c

Modified: 
clang/lib/Sema/SemaType.cpp
clang/test/Sema/attr-noreturn.c

Removed: 




diff  --git a/clang/lib/Sema/SemaType.cpp b/clang/lib/Sema/SemaType.cpp
index 534178388048..356b51e439a6 100644
--- a/clang/lib/Sema/SemaType.cpp
+++ b/clang/lib/Sema/SemaType.cpp
@@ -6502,6 +6502,7 @@ namespace {
   Desugar,
   Attributed,
   Parens,
+  Array,
   Pointer,
   BlockPointer,
   Reference,
@@ -6522,6 +6523,10 @@ namespace {
 } else if (isa(Ty)) {
   T = cast(Ty)->getInnerType();
   Stack.push_back(Parens);
+} else if (isa(Ty) || isa(Ty) ||
+   isa(Ty)) {
+  T = cast(Ty)->getElementType();
+  Stack.push_back(Array);
 } else if (isa(Ty)) {
   T = cast(Ty)->getPointeeType();
   Stack.push_back(Pointer);
@@ -6599,6 +6604,27 @@ namespace {
   case MacroQualified:
 return wrap(C, cast(Old)->getUnderlyingType(), I);
 
+  case Array: {
+if (const auto *CAT = dyn_cast(Old)) {
+  QualType New = wrap(C, CAT->getElementType(), I);
+  return C.getConstantArrayType(New, CAT->getSize(), 
CAT->getSizeExpr(),
+CAT->getSizeModifier(),
+CAT->getIndexTypeCVRQualifiers());
+}
+
+if (const auto *VAT = dyn_cast(Old)) {
+  QualType New = wrap(C, VAT->getElementType(), I);
+  return C.getVariableArrayType(
+  New, VAT->getSizeExpr(), VAT->getSizeModifier(),
+  VAT->getIndexTypeCVRQualifiers(), VAT->getBracketsRange());
+}
+
+const auto *IAT = cast(Old);
+QualType New = wrap(C, IAT->getElementType(), I);
+return C.getIncompleteArrayType(New, IAT->getSizeModifier(),
+IAT->getIndexTypeCVRQualifiers());
+  }
+
   case Pointer: {
 QualType New = wrap(C, cast(Old)->getPointeeType(), I);
 return C.getPointerType(New);

diff  --git a/clang/test/CodeGen/attr-noreturn.c 
b/clang/test/CodeGen/attr-noreturn.c
new file mode 100644
index ..b420edfc0595
--- /dev/null
+++ b/clang/test/CodeGen/attr-noreturn.c
@@ -0,0 +1,10 @@
+// RUN: %clang_cc1 -S -emit-llvm %s -o - | FileCheck %s
+
+typedef void (*fptrs_t[4])(void);
+fptrs_t p __attribute__((noreturn));
+
+void __attribute__((noreturn)) f() {
+  p[0]();
+}
+// CHECK: call
+// CHECK-NEXT: unreachable

diff  --git a/clang/test/Sema/attr-noreturn.c b/clang/test/Sema/attr-noreturn.c
index dab571064a22..3d1e8d7f4079 100644
--- a/clang/test/Sema/attr-noreturn.c
+++ b/clang/test/Sema/attr-noreturn.c
@@ -42,3 +42,34 @@ __attribute__((noreturn)) void f(__attribute__((noreturn)) 
void (*x)(void)) {
 }
 
 typedef void (*Fun)(void) __attribute__ ((noreturn(2))); // expected-error 
{{'noreturn' attribute takes no arguments}}
+
+
+typedef void fn_t(void);
+
+fn_t *fp __attribute__((noreturn));
+void __attribute__((noreturn)) f6(int i) {
+  fp();
+}
+
+fn_t *fps[4] __attribute__((noreturn));
+void __attribute__((noreturn)) f7(int i) {
+  fps[i]();
+}
+
+extern fn_t *ifps[] __attribute__((noreturn));
+void __attribute__((noreturn)) f8(int i) {
+  ifps[i]();
+}
+
+void __attribute__((noreturn)) f9(int n) {
+  extern int g9(int, fn_t **);
+  fn_t *fp[n] __attribute__((noreturn));
+  int i = g9(n, fp);
+  fp[i]();
+}
+
+typedef fn_t *fptrs_t[4];
+fptrs_t ps __attribute__((noreturn));
+void __attribute__((noreturn)) f10(int i) {
+  ps[i]();
+}



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


[PATCH] D74387: [SYCL] Defer __float128 type usage diagnostics

2020-03-23 Thread Mariya Podchishchaeva via Phabricator via cfe-commits
Fznamznon updated this revision to Diff 251982.
Fznamznon edited the summary of this revision.
Fznamznon added a comment.

Fix the test by adding the target with __float128 support and make sure that
no diagnostic are emitted.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D74387

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Sema/Sema.h
  clang/lib/Sema/CMakeLists.txt
  clang/lib/Sema/SemaAvailability.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaSYCL.cpp
  clang/lib/Sema/SemaType.cpp
  clang/test/SemaSYCL/float128.cpp

Index: clang/test/SemaSYCL/float128.cpp
===
--- /dev/null
+++ clang/test/SemaSYCL/float128.cpp
@@ -0,0 +1,92 @@
+// RUN: %clang_cc1 -triple spir64 -fsycl -fsycl-is-device -verify -fsyntax-only %s
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -fsycl -fsycl-is-device -fsyntax-only %s
+
+template 
+class Z {
+public:
+  // TODO: If T is __float128 This might be a problem
+  T field;
+  //expected-error@+1 2{{'__float128' is not supported on this target}}
+  __float128 field1;
+};
+
+void host_ok(void) {
+  __float128 A;
+  int B = sizeof(__float128);
+  Z<__float128> C;
+  C.field1 = A;
+}
+
+void usage() {
+  //expected-error@+1 5{{'__float128' is not supported on this target}}
+  __float128 A;
+  Z<__float128> C;
+  //expected-error@+2 {{'A' is unavailable}}
+  //expected-error@+1 {{'field1' is unavailable}}
+  C.field1 = A;
+  //expected-error@+1 {{'A' is unavailable}}
+  decltype(A) D;
+
+  //expected-error@+1 {{'A' is unavailable}}
+  auto foo1 = [=]() {
+//expected-error@+1 {{'__float128' is not supported on this target}}
+__float128 AA;
+//expected-error@+1 {{'A' is unavailable}}
+auto BB = A;
+BB += 1;
+  };
+
+  //expected-note@+1 {{called by 'usage'}}
+  foo1();
+}
+
+template 
+void foo2(){};
+
+//expected-error@+1 {{'__float128 (__float128)' is not supported on this target}}
+__float128 foo(__float128 P) { return P; }
+
+template 
+__attribute__((sycl_kernel)) void kernel(Func kernelFunc) {
+  //expected-note@+1 5{{called by 'kernel}}
+  kernelFunc();
+  //expected-error@+1 {{'__float128' is not supported on this target}}
+  __float128 A;
+}
+
+int main() {
+  //expected-error@+1 2{{'__float128' is not supported on this target}}
+  __float128 CapturedToDevice = 1;
+  host_ok();
+  kernel([=]() {
+//expected-error@+1 {{'CapturedToDevice' is unavailable}}
+decltype(CapturedToDevice) D;
+//expected-error@+1 {{'CapturedToDevice' is unavailable}}
+auto C = CapturedToDevice;
+//expected-error@+1 {{'__float128' is not supported on this target}}
+__float128 ;
+Z<__float128> S;
+//expected-error@+1 {{'field1' is unavailable}}
+S.field1 += 1;
+S.field = 1;
+  });
+
+  kernel([=]() {
+//expected-note@+1 2{{called by 'operator()'}}
+usage();
+// expected-error@+1 2{{'__float128' is not supported on this target}}
+__float128 ;
+// expected-error@+2 {{'' is unavailable}}
+// expected-error@+1 {{'foo' is unavailable}}
+auto A = foo();
+  });
+
+  kernel([=]() {
+Z<__float128> S;
+foo2<__float128>();
+// TODO: this shouldn't be diagnosed
+// expected-error@+1 {{'__float128' is not supported on this target}}
+int E = sizeof(__float128);
+  });
+  return 0;
+}
Index: clang/lib/Sema/SemaType.cpp
===
--- clang/lib/Sema/SemaType.cpp
+++ clang/lib/Sema/SemaType.cpp
@@ -1516,10 +1516,21 @@
 break;
   case DeclSpec::TST_float128:
 if (!S.Context.getTargetInfo().hasFloat128Type() &&
+!S.getLangOpts().SYCLIsDevice &&
 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice))
   S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
 << "__float128";
 Result = Context.Float128Ty;
+if (!S.Context.getTargetInfo().hasFloat128Type() &&
+S.getLangOpts().SYCLIsDevice &&
+S.DelayedDiagnostics.shouldDelayDiagnostics()) {
+  S.DelayedDiagnostics.add(sema::DelayedDiagnostic::makeForbiddenType(
+  DS.getTypeSpecTypeLoc(), diag::err_type_unsupported, Result,
+  /*ignored*/ 0));
+  S.SYCLDiagIfDeviceCode(DS.getTypeSpecTypeLoc(),
+ diag::err_type_unsupported)
+  << Result;
+}
 break;
   case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
 break;
Index: clang/lib/Sema/SemaSYCL.cpp
===
--- /dev/null
+++ clang/lib/Sema/SemaSYCL.cpp
@@ -0,0 +1,63 @@
+//===- SemaSYCL.cpp - Semantic Analysis for SYCL constructs ---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt 

[PATCH] D76597: [clang-format] Reflow long C# generic type constraints correctly

2020-03-23 Thread Jonathan B Coe via Phabricator via cfe-commits
jbcoe created this revision.
jbcoe added a reviewer: krasimir.
jbcoe added a project: clang-format.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Align sequential generic type constraints on a type.

Indent sequential generic type constraints on different types as continuations.

Do not allow '(' and '<' within a generic type constraint to open new scopes.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D76597

Files:
  clang/lib/Format/ContinuationIndenter.cpp
  clang/lib/Format/ContinuationIndenter.h
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/FormatTestCSharp.cpp

Index: clang/unittests/Format/FormatTestCSharp.cpp
===
--- clang/unittests/Format/FormatTestCSharp.cpp
+++ clang/unittests/Format/FormatTestCSharp.cpp
@@ -687,6 +687,14 @@
   where T : IMyInterface { doThing(); }
 })",
Style);
+
+  verifyFormat(R"(//
+class ItemFactory
+where T : new(),
+  IAnInterface,
+  IAnotherInterface,
+  IAnotherInterfaceStill {})",
+   Style);
 }
 
 } // namespace format
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -3620,6 +3620,9 @@
 if (Left.isOneOf(TT_CSharpNamedArgumentColon, TT_AttributeColon) ||
 Right.isOneOf(TT_CSharpNamedArgumentColon, TT_AttributeColon))
   return false;
+// Only break after commas for generic type constraints.
+if (Line.First->is(TT_CSharpGenericTypeConstraint))
+  return Left.is(TT_CSharpGenericTypeConstraintComma);
   } else if (Style.Language == FormatStyle::LK_Java) {
 if (Left.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
  Keywords.kw_implements))
Index: clang/lib/Format/ContinuationIndenter.h
===
--- clang/lib/Format/ContinuationIndenter.h
+++ clang/lib/Format/ContinuationIndenter.h
@@ -208,7 +208,8 @@
 LastOperatorWrapped(true), ContainsLineBreak(false),
 ContainsUnwrappedBuilder(false), AlignColons(true),
 ObjCSelectorNameFound(false), HasMultipleNestedBlocks(false),
-NestedBlockInlined(false), IsInsideObjCArrayLiteral(false) {}
+NestedBlockInlined(false), IsInsideObjCArrayLiteral(false),
+IsCSharpGenericTypeConstraint(false) {}
 
   /// \brief The token opening this parenthesis level, or nullptr if this level
   /// is opened by fake parenthesis.
@@ -329,6 +330,8 @@
   /// array literal.
   bool IsInsideObjCArrayLiteral : 1;
 
+  bool IsCSharpGenericTypeConstraint : 1;
+
   bool operator<(const ParenState &Other) const {
 if (Indent != Other.Indent)
   return Indent < Other.Indent;
@@ -366,6 +369,8 @@
   return ContainsUnwrappedBuilder;
 if (NestedBlockInlined != Other.NestedBlockInlined)
   return NestedBlockInlined;
+if (IsCSharpGenericTypeConstraint != Other.IsCSharpGenericTypeConstraint)
+  return IsCSharpGenericTypeConstraint;
 return false;
   }
 };
Index: clang/lib/Format/ContinuationIndenter.cpp
===
--- clang/lib/Format/ContinuationIndenter.cpp
+++ clang/lib/Format/ContinuationIndenter.cpp
@@ -634,6 +634,7 @@
 State.Stack.back().NoLineBreak = true;
 
   if (Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign &&
+  !State.Stack.back().IsCSharpGenericTypeConstraint &&
   Previous.opensScope() && Previous.isNot(TT_ObjCMethodExpr) &&
   (Current.isNot(TT_LineComment) || Previous.BlockKind == BK_BracedInit))
 State.Stack.back().Indent = State.Column + Spaces;
@@ -715,6 +716,8 @@
   } else if (Previous.is(TT_InheritanceColon)) {
 State.Stack.back().Indent = State.Column;
 State.Stack.back().LastSpace = State.Column;
+  } else if (Current.is(TT_CSharpGenericTypeConstraintColon)) {
+State.Stack.back().ColonPos = State.Column;
   } else if (Previous.opensScope()) {
 // If a function has a trailing call, indent all parameters from the
 // opening parenthesis. This avoids confusing indents like:
@@ -924,7 +927,13 @@
 unsigned ContinuationIndenter::getNewLineColumn(const LineState &State) {
   if (!State.NextToken || !State.NextToken->Previous)
 return 0;
+
   FormatToken &Current = *State.NextToken;
+
+  if (State.Stack.back().IsCSharpGenericTypeConstraint &&
+  Current.isNot(TT_CSharpGenericTypeConstraint))
+return State.Stack.back().ColonPos + 2;
+
   const FormatToken &Previous = *Current.Previous;
   // If we are continuing an expression, we want to use the continuation indent.
   unsigned ContinuationIndent =
@@ -1106,9 +1115,11 @@
   assert(State.Stack.size());
   const FormatToken &Current = *State.NextToken;
 
+  if (Current.is(TT_CSharpGenericTypeConstraint))
+State.Stack.back().IsCSharpGenericTypeConstraint = true;

[PATCH] D75109: Apply function attributes through array declarators

2020-03-23 Thread Momchil Velikov via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG6081ccf4a3b6: Apply function attributes through array 
declarators (authored by chill).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D75109

Files:
  clang/lib/Sema/SemaType.cpp
  clang/test/CodeGen/attr-noreturn.c
  clang/test/Sema/attr-noreturn.c

Index: clang/test/Sema/attr-noreturn.c
===
--- clang/test/Sema/attr-noreturn.c
+++ clang/test/Sema/attr-noreturn.c
@@ -42,3 +42,34 @@
 }
 
 typedef void (*Fun)(void) __attribute__ ((noreturn(2))); // expected-error {{'noreturn' attribute takes no arguments}}
+
+
+typedef void fn_t(void);
+
+fn_t *fp __attribute__((noreturn));
+void __attribute__((noreturn)) f6(int i) {
+  fp();
+}
+
+fn_t *fps[4] __attribute__((noreturn));
+void __attribute__((noreturn)) f7(int i) {
+  fps[i]();
+}
+
+extern fn_t *ifps[] __attribute__((noreturn));
+void __attribute__((noreturn)) f8(int i) {
+  ifps[i]();
+}
+
+void __attribute__((noreturn)) f9(int n) {
+  extern int g9(int, fn_t **);
+  fn_t *fp[n] __attribute__((noreturn));
+  int i = g9(n, fp);
+  fp[i]();
+}
+
+typedef fn_t *fptrs_t[4];
+fptrs_t ps __attribute__((noreturn));
+void __attribute__((noreturn)) f10(int i) {
+  ps[i]();
+}
Index: clang/test/CodeGen/attr-noreturn.c
===
--- /dev/null
+++ clang/test/CodeGen/attr-noreturn.c
@@ -0,0 +1,10 @@
+// RUN: %clang_cc1 -S -emit-llvm %s -o - | FileCheck %s
+
+typedef void (*fptrs_t[4])(void);
+fptrs_t p __attribute__((noreturn));
+
+void __attribute__((noreturn)) f() {
+  p[0]();
+}
+// CHECK: call
+// CHECK-NEXT: unreachable
Index: clang/lib/Sema/SemaType.cpp
===
--- clang/lib/Sema/SemaType.cpp
+++ clang/lib/Sema/SemaType.cpp
@@ -6502,6 +6502,7 @@
   Desugar,
   Attributed,
   Parens,
+  Array,
   Pointer,
   BlockPointer,
   Reference,
@@ -6522,6 +6523,10 @@
 } else if (isa(Ty)) {
   T = cast(Ty)->getInnerType();
   Stack.push_back(Parens);
+} else if (isa(Ty) || isa(Ty) ||
+   isa(Ty)) {
+  T = cast(Ty)->getElementType();
+  Stack.push_back(Array);
 } else if (isa(Ty)) {
   T = cast(Ty)->getPointeeType();
   Stack.push_back(Pointer);
@@ -6599,6 +6604,27 @@
   case MacroQualified:
 return wrap(C, cast(Old)->getUnderlyingType(), I);
 
+  case Array: {
+if (const auto *CAT = dyn_cast(Old)) {
+  QualType New = wrap(C, CAT->getElementType(), I);
+  return C.getConstantArrayType(New, CAT->getSize(), CAT->getSizeExpr(),
+CAT->getSizeModifier(),
+CAT->getIndexTypeCVRQualifiers());
+}
+
+if (const auto *VAT = dyn_cast(Old)) {
+  QualType New = wrap(C, VAT->getElementType(), I);
+  return C.getVariableArrayType(
+  New, VAT->getSizeExpr(), VAT->getSizeModifier(),
+  VAT->getIndexTypeCVRQualifiers(), VAT->getBracketsRange());
+}
+
+const auto *IAT = cast(Old);
+QualType New = wrap(C, IAT->getElementType(), I);
+return C.getIncompleteArrayType(New, IAT->getSizeModifier(),
+IAT->getIndexTypeCVRQualifiers());
+  }
+
   case Pointer: {
 QualType New = wrap(C, cast(Old)->getPointeeType(), I);
 return C.getPointerType(New);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: [clang] d9b9621 - Reland D73534: [DebugInfo] Enable the debug entry values feature by default

2020-03-23 Thread Djordje via cfe-commits
(+ CCing some debug info folks as well)

Hi David,

OK, I agree, my apologize.

The patch enables the whole feature by default and removes the experimental 
option that has been used during the implementation.
We tested the code (and the assertions regarding the feature itself) by using 
the experimental option on some large projects, but since the feature became 
that huge (and new patches regarding the feature are coming every day -- which 
is nice), it is impossible to test everything.

The Debug Entry Values implementation grows these days, and new functionalities 
comes in, but it has all been tested with the experimental option, so 
committing this particular patch imposes all the cases developers oversighted 
during the implementation.

My impression is that, before adding new functionalities to the feature, we 
should make sure the D73534 is stable and gets stuck. We should have done it 
before, but I think that is the lesson learned here.

In general, experimental options are very good up to the some point, but if the 
feature being tested grows a lot, a "breakpoint" should be set up and take care 
the experimental option is removed and the code is well tested on the real 
cases out there, and then moving to the next stage of the implementation.

Besides this, CISCO is using the feature ON by default for some time, and we 
have good experience there. This really improves the debugging user experience 
while debugging the "optimized" code.

Best regards,
Djordje

On 22.3.20. 16:30, David Blaikie wrote:
> Also, this patch was reverted and recommitted several times (more than I 
> think would be ideal) - please include more details in the commit message 
> about what went wrong, what was fixed, what testing was missed in the first 
> place and done in subsequent precommit validation (& is there anything more 
> broadly we could learn from this patches story to avoid this kind of 
> revert/recommit repetition in the future?)
>
> On Sat, Mar 21, 2020 at 8:13 PM David Blaikie  > wrote:
>
> Please include the "Differential Revision" line so that Phab picks up 
> commits like this and ties them into the review (& also makes it conveniently 
> clickable to jump from the commit mail to the review)
>
> On Thu, Mar 19, 2020 at 5:58 AM Djordje Todorovic via cfe-commits 
> mailto:cfe-commits@lists.llvm.org>> wrote:
>
>
> Author: Djordje Todorovic
> Date: 2020-03-19T13:57:30+01:00
> New Revision: d9b962100942c71a4c26debaa716f7ab0c4ea8a1
>
> URL: 
> https://github.com/llvm/llvm-project/commit/d9b962100942c71a4c26debaa716f7ab0c4ea8a1
> DIFF: 
> https://github.com/llvm/llvm-project/commit/d9b962100942c71a4c26debaa716f7ab0c4ea8a1.diff
>
> LOG: Reland D73534: [DebugInfo] Enable the debug entry values feature 
> by default
>
> The issue that was causing the build failures was fixed with the 
> D76164.
>
> Added:
>     llvm/test/DebugInfo/X86/no-entry-values-with-O0.ll
>
> Modified:
>     clang/include/clang/Basic/CodeGenOptions.def
>     clang/include/clang/Driver/CC1Options.td
>     clang/lib/CodeGen/BackendUtil.cpp
>     clang/lib/CodeGen/CGDebugInfo.cpp
>     clang/lib/Frontend/CompilerInvocation.cpp
>     clang/test/CodeGen/debug-info-extern-call.c
>     clang/test/CodeGenCXX/dbg-info-all-calls-described.cpp
>     lldb/packages/Python/lldbsuite/test/decorators.py
>     
> lldb/test/API/functionalities/param_entry_vals/basic_entry_values_x86_64/Makefile
>     llvm/include/llvm/Target/TargetMachine.h
>     llvm/include/llvm/Target/TargetOptions.h
>     llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp
>     llvm/lib/CodeGen/AsmPrinter/DwarfDebug.h
>     llvm/lib/CodeGen/CommandFlags.cpp
>     llvm/lib/CodeGen/LiveDebugValues.cpp
>     llvm/lib/CodeGen/TargetOptionsImpl.cpp
>     llvm/lib/Target/AArch64/AArch64TargetMachine.cpp
>     llvm/lib/Target/ARM/ARMTargetMachine.cpp
>     llvm/lib/Target/X86/X86TargetMachine.cpp
>     llvm/test/CodeGen/MIR/Hexagon/bundled-call-site-info.mir
>     llvm/test/CodeGen/MIR/X86/call-site-info-error4.mir
>     llvm/test/CodeGen/X86/call-site-info-output.ll
>     llvm/test/DebugInfo/AArch64/dbgcall-site-float-entry-value.ll
>     llvm/test/DebugInfo/MIR/AArch64/dbgcall-site-orr-moves.mir
>     llvm/test/DebugInfo/MIR/ARM/call-site-info-vmovd.mir
>     llvm/test/DebugInfo/MIR/ARM/call-site-info-vmovs.mir
>     llvm/test/DebugInfo/MIR/ARM/dbgcall-site-propagated-value.mir
>     
> llvm/test/DebugInfo/MIR/Hexagon/dbgcall-site-instr-before-bundled-call.mir
>     
> llvm/test/DebugInfo/MIR/Hexagon/live-debug-values-bundled-entry-values.mir
>     llvm/test/DebugInfo/MIR/SystemZ/call-site-lzer.mir
>     llvm/test/DebugInfo/MIR/X86/DW_OP_entr

[PATCH] D76551: [Alignment][NFC] Use TargetFrameLowering::getStackAlign()

2020-03-23 Thread Guillaume Chatelet via Phabricator via cfe-commits
gchatelet updated this revision to Diff 251969.
gchatelet marked 3 inline comments as done.
gchatelet added a comment.
Herald added subscribers: libc-commits, openmp-commits, libcxx-commits, 
cfe-commits, Joonsoo, kerbowa, liufengdb, aartbik, lucyrfox, mgester, 
arpith-jacob, csigg, nicolasvasilache, antiagainst, shauheen, burmako, 
jpienaar, rriddle, mehdi_amini, dmgreen, rupprecht, arphaman, dexonsmith, 
steven_wu, mgorny, nhaehnle, jvesely, emaste, jholewinski.
Herald added a reviewer: bollu.
Herald added a reviewer: espindola.
Herald added a reviewer: alexshap.
Herald added a reviewer: jhenderson.
Herald added a reviewer: nicolasvasilache.
Herald added a reviewer: herhut.
Herald added a reviewer: rriddle.
Herald added a reviewer: aartbik.
Herald added projects: clang, libc++, OpenMP, libc-project.
Herald added a reviewer: libc++.

- inline variable
- Address comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76551

Files:
  clang-tools-extra/docs/clang-rename.rst
  clang/docs/LibASTImporter.rst
  clang/docs/ReleaseNotes.rst
  clang/docs/analyzer/checkers.rst
  clang/include/clang/AST/OpenMPClause.h
  clang/include/clang/Driver/ToolChain.h
  clang/lib/CodeGen/EHScopeStack.h
  clang/lib/Driver/ToolChain.cpp
  clang/lib/Driver/ToolChains/Cuda.cpp
  clang/lib/Driver/ToolChains/Darwin.cpp
  clang/lib/Driver/ToolChains/HIP.cpp
  libc/CMakeLists.txt
  libc/config/linux/api.td
  libc/lib/CMakeLists.txt
  libc/spec/stdc.td
  libc/src/signal/linux/CMakeLists.txt
  libc/src/signal/linux/signal.cpp
  libc/src/signal/signal.h
  libc/test/src/signal/CMakeLists.txt
  libc/test/src/signal/signal_test.cpp
  libc/utils/UnitTest/Test.cpp
  libc/utils/UnitTest/Test.h
  libcxx/docs/TestingLibcxx.rst
  libcxx/docs/UsingLibcxx.rst
  libcxx/docs/index.rst
  libunwind/docs/BuildingLibunwind.rst
  libunwind/docs/index.rst
  lld/docs/AtomLLD.rst
  lld/docs/NewLLD.rst
  lld/docs/design.rst
  lld/docs/development.rst
  lld/docs/getting_started.rst
  lld/docs/index.rst
  llvm/docs/AMDGPUUsage.rst
  llvm/docs/AliasAnalysis.rst
  llvm/docs/CMake.rst
  llvm/docs/CommandGuide/llvm-lipo.rst
  llvm/docs/CommandGuide/llvm-objcopy.rst
  llvm/docs/CommandGuide/llvm-objdump.rst
  llvm/docs/CommandGuide/llvm-size.rst
  llvm/docs/CommandGuide/llvm-strings.rst
  llvm/docs/CommandGuide/llvm-strip.rst
  llvm/docs/CompileCudaWithLLVM.rst
  llvm/docs/Docker.rst
  llvm/docs/FAQ.rst
  llvm/docs/Frontend/PerformanceTips.rst
  llvm/docs/GettingStarted.rst
  llvm/docs/GettingStartedVS.rst
  llvm/docs/GlobalISel/GMIR.rst
  llvm/docs/GlobalISel/IRTranslator.rst
  llvm/docs/GlobalISel/KnownBits.rst
  llvm/docs/HistoricalNotes/2007-OriginalClangReadme.txt
  llvm/docs/HowToCrossCompileLLVM.rst
  llvm/docs/HowToSetUpLLVMStyleRTTI.rst
  llvm/docs/HowToSubmitABug.rst
  llvm/docs/LLVMBuild.txt
  llvm/docs/LangRef.rst
  llvm/docs/Lexicon.rst
  llvm/docs/LibFuzzer.rst
  llvm/docs/LoopTerminology.rst
  llvm/docs/MarkdownQuickstartTemplate.md
  llvm/docs/MergeFunctions.rst
  llvm/docs/Packaging.rst
  llvm/docs/ProgrammersManual.rst
  llvm/docs/Proposals/GitHubMove.rst
  llvm/docs/README.txt
  llvm/docs/Reference.rst
  llvm/docs/ReleaseProcess.rst
  llvm/docs/SphinxQuickstartTemplate.rst
  llvm/docs/TableGen/index.rst
  llvm/docs/TestSuiteGuide.md
  llvm/docs/TestingGuide.rst
  llvm/docs/TypeMetadata.rst
  llvm/docs/UserGuides.rst
  llvm/docs/Vectorizers.rst
  llvm/docs/WritingAnLLVMPass.rst
  llvm/docs/index.rst
  llvm/docs/tutorial/BuildingAJIT1.rst
  llvm/docs/tutorial/MyFirstLanguageFrontend/LangImpl02.rst
  llvm/docs/tutorial/MyFirstLanguageFrontend/LangImpl03.rst
  llvm/docs/tutorial/MyFirstLanguageFrontend/LangImpl04.rst
  llvm/docs/tutorial/MyFirstLanguageFrontend/LangImpl05.rst
  llvm/docs/tutorial/MyFirstLanguageFrontend/LangImpl08.rst
  llvm/docs/tutorial/MyFirstLanguageFrontend/LangImpl09.rst
  llvm/docs/tutorial/OCamlLangImpl3.rst
  llvm/docs/tutorial/OCamlLangImpl5.rst
  llvm/docs/tutorial/index.rst
  llvm/include/llvm/ADT/Triple.h
  llvm/include/llvm/ExecutionEngine/Orc/Core.h
  llvm/include/llvm/ExecutionEngine/Orc/DebugUtils.h
  llvm/include/llvm/ExecutionEngine/Orc/Speculation.h
  llvm/include/llvm/MC/MCObjectFileInfo.h
  llvm/include/llvm/Target/TargetLoweringObjectFile.h
  llvm/include/llvm/TextAPI/MachO/InterfaceFile.h
  llvm/include/llvm/Transforms/IPO/PassManagerBuilder.h
  llvm/include/llvm/Transforms/InstCombine/InstCombine.h
  llvm/include/llvm/Transforms/Utils/LowerMemIntrinsics.h
  llvm/lib/Analysis/LazyValueInfo.cpp
  llvm/lib/Analysis/TargetLibraryInfo.cpp
  llvm/lib/Analysis/ValueTracking.cpp
  llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
  llvm/lib/CodeGen/GlobalISel/LegalizerHelper.cpp
  llvm/lib/CodeGen/MachineFunction.cpp
  llvm/lib/CodeGen/PrologEpilogInserter.cpp
  llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp
  llvm/lib/CodeGen/SelectionDAG/FunctionLoweringInfo.cpp
  llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp
  llvm/lib/CodeGen/SelectionD

Re: [clang] 857bf5d - [FIX] Do not copy an llvm::function_ref if it has to be reused

2020-03-23 Thread Johannes Doerfert via cfe-commits


Apologies for the confusion.

I wrote the commit message after looking into this and I though the
issue was related to the capture by copy in the inner llvm::any_of and
the reuse in the outer. Looking back at the code I cannot say anymore
how I got that impression.

If you think the reference is problematic, I'm totally happy to remove
it. If the windows bots (or any other ones) don't like it we need to
investigate why. As mentioned, I had a problem recreating the problem
locally before.

Cheers,
  Johannes


On 3/22/20 1:37 PM, Arthur O'Dwyer wrote:
> On Sun, Mar 22, 2020 at 1:48 PM David Blaikie via cfe-commits <
> cfe-commits@lists.llvm.org> wrote:
>
>> On Sun, Mar 22, 2020 at 10:40 AM Johannes Doerfert 


>> wrote:
>>
>>> Some buildbots, I think only Windows buildbots for some reason, crashed
>>> in this function.
>>>
>>> The reason, as described, is that an `llvm::function_ref` cannot be
>>> copied and then reused. It just happened to work on almost all
>>> configurations.
>>>
>>
>> That doesn't seem to be accurate, or if it is there's a lot of 
mistakes in
>> the codebase - basically every function_ref parameter I can see in 
LLVM is

>> passing by value, not by const ref. The implementation of
>> llvm::function_ref looks quite copyable so long as it doesn't 
outlive the

>> functor it is pointing to.
>>
>
> David is correct. llvm::function_ref, like std::reference_wrapper, is a
> trivially copyable type, and it's designed to be copied.
> Like string_view and reference_wrapper, function_ref is designed to be
> passed by value. Redundantly passing function_ref *again by 
reference* is a

> code smell.
>
> I've also checked the code here, and it looks like there are only two
> callers of `anyScoreOrCondition` — both in Sema/SemaOpenMP.cpp — and they
> are both fine. FWIW, I would recommend reverting Johannes' change and
> seeing if those Windows buildbots are still unhappy (and if so, why).
>
>
> Btw, one failure mode I'm aware of, but which I believe is NOT 
relevant in

> Johannes' case, is that `function_ref`'s converting constructor behaves
> differently from its copy constructor.
>
> int main()
>
> {
>
> auto lamb = [](){ return 42; };
>
> auto sheep = [](){ return 43; };
>
> llvm::function_ref one = lamb;
>
>
> llvm::function_ref twoA = one;    // twoA refers to lamb
>
> llvm::function_ref twoB = one;  // twoB refers to one which
> refers to lamb
>
>
> one = sheep;
>
>
> assert(twoA() == 42);  // twoA refers to lamb
>
> assert(twoB() == 43);  // twoB refers to one which refers to sheep
>
> }
>
> That is, if you have a function that takes a parameter of type
> function_ref, and someone passes it an argument of type 
function_ref,
> then inside the function your parameter will be referring to that 
argument

> itself instead of to its referent.
> However, in Johannes' particular case, we have no function_refs referring
> to other function_refs. We just make a lambda and take a function_ref to
> it, the end. So I'm pretty sure this pitfall is irrelevant.
>
> –Arthur
>

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


[PATCH] D76551: [Alignment][NFC] Use TargetFrameLowering::getStackAlign()

2020-03-23 Thread Guillaume Chatelet via Phabricator via cfe-commits
gchatelet updated this revision to Diff 251971.
gchatelet added a comment.
Herald added a reviewer: jdoerfert.

rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76551

Files:
  llvm/lib/CodeGen/MachineFunction.cpp
  llvm/lib/CodeGen/PrologEpilogInserter.cpp
  llvm/lib/CodeGen/SelectionDAG/FunctionLoweringInfo.cpp
  llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp
  llvm/lib/Target/AVR/AVRFrameLowering.cpp
  llvm/lib/Target/MSP430/MSP430FrameLowering.cpp
  llvm/lib/Target/Mips/MipsCallLowering.cpp
  llvm/lib/Target/PowerPC/PPCRegisterInfo.cpp
  llvm/lib/Target/RISCV/RISCVFrameLowering.cpp
  llvm/lib/Target/X86/X86CallFrameOptimization.cpp
  llvm/lib/Target/X86/X86FastISel.cpp
  llvm/lib/Target/X86/X86FrameLowering.cpp
  llvm/lib/Target/X86/X86ISelLowering.cpp
  llvm/lib/Target/X86/X86InstrInfo.cpp
  llvm/lib/Target/X86/X86InstrInfo.h

Index: llvm/lib/Target/X86/X86InstrInfo.h
===
--- llvm/lib/Target/X86/X86InstrInfo.h
+++ llvm/lib/Target/X86/X86InstrInfo.h
@@ -474,7 +474,7 @@
   unsigned OpNum,
   ArrayRef MOs,
   MachineBasicBlock::iterator InsertPt,
-  unsigned Size, unsigned Alignment,
+  unsigned Size, Align Alignment,
   bool AllowCommute) const;
 
   bool isHighLatencyDef(int opc) const override;
@@ -594,7 +594,7 @@
 unsigned OpNum,
 ArrayRef MOs,
 MachineBasicBlock::iterator InsertPt,
-unsigned Size, unsigned Align) const;
+unsigned Size, Align Alignment) const;
 
   /// isFrameOperand - Return true and the FrameIndex if the specified
   /// operand and follow operands form a reference to the stack frame.
Index: llvm/lib/Target/X86/X86InstrInfo.cpp
===
--- llvm/lib/Target/X86/X86InstrInfo.cpp
+++ llvm/lib/Target/X86/X86InstrInfo.cpp
@@ -625,8 +625,7 @@
   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
 
   if (isFrameInstr(MI)) {
-unsigned StackAlign = TFI->getStackAlignment();
-int SPAdj = alignTo(getFrameSize(MI), StackAlign);
+int SPAdj = alignTo(getFrameSize(MI), TFI->getStackAlign());
 SPAdj -= getFrameAdjustment(MI);
 if (!isFrameSetup(MI))
   SPAdj = -SPAdj;
@@ -3737,7 +3736,7 @@
  "Stack slot too small for store");
   unsigned Alignment = std::max(TRI->getSpillSize(*RC), 16);
   bool isAligned =
-  (Subtarget.getFrameLowering()->getStackAlignment() >= Alignment) ||
+  (Subtarget.getFrameLowering()->getStackAlign() >= Alignment) ||
   RI.canRealignStack(MF);
   unsigned Opc = getStoreRegOpcode(SrcReg, RC, isAligned, Subtarget);
   addFrameReference(BuildMI(MBB, MI, DebugLoc(), get(Opc)), FrameIdx)
@@ -3752,7 +3751,7 @@
   const MachineFunction &MF = *MBB.getParent();
   unsigned Alignment = std::max(TRI->getSpillSize(*RC), 16);
   bool isAligned =
-  (Subtarget.getFrameLowering()->getStackAlignment() >= Alignment) ||
+  (Subtarget.getFrameLowering()->getStackAlign() >= Alignment) ||
   RI.canRealignStack(MF);
   unsigned Opc = getLoadRegOpcode(DestReg, RC, isAligned, Subtarget);
   addFrameReference(BuildMI(MBB, MI, DebugLoc(), get(Opc), DestReg), FrameIdx);
@@ -5211,7 +5210,7 @@
 MachineInstr *X86InstrInfo::foldMemoryOperandCustom(
 MachineFunction &MF, MachineInstr &MI, unsigned OpNum,
 ArrayRef MOs, MachineBasicBlock::iterator InsertPt,
-unsigned Size, unsigned Align) const {
+unsigned Size, Align Alignment) const {
   switch (MI.getOpcode()) {
   case X86::INSERTPSrr:
   case X86::VINSERTPSrr:
@@ -5227,7 +5226,7 @@
   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
   const TargetRegisterClass *RC = getRegClass(MI.getDesc(), OpNum, &RI, MF);
   unsigned RCSize = TRI.getRegSizeInBits(*RC) / 8;
-  if ((Size == 0 || Size >= 16) && RCSize >= 16 && 4 <= Align) {
+  if ((Size == 0 || Size >= 16) && RCSize >= 16 && Alignment >= Align(4)) {
 int PtrOffset = SrcIdx * 4;
 unsigned NewImm = (DstIdx << 4) | ZMask;
 unsigned NewOpCode =
@@ -5251,7 +5250,7 @@
   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
   const TargetRegisterClass *RC = getRegClass(MI.getDesc(), OpNum, &RI, MF);
   unsigned RCSize = TRI.getRegSizeInBits(*RC) / 8;
-  if ((Size == 0 || Size >= 16) && RCSize >= 16 && 8 <= Align) {
+  if ((Size == 0 || Size >= 16) && RCSize >= 16 && Alignment >= Align(8)) {
 unsigned NewOpCode =
 (MI.getOpcode() == X86::VMOVHLPSZrr) ? X86::VMOVLPSZ128r

Re: [clang] d9b9621 - Reland D73534: [DebugInfo] Enable the debug entry values feature by default

2020-03-23 Thread Djordje via cfe-commits
Hi David,

Thanks for the heads-up!

On 23.3.20. 11:02, David Stenberg wrote:
> Hi!
>
> On Mon, 2020-03-23 at 08:56 +0100, Djordje wrote:
>> (+ CCing some debug info folks as well)
>>
>> Hi David,
>>
>> OK, I agree, my apologize.
>>
>> The patch enables the whole feature by default and removes the experimental
>> option that has been used during the implementation.
>> We tested the code (and the assertions regarding the feature itself) by using
>> the experimental option on some large projects, but since the feature became
>> that huge (and new patches regarding the feature are coming every day -- 
>> which
>> is nice), it is impossible to test everything.
> When the issue related to D75036 was reported I probably should have reverted
> that commit directly when starting to troubleshoot the issue, so that we 
> didn't
> have to end up reverting D73534.
>
> Sorry about that!
>
>> The Debug Entry Values implementation grows these days, and new 
>> functionalities
>> comes in, but it has all been tested with the experimental option, so
>> committing this particular patch imposes all the cases developers oversighted
>> during the implementation.
>>
>> My impression is that, before adding new functionalities to the feature, we
>> should make sure the D73534 is stable and gets stuck. We should have done it
>> before, but I think that is the lesson learned here.
> That sounds reasonable I think. For how long should we do that? A week? Two
> weeks?
I am not sure, but I guess two weeks are fine.
>> In general, experimental options are very good up to the some point, but if 
>> the
>> feature being tested grows a lot, a "breakpoint" should be set up and take 
>> care
>> the experimental option is removed and the code is well tested on the real
>> cases out there, and then moving to the next stage of the implementation.
>>
>> Besides this, CISCO is using the feature ON by default for some time, and we
>> have good experience there. This really improves the debugging user 
>> experience
>> while debugging the "optimized" code.
>>
>> Best regards,
>> Djordje
> Best regards,
> David S

Thanks,
Djordje

>> On 22.3.20. 16:30, David Blaikie wrote:
>>> Also, this patch was reverted and recommitted several times (more than I
>>> think would be ideal) - please include more details in the commit message
>>> about what went wrong, what was fixed, what testing was missed in the first
>>> place and done in subsequent precommit validation (& is there anything more
>>> broadly we could learn from this patches story to avoid this kind of
>>> revert/recommit repetition in the future?)
>>>
>>> On Sat, Mar 21, 2020 at 8:13 PM David Blaikie >> dblai...@gmail.com>> wrote:
>>>
>>> Please include the "Differential Revision" line so that Phab picks up
>>> commits like this and ties them into the review (& also makes it 
>>> conveniently
>>> clickable to jump from the commit mail to the review)
>>>
>>> On Thu, Mar 19, 2020 at 5:58 AM Djordje Todorovic via cfe-commits <
>>> cfe-commits@lists.llvm.org > wrote:
>>>
>>>
>>> Author: Djordje Todorovic
>>> Date: 2020-03-19T13:57:30+01:00
>>> New Revision: d9b962100942c71a4c26debaa716f7ab0c4ea8a1
>>>
>>> URL: 
>>> https://protect2.fireeye.com/v1/url?k=77e8c227-2b3ccf55-77e882bc-86859b2931b3-a6817f347a752f02&q=1&e=88d8925e-f175-4c81-9485-741ddc24573f&u=https%3A%2F%2Fgithub.com%2Fllvm%2Fllvm-project%2Fcommit%2Fd9b962100942c71a4c26debaa716f7ab0c4ea8a1
>>> DIFF: 
>>> https://protect2.fireeye.com/v1/url?k=3914be57-65c0b325-3914fecc-86859b2931b3-b52b8ad09d192520&q=1&e=88d8925e-f175-4c81-9485-741ddc24573f&u=https%3A%2F%2Fgithub.com%2Fllvm%2Fllvm-project%2Fcommit%2Fd9b962100942c71a4c26debaa716f7ab0c4ea8a1.diff
>>>
>>> LOG: Reland D73534: [DebugInfo] Enable the debug entry values 
>>> feature
>>> by default
>>>
>>> The issue that was causing the build failures was fixed with the
>>> D76164.
>>>
>>> Added:
>>> llvm/test/DebugInfo/X86/no-entry-values-with-O0.ll
>>>
>>> Modified:
>>> clang/include/clang/Basic/CodeGenOptions.def
>>> clang/include/clang/Driver/CC1Options.td
>>> clang/lib/CodeGen/BackendUtil.cpp
>>> clang/lib/CodeGen/CGDebugInfo.cpp
>>> clang/lib/Frontend/CompilerInvocation.cpp
>>> clang/test/CodeGen/debug-info-extern-call.c
>>> clang/test/CodeGenCXX/dbg-info-all-calls-described.cpp
>>> lldb/packages/Python/lldbsuite/test/decorators.py
>>>
>>> lldb/test/API/functionalities/param_entry_vals/basic_entry_values_x86_64/Make
>>> file
>>> llvm/include/llvm/Target/TargetMachine.h
>>> llvm/include/llvm/Target/TargetOptions.h
>>> llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp
>>> llvm/lib/CodeGen/AsmPrinter/DwarfDebug.h
>>> llvm/lib/CodeGen/CommandFlags.cpp
>>> llvm/lib/CodeGen/LiveDebugValues.cpp
>>>

[PATCH] D76078: [AArch64][SVE] Add a pass for SVE intrinsic optimisations

2020-03-23 Thread Andrzej Warzynski via Phabricator via cfe-commits
andwar added a comment.

Thanks for the updates @kmclaughlin ! Would you mind adding a comment to 
clearly mark the negative tests? E.g. for `@reinterpret_reductions_1`? Maybe 
also a comment `why` a particular case is not optimised? You've already done 
that for some tests, but not all of them.




Comment at: llvm/lib/Target/AArch64/SVEIntrinsicOpts.cpp:10
+//
+// Performs general IR level optimizations on SVE intrinsics.
+//

I don't see any documentation for the pass that's being added here (apart from 
the commit msg). Perhaps it's worth expanding this comment?



Comment at: llvm/lib/Target/AArch64/SVEIntrinsicOpts.cpp:221
+bool SVEIntrinsicOpts::optimizeFunctions(
+SmallVectorImpl &Functions) {
+  bool Changed = false;

I think that you could simplify things a bit by using `SmallPtrSet` instead: 
http://llvm.org/docs/ProgrammersManual.html#dss-smallptrset.

With a set you can avoid explicit checks like this:
``` 
std::find(Functions.begin(), Functions.end(), Inst->getFunction()) == 
Functions.end()
```
With `SmallPtrSet` you can write less code :)



Comment at: llvm/lib/Target/AArch64/SVEIntrinsicOpts.cpp:241
+
+  for (auto &F : M.getFunctionList()) {
+if (!F.isDeclaration())

Could you decorate this `for` loop with a comment explaining `what` kind of 
data is generated here and `why`? Ta!


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

https://reviews.llvm.org/D76078



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


[PATCH] D75068: libclang: Add static build support for Windows

2020-03-23 Thread Cristian Adam via Phabricator via cfe-commits
cristian.adam added a comment.

Ping.

I find it a bit uncool to revert commits and then be away for a month.

I guess it's my fault for not making the patch perfect in the first place.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D75068



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


[PATCH] D70411: [analyzer] CERT: STR31-C

2020-03-23 Thread Balázs Kéri via Phabricator via cfe-commits
balazske added inline comments.



Comment at: clang/docs/analyzer/checkers.rst:1935
+
+alpha.security.cert.str.31c
+"""

There are already more checkers that can check for CERT related problems but 
not specially made for these. These checkers do not reside in this new `cert` 
group. And generally a checker does not check for specifically a CERT rule, 
instead for more of them or other things too, or more checkers can detect a 
single rule. (And the user can think that only these CERT rules are checkable 
that exist in this package, that is not true.) So I do not like the 
introduction of this new `cert` package. (The documentation of existing 
checkers lists if the checker is designed for a CERT rule.)



Comment at: 
clang/include/clang/StaticAnalyzer/Core/BugReporter/CommonBugCategories.h:22
+extern const char *const CXXObjectLifecycle;
+extern const char *const SecurityError;
+} // namespace categories

Are there already not other checkers that find security related bugs (the taint 
checker?)? Why do these not use a `SecurityError`? It is not bad to have a 
`SecurityError` but maybe there is a reason why was it not there already. If 
these categories are exclusive it is hard to find out what problem (probably 
already existing bug type in other checkers) belongs to what category (it can 
be for this checker `UnixAPI` or `MemoryError` too?). 


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

https://reviews.llvm.org/D70411



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


[PATCH] D76599: Represent FP options in AST by special Statement node

2020-03-23 Thread Serge Pavlov via Phabricator via cfe-commits
sepavloff created this revision.
sepavloff added reviewers: rsmith, rjmccall, andrew.w.kaylor, efriedma, 
mibintc, kpn, sammccall, hokein.
Herald added subscribers: martong, arphaman.
Herald added a project: clang.

Now FPOption object is stored in the bits of Stmt class. The space
there is limited by 7 bits, which is by far not enough as FPOption
is supposed to grow incorporating other options related to floating
point operations. The problem was discussed in
http://lists.llvm.org/pipermail/cfe-dev/2020-March/064850.html. In
short, attempts to put FPOption as a field to relevant AST classes
result in substantial increase of AST size because such field would
consume memory even for nodes that do not deal with FP operations.

As a solution, a new statement node `FloatingPragmaStmt` has been
added. It represents a pragma that modifies floating point options.
This statement is placed at the beginning of corresponding
`CompoundStmt`. It provides persistency for the FP options and
allows to maintain actual FP state. Other nodes such as BinaryOperator
do not have to have a copy of FPOption, thus no unnecessary memory
consumption occurs.

If more than one pragma are specified in a compound statement, there
is a separate node for each. Each node keeps FP options accumulated
from all previous pragma nodes and from this one. Pragma specified
at file level results in pragma nodes implicitly inserted into every
function body affected by the pragma. In compilation option result
in non-default FP options, the synthesized pragma is inserted as well.

There are cases when an expression occurs outside compound statement.
These are global variable initializers, default arguments and some
other. This solution does not work for them, a special expression
node is required for them, it will be implemented later.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D76599

Files:
  clang/include/clang-c/Index.h
  clang/include/clang/AST/Expr.h
  clang/include/clang/AST/ExprCXX.h
  clang/include/clang/AST/RecursiveASTVisitor.h
  clang/include/clang/AST/Stmt.h
  clang/include/clang/AST/TextNodeDumper.h
  clang/include/clang/Basic/LangOptions.h
  clang/include/clang/Basic/StmtNodes.td
  clang/include/clang/Sema/Sema.h
  clang/include/clang/Serialization/ASTBitCodes.h
  clang/lib/AST/ExprConstant.cpp
  clang/lib/AST/StmtPrinter.cpp
  clang/lib/AST/StmtProfile.cpp
  clang/lib/AST/TextNodeDumper.cpp
  clang/lib/Basic/LangOptions.cpp
  clang/lib/CodeGen/CGExprScalar.cpp
  clang/lib/CodeGen/CGStmt.cpp
  clang/lib/CodeGen/CodeGenFunction.h
  clang/lib/Parse/ParsePragma.cpp
  clang/lib/Parse/ParseStmt.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/lib/Sema/SemaExceptionSpec.cpp
  clang/lib/Sema/SemaStmt.cpp
  clang/lib/Sema/TreeTransform.h
  clang/lib/Serialization/ASTReaderStmt.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/lib/Serialization/ASTWriterStmt.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
  clang/test/AST/ast-dump-pragma.cpp
  clang/test/CodeGen/fp-contract-pragma.cpp
  clang/test/Coverage/c-language-features.inc
  clang/tools/libclang/CIndex.cpp
  clang/tools/libclang/CXCursor.cpp

Index: clang/tools/libclang/CXCursor.cpp
===
--- clang/tools/libclang/CXCursor.cpp
+++ clang/tools/libclang/CXCursor.cpp
@@ -742,6 +742,10 @@
 break;
   case Stmt::BuiltinBitCastExprClass:
 K = CXCursor_BuiltinBitCastExpr;
+break;
+  case Stmt::FloatingPragmaStmtClass:
+K = CXcursor_FloatingPragmaStmt;
+break;
   }
 
   CXCursor C = { K, 0, { Parent, S, TU } };
Index: clang/tools/libclang/CIndex.cpp
===
--- clang/tools/libclang/CIndex.cpp
+++ clang/tools/libclang/CIndex.cpp
@@ -5612,6 +5612,8 @@
   return cxstring::createRef("attribute(warn_unused_result)");
   case CXCursor_AlignedAttr:
   return cxstring::createRef("attribute(aligned)");
+  case CXcursor_FloatingPragmaStmt:
+  return cxstring::createRef("FloatingPragma");
   }
 
   llvm_unreachable("Unhandled CXCursorKind");
Index: clang/test/Coverage/c-language-features.inc
===
--- clang/test/Coverage/c-language-features.inc
+++ clang/test/Coverage/c-language-features.inc
@@ -210,3 +210,9 @@
 void f11() {
   struct s12 var = { .aa = 33 };
 }
+
+float pragma_01(float x, float y, float z) {
+  #pragma clang fp contract(on)
+  #pragma STDC FP_CONTRACT OFF
+  return x + y * z;
+}
Index: clang/test/CodeGen/fp-contract-pragma.cpp
===
--- clang/test/CodeGen/fp-contract-pragma.cpp
+++ clang/test/CodeGen/fp-contract-pragma.cpp
@@ -89,3 +89,20 @@
   #pragma STDC FP_CONTRACT ON
   return c - a * b;
 }
+
+float fp_contract_10(float a, float x, float y, float z) {
+// CHECK-LABEL: _Z14fp_contract_10
+// CHECK:   call float @llvm.fmuladd.f32
+// CHECK:   fmul floa

Re: [clang] 43606ef - Suppress an "unused variable" warning in release build

2020-03-23 Thread Mikhail Maltsev via cfe-commits
Yes, it does. isIntegerConstantExpr assigns a value to CoprocNoAP.

--
Regards,
   Mikhail Maltsev


From: David Blaikie 
Sent: Sunday, March 22, 2020 03:32
To: Mikhail Maltsev; Mikhail Maltsev
Cc: cfe-commits
Subject: Re: [clang] 43606ef - Suppress an "unused variable" warning in release 
build

Does "isIntegerConstantExpr" have side effects that are desired/necessary? 
Otherwise please change this to roll the isIntegerConstantExpr into the assert 
(so that it is only executed when asserts are enabled)

On Tue, Mar 10, 2020 at 10:11 AM Mikhail Maltsev via cfe-commits 
mailto:cfe-commits@lists.llvm.org>> wrote:

Author: Mikhail Maltsev
Date: 2020-03-10T17:10:52Z
New Revision: 43606efb6847fc9c79e7d93760a2a6191e8a8539

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

LOG: Suppress an "unused variable" warning in release build

Added:


Modified:
clang/lib/Sema/SemaChecking.cpp

Removed:




diff  --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 24d0d9209a1d..8a2b4b019663 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -2094,6 +2094,7 @@ bool Sema::CheckARMCoprocessorImmediate(const Expr 
*CoprocArg, bool WantCDE) {

   llvm::APSInt CoprocNoAP;
   bool IsICE = CoprocArg->isIntegerConstantExpr(CoprocNoAP, Context);
+  (void)IsICE;
   assert(IsICE && "Coprocossor immediate is not a constant expression");
   int64_t CoprocNo = CoprocNoAP.getExtValue();
   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");



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


Re: [clang] 4a0267e - Convert a reachable llvm_unreachable into an assert.

2020-03-23 Thread Aaron Ballman via cfe-commits
On Sun, Mar 22, 2020 at 3:31 PM David Blaikie  wrote:
>
> On Sun, Mar 22, 2020 at 9:34 AM Aaron Ballman  wrote:
>>
>> On Sun, Mar 22, 2020 at 12:19 PM David Blaikie  wrote:
>> >
>> > On Sun, Mar 22, 2020 at 6:34 AM Aaron Ballman  
>> > wrote:
>> >>
>> >> On Sat, Mar 21, 2020 at 11:31 PM David Blaikie  wrote:
>> >> >
>> >> > Why the change? this seems counter to LLVM's style which pretty 
>> >> > consistently uses unreachable rather than assert(false), so far as I 
>> >> > know?
>> >>
>> >> We're not super consistent (at least within Clang), but the rules as
>> >> I've generally understood them are to use llvm_unreachable only for
>> >> truly unreachable code and to use assert(false) when the code is
>> >> technically reachable but is a programmer mistake to have gotten
>> >> there.
>> >
>> >
>> > I don't see those as two different things personally - llvm_unreachable is 
>> > used when the programmer believes it to be unreachable (not that it must 
>> > be proven to be unreachable - we have message text there so it's 
>> > informative if the assumption turns out not to hold)
>>
>> The message text doesn't help when the code is reached in release
>> mode, which was the issue. Asserts + release you still get some
>> helpful text saying "you screwed up". llvm_unreachable in release
>> mode, you may get lucky or you may not (in this case, I didn't get
>> lucky -- there was no text, just a crash).
>
>
> That doesn't seem to be what it's documented to do:
>
> /// Marks that the current location is not supposed to be reachable.
> /// In !NDEBUG builds, prints the message and location info to stderr.
> /// In NDEBUG builds, becomes an optimizer hint that the current location
> /// is not supposed to be reachable.  On compilers that don't support
> /// such hints, prints a reduced message instead.
>
> & certainly I think the documentation is what it /should/ be doing.
>
> /maybe/ https://reviews.llvm.org/rG5f4535b974e973d52797945fbf80f19ffba8c4ad 
> broke that contract on Windows, but I'm not sure how? (an unreachable at the 
> end of that function shouldn't cause the whole function to be unreachable - 
> because abort could have side effects and halt the program before the 
> unreachable is reached)

Agreed. It could also be that my machine is in a weird state (I'm
currently battling a situation where the command line parser appears
to be totally broken on Windows due to misuse of a ManagedStatic
somewhere but I've not seen any commits that relate to the issues).

>> >> In this particular case, the code is very much reachable
>> >
>> >
>> > In what sense? If it is actually reachable - shouldn't it be tested? (& in 
>> > which case the assert(false) will get in the way of that testing)
>>
>> In the sense that normal code paths reach that code easily. Basically,
>> that code is checking to see whether a plugin you've written properly
>> sets up its options or not. When you're developing a plugin, it's
>> quite reasonable to expect you won't get it just right on the first
>> try, so you hit the code path but only as a result of you not writing
>> the plugin quite right. So under normal conditions (once the plugin is
>> working), the code path should not be reached but under development
>> the code path gets reached accidentally.
>>
>> >> and I
>> >> spent a lot more time debugging than I should have because I was using
>> >> a release + asserts build and the semantics of llvm_unreachable made
>> >> unfortunate codegen (switching to an assert makes the issue
>> >> immediately obvious).
>> >
>> >
>> > I think it might be reasonable to say that release+asserts to have 
>> > unreachable behave the same way unreachable behaves at -O0 (which is to 
>> > say, much like assert(false)). Clearly release+asserts effects code 
>> > generation, so there's nothing like the "debug info invariance" goal that 
>> > this would be tainting, etc.
>> >
>> > Certainly opinions vary here, but here are some commits that show the sort 
>> > of general preference:
>> > http://llvm.org/viewvc/llvm-project?view=revision&revision=259302
>> > http://llvm.org/viewvc/llvm-project?view=revision&revision=253005
>> > http://llvm.org/viewvc/llvm-project?view=revision&revision=251266
>> >
>> > And some counter examples:
>> > http://llvm.org/viewvc/llvm-project?view=revision&revision=225043
>> > Including this thread where Chandler originally (not sure what his take on 
>> > it is these days) expressed some ideas more along your lines:
>> > http://lists.llvm.org/pipermail/cfe-commits/Week-of-Mon-20110919/thread.html#46583
>> >
>> > But I'm always pretty concerned about the idea that assertions should be 
>> > used in places where the behavior of the program has any constraints when 
>> > the assertion is false...
>>
>> I'm opposed to using unreachability hints on control flow paths you
>> expect to reach -- the semantics are just plain wrong, even if you can
>> get the same end result of controlled crash + message. In this
>> particular case, the code is

[PATCH] D76545: [clang-tidy] Add a new check group 'experimental-'

2020-03-23 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D76545#1936389 , @whisperity wrote:

> In D76545#1935603 , @aaron.ballman 
> wrote:
>
> > I think we want to keep the experimental checks grouped to their parent 
> > module rather than being in a module of their own.
>
>
> For this, wouldn't the fact that telling Tidy to enable `cppcoreguidelines-*` 
> (i.e. `--checks='-*,cppcoreguidelines-*'`) also enables the 
> `cppcoreguidelines-experimental-*` cause a problem? (This is the original 
> reason why I tinkered in the "top-level" `experimental-` mode.)


It will by default, but it doesn't have to. For instance, we could add an 
`--experimental` flag to clang-tidy that automatically enables the 
`-experimental-*` checks in any otherwise-enabled module for the run.

> In D76545#1935603 , @aaron.ballman 
> wrote:
> 
>> I'm not opposed to the idea of experimental checks, but I don't want to see 
>> "experimental" become a dumping ground for low-quality checks that we then 
>> have to maintain indefinitely.
> 
> 
> I think this could (in terms of development, support, etc.) work similarly to 
> the `alpha.` group/package of Clang Static Analyser checkers. I'm not too 
> knowledgeable about CSA - perhaps @Szelethus could help me out, - but their 
> idea of alpha checkers is that they are mature in terms of the general idea, 
> but clunky in terms of working. (The official stance is that anything out of 
> alpha should not crash, anything within alpha might crash, and if you enable 
> it and you crash, you are your own perpetrator.)

The `alpha` checks from CSA was the situation I was hoping to avoid -- my 
experience has been that checks go into there and rarely come out of alpha 
stage but continue to require periodic maintenance.

> @aaron.ballman @njames93 Should I write up a pitch mail to cfe-dev about this?

I think that would be a reasonable next step.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76545



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


[PATCH] D76355: [Syntax] Build mapping from AST to syntax tree nodes

2020-03-23 Thread Marcel Hlopko via Phabricator via cfe-commits
hlopko added inline comments.



Comment at: clang/lib/Tooling/Syntax/BuildTree.cpp:570
+  auto *N = new (allocator()) syntax::SimpleDeclarator;
+  Builder.foldNode(Builder.getRange(R.getBegin(), R.getEnd()), N, D);
+  Builder.markChild(N, syntax::NodeRole::SimpleDeclaration_declarator);

gribozavr2 wrote:
> It might make sense to add a helper `Builder.getRange(SourceRange)` and 
> simplify these calls to `Builder.getRange(something.getBegin(), 
> something.getEnd())` throughout the patch.
Done and refactored all the calls that made sense to use the SourceRange 
method. I didn't modify call like Builder.getRange(L.getLBracketLoc(), 
L.getRBracketLoc()).



Comment at: clang/lib/Tooling/Syntax/BuildTree.cpp:975
+  const syntax::Token *TemplateKW,
+  syntax::SimpleDeclaration *InnerDeclaration) {
 assert(!ExternKW || ExternKW->kind() == tok::kw_extern);

gribozavr2 wrote:
> Add a `Decl *From` parameter and pass it through to `Builder.foldNode()` 
> below?
Done, but to get rid of all nullptr parents in BuildTree.cpp we'd have to 
implement support for Types in the AST mapping. Let's not do that in this patch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76355



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


[PATCH] D76355: [Syntax] Build mapping from AST to syntax tree nodes

2020-03-23 Thread Marcel Hlopko via Phabricator via cfe-commits
hlopko updated this revision to Diff 251993.
hlopko marked 6 inline comments as done.
hlopko added a comment.

Address comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76355

Files:
  clang/include/clang/Tooling/Syntax/Tree.h
  clang/lib/Tooling/Syntax/BuildTree.cpp
  clang/lib/Tooling/Syntax/Mutations.cpp
  clang/lib/Tooling/Syntax/Tree.cpp

Index: clang/lib/Tooling/Syntax/Tree.cpp
===
--- clang/lib/Tooling/Syntax/Tree.cpp
+++ clang/lib/Tooling/Syntax/Tree.cpp
@@ -58,22 +58,33 @@
 
 syntax::Node::Node(NodeKind Kind)
 : Parent(nullptr), NextSibling(nullptr), Kind(static_cast(Kind)),
-  Role(static_cast(NodeRole::Detached)), Original(false),
-  CanModify(false) {}
+  Role(0), Original(false), CanModify(false) {
+  this->SetRole(NodeRole::Detached);
+}
 
 bool syntax::Node::isDetached() const { return role() == NodeRole::Detached; }
 
+void syntax::Node::SetRole(NodeRole NR) {
+  this->Role = static_cast(NR);
+}
+
 bool syntax::Tree::classof(const Node *N) { return N->kind() > NodeKind::Leaf; }
 
 void syntax::Tree::prependChildLowLevel(Node *Child, NodeRole Role) {
-  assert(Child->Parent == nullptr);
-  assert(Child->NextSibling == nullptr);
   assert(Child->role() == NodeRole::Detached);
   assert(Role != NodeRole::Detached);
 
+  Child->SetRole(Role);
+  prependChildLowLevel(Child);
+}
+
+void syntax::Tree::prependChildLowLevel(Node *Child) {
+  assert(Child->Parent == nullptr);
+  assert(Child->NextSibling == nullptr);
+  assert(Child->role() != NodeRole::Detached);
+
   Child->Parent = this;
   Child->NextSibling = this->FirstChild;
-  Child->Role = static_cast(Role);
   this->FirstChild = Child;
 }
 
@@ -94,7 +105,7 @@
N != End;) {
 auto *Next = N->NextSibling;
 
-N->Role = static_cast(NodeRole::Detached);
+N->SetRole(NodeRole::Detached);
 N->Parent = nullptr;
 N->NextSibling = nullptr;
 if (N->Original)
Index: clang/lib/Tooling/Syntax/Mutations.cpp
===
--- clang/lib/Tooling/Syntax/Mutations.cpp
+++ clang/lib/Tooling/Syntax/Mutations.cpp
@@ -35,7 +35,7 @@
 assert(!New->isDetached());
 assert(Role != NodeRole::Detached);
 
-New->Role = static_cast(Role);
+New->SetRole(Role);
 auto *P = Anchor->parent();
 P->replaceChildRangeLowLevel(Anchor, Anchor, New);
 
Index: clang/lib/Tooling/Syntax/BuildTree.cpp
===
--- clang/lib/Tooling/Syntax/BuildTree.cpp
+++ clang/lib/Tooling/Syntax/BuildTree.cpp
@@ -25,6 +25,8 @@
 #include "clang/Tooling/Syntax/Tokens.h"
 #include "clang/Tooling/Syntax/Tree.h"
 #include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/PointerUnion.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/ScopeExit.h"
 #include "llvm/ADT/SmallVector.h"
@@ -34,6 +36,7 @@
 #include "llvm/Support/FormatVariadic.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/raw_ostream.h"
+#include 
 #include 
 
 using namespace clang;
@@ -145,6 +148,30 @@
   return SourceRange(Start, End);
 }
 
+namespace {
+/// All AST hierarchy roots that can be represented as pointers.
+using ASTPtr = llvm::PointerUnion;
+/// Maintains a mapping from AST to syntax tree nodes. This class will get more
+/// complicated as we support more kinds of AST nodes, e.g. TypeLocs.
+/// FIXME: expose this as public API.
+class ASTToSyntaxMapping {
+public:
+  void add(ASTPtr From, syntax::Tree *To) {
+assert(To != nullptr);
+assert(!From.isNull());
+
+bool Added = Nodes.insert({From, To}).second;
+(void)Added;
+assert(Added && "mapping added twice");
+  }
+
+  syntax::Tree *find(ASTPtr P) const { return Nodes.lookup(P); }
+
+private:
+  llvm::DenseMap Nodes;
+};
+} // namespace
+
 /// A helper class for constructing the syntax tree while traversing a clang
 /// AST.
 ///
@@ -172,7 +199,18 @@
 
   /// Populate children for \p New node, assuming it covers tokens from \p
   /// Range.
-  void foldNode(llvm::ArrayRef Range, syntax::Tree *New);
+  void foldNode(llvm::ArrayRef Range, syntax::Tree *New,
+ASTPtr From) {
+assert(New);
+Pending.foldChildren(Arena, Range, New);
+if (From)
+  Mapping.add(From, New);
+  }
+  void foldNode(llvm::ArrayRef Range, syntax::Tree *New,
+TypeLoc L) {
+// FIXME: add mapping for TypeLocs
+foldNode(Range, New, nullptr);
+  }
 
   /// Must be called with the range of each `DeclaratorDecl`. Ensures the
   /// corresponding declarator nodes are covered by `SimpleDeclaration`.
@@ -195,8 +233,10 @@
   /// Set role for \p T.
   void markChildToken(const syntax::Token *T, NodeRole R);
 
-  /// Set role for the node that spans exactly \p Range.
-  void markChild(llvm::ArrayRef Range, NodeRole R);
+  /// Set role for \p N.
+  void markChild(syntax::Nod

[PATCH] D76549: [clang-tidy] Fix RenamerClangTidy handling qualified TypeLocs

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

LGTM!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76549



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


[PATCH] D69560: [clang-tidy] Add 'experimental-cppcoreguidelines-avoid-adjacent-arguments-of-the-same-type' check

2020-03-23 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D69560#1936153 , @vingeldal wrote:

> In D69560#1935071 , @whisperity 
> wrote:
>
> > @aaron.ballman I've gone over LLVM (and a few other projects). Some general 
> > observations:
> >
> > - Length of `2` **is vile**. I understand that the C++CG rule says even 
> > lengths of 2 should be matched, but that is industrially infeasible unless 
> > one introduces such a rule incrementally to their project. Findings of 
> > length 2 are **, in general,** an order of magnitude more than... basically 
> > the rest of the findings.
> >   - On big projects, even the current "default" of "length `3`" seems to be 
> > too low. In reality, one should consider (this is likely to be out of scope 
> > for Tidy) how often these functions are called, and various other metrics 
> > on how serious an offender is.
>
>
> Not a problem since existing projects can just use the option and change to 
> whatever level suits them best. My opinion is still that the default 
> shouldn't be set to whatever we think is most useful for the majority of 
> existing projects but to what reflects the actual guideline.


That's what we try to aim for, but ultimately it means we have to decide 
whether that means we're willing to abandon a check over it or not (and we 
traditionally have not abandoned checks, but instead gone with more reasonable 
defaults). This is a case where I would probably rather abandon the check than 
go with that poor of a default behavior.

I think a more productive way forward is to collaborate with the rule authors 
until they have a rule that can be checked and reasonably complied with (which 
I imagine would require some heuristic choices in the rule that we could then 
apply in the check).

> Consider how this situation is similar to the guidelines regarding pointers. 
> The guidelines assume that a project isn't using old standards of C++. Where 
> one has a huge legacy code base it will be impractical at best to try to 
> apply the C++ Core Guidelines for pointer handling on the old code.
> 
> The expectation is that new projects will use the new libraries and language 
> features available to do things differently, in a way that makes it possible  
> and practical to follow the guidelines; while legacy code remains unchecked 
> or incrementally improved.
>  For any new code base this guideline shouldn't be a problem and existing 
> projects can just adapt the usage of this rule to fit their situation by 
> applying it selectively in the code base and/or changing the options.

This is a very different situation, IMO. This is a check that is almost 
impossible to comply with when developing new code because it is insufficiently 
clear on what constitutes "related" parameters. Two adjacent types in a 
function parameter list is an incredibly common situation that arises naturally 
when writing code (especially for constructors, where your parameter order has 
to match the declaration order within the class) and designing around that from 
scratch is not always possible. Retroactively applying this rule to an existing 
code base would be nearly impossible for a project of any size.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69560



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


[PATCH] D70411: [analyzer] CERT: STR31-C

2020-03-23 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus added inline comments.



Comment at: clang/docs/analyzer/checkers.rst:1935
+
+alpha.security.cert.str.31c
+"""

balazske wrote:
> There are already more checkers that can check for CERT related problems but 
> not specially made for these. These checkers do not reside in this new `cert` 
> group. And generally a checker does not check for specifically a CERT rule, 
> instead for more of them or other things too, or more checkers can detect a 
> single rule. (And the user can think that only these CERT rules are checkable 
> that exist in this package, that is not true.) So I do not like the 
> introduction of this new `cert` package. (The documentation of existing 
> checkers lists if the checker is designed for a CERT rule.)
I disagree to some extent. I think it would be great to have a `cert` package 
that houses all checkers for each of the rules with the addition of checker 
aliases. Clang-tidy has something similar as well!


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

https://reviews.llvm.org/D70411



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


[PATCH] D76597: [clang-format] Reflow long C# generic type constraints correctly

2020-03-23 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir accepted this revision.
krasimir added a comment.
This revision is now accepted and ready to land.

Awesome! Thank you!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76597



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


[clang] fa0320d - Add ParsedAttrInfo::handleDeclAttribute

2020-03-23 Thread John Brawn via cfe-commits

Author: John Brawn
Date: 2020-03-23T13:23:11Z
New Revision: fa0320dd8d5aa6ea920ac78224d5044398ba50b4

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

LOG: Add ParsedAttrInfo::handleDeclAttribute

This makes it possible for plugin attributes to actually do something, and also
removes a lot of boilerplate for simple attributes in SemaDeclAttr.cpp.

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

Added: 


Modified: 
clang/docs/ClangPlugins.rst
clang/docs/InternalsManual.rst
clang/include/clang/Basic/Attr.td
clang/include/clang/Sema/ParsedAttr.h
clang/lib/Sema/ParsedAttr.cpp
clang/lib/Sema/SemaDeclAttr.cpp
clang/utils/TableGen/ClangAttrEmitter.cpp

Removed: 




diff  --git a/clang/docs/ClangPlugins.rst b/clang/docs/ClangPlugins.rst
index 23e037e197c9..7e33ea33c0df 100644
--- a/clang/docs/ClangPlugins.rst
+++ b/clang/docs/ClangPlugins.rst
@@ -63,6 +63,53 @@ registering it using ``PragmaHandlerRegistry::Add<>``:
 
   static PragmaHandlerRegistry::Add 
Y("example_pragma","example pragma description");
 
+Defining attributes
+===
+
+Plugins can define attributes by declaring a ``ParsedAttrInfo`` and registering
+it using ``ParsedAttrInfoRegister::Add<>``:
+
+.. code-block:: c++
+
+  class ExampleAttrInfo : public ParsedAttrInfo {
+  public:
+ExampleAttrInfo() {
+  Spellings.push_back({ParsedAttr::AS_GNU,"example"});
+}
+AttrHandling handleDeclAttribute(Sema &S, Decl *D,
+ const ParsedAttr &Attr) const override {
+  // Handle the attribute
+  return AttributeApplied;
+}
+  };
+
+  static ParsedAttrInfoRegistry::Add 
Z("example_attr","example attribute description");
+
+The members of ``ParsedAttrInfo`` that a plugin attribute must define are:
+
+ * ``Spellings``, which must be populated with every `Spelling
+   `_ of the
+   attribute, each of which consists of an attribute syntax and how the
+   attribute name is spelled for that syntax. If the syntax allows a scope then
+   the spelling must be "scope::attr" if a scope is present or "::attr" if not.
+ * ``handleDeclAttribute``, which is the function that applies the attribute to
+   a declaration. It is responsible for checking that the attribute's arguments
+   are valid, and typically applies the attribute by adding an ``Attr`` to the
+   ``Decl``. It returns either ``AttributeApplied``, to indicate that the
+   attribute was successfully applied, or ``AttributeNotApplied`` if it wasn't.
+
+The members of ``ParsedAttrInfo`` that may need to be defined, depending on the
+attribute, are:
+
+ * ``NumArgs`` and ``OptArgs``, which set the number of required and optional
+   arguments to the attribute.
+ * ``diagAppertainsToDecl``, which checks if the attribute has been used on the
+   right kind of declaration and issues a diagnostic if not.
+ * ``diagLangOpts``, which checks if the attribute is permitted for the current
+   language mode and issues a diagnostic if not.
+ * ``existsInTarget``, which checks if the attribute is permitted for the given
+   target.
+
 Putting it all together
 ===
 

diff  --git a/clang/docs/InternalsManual.rst b/clang/docs/InternalsManual.rst
index 3681675a3244..09aec6df69f2 100644
--- a/clang/docs/InternalsManual.rst
+++ b/clang/docs/InternalsManual.rst
@@ -2455,6 +2455,9 @@ Attributes that do not require custom semantic handling 
should set the
 attributes are assumed to use a semantic handler by default. Attributes
 without a semantic handler are not given a parsed attribute ``Kind`` 
enumerator.
 
+"Simple" attributes, that require no custom semantic processing aside from what
+is automatically provided, should set the ``SimpleHandler`` field to ``1``.
+
 Target-specific attributes may share a spelling with other attributes in
 
diff erent targets. For instance, the ARM and MSP430 targets both have an
 attribute spelled ``GNU<"interrupt">``, but with 
diff erent parsing and semantic
@@ -2481,12 +2484,11 @@ Boilerplate
 All semantic processing of declaration attributes happens in 
`lib/Sema/SemaDeclAttr.cpp
 
`_,
 and generally starts in the ``ProcessDeclAttribute()`` function. If the
-attribute is a "simple" attribute -- meaning that it requires no custom 
semantic
-processing aside from what is automatically  provided, add a call to
-``handleSimpleAttribute(S, D, Attr);`` to the switch statement.
-Otherwise, write a new ``handleYourAttr()`` function, and add that to the 
switch
-statement. Please do not implement handling logic directly in the ``case`` for
-the attribute.
+attribute has the ``SimpleHandler`` field set to ``1`` then the function to
+process the attribute will be automaticall

[PATCH] D76054: [clang-apply-replacements] No longer deduplucates replacements from the same TU

2020-03-23 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel accepted this revision.
ymandel added a comment.
This revision is now accepted and ready to land.

Thanks for the example and, generally, explanation. Just a few small comments.




Comment at: 
clang-tools-extra/clang-apply-replacements/lib/Tooling/ApplyReplacements.cpp:148
   // FIXME: Find an efficient way to deduplicate on diagnostics level.
-  llvm::DenseMap>
+  llvm::DenseMap 
%T/Inputs/identical2/identical2.cpp
+// RUN: sed "s#\$(path)#%/T/Inputs/identical2#" 
%S/Inputs/identical2/file1.yaml > %T/Inputs/identical2/file1.yaml
+// RUN: sed "s#\$(path)#%/T/Inputs/identical2#" 
%S/Inputs/identical2/file2.yaml > %T/Inputs/identical2/file2.yaml

Why is this `%/T` rather than `%T`? I realize it is the same in 
`identical.cpp`, but just want to understand what I'm reading...



Comment at: clang-tools-extra/test/clang-apply-replacements/identical2.cpp:8
+
+// Similar to identical test but each yaml file contains the same fix twice. 
+// This check ensures that only the duplicated replacements in a single yaml 

Consider differentiating the name of this test more and making it more 
descriptive, e.g. identical_in_TU. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76054



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


[PATCH] D76604: [Analyzer] Model `size()` member function of containers

2020-03-23 Thread Balogh, Ádám via Phabricator via cfe-commits
baloghadamsoftware created this revision.
baloghadamsoftware added reviewers: NoQ, Szelethus, martong.
baloghadamsoftware added a project: clang.
Herald added subscribers: ASDenysPetrov, steakhal, Charusso, gamesh411, dkrupp, 
donat.nagy, mikhail.ramalho, a.sidorin, rnkovacs, szepet, xazax.hun, whisperity.
baloghadamsoftware added a parent revision: D76590: [Analyzer] Model `empty()` 
member function of containers.
baloghadamsoftware added a comment.

Supersedes D62724 .


After `empty()`, also model `size()` to further improve existing checkers and 
enable more future checkers for iterators and containers.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D76604

Files:
  clang/lib/StaticAnalyzer/Checkers/ContainerModeling.cpp
  clang/lib/StaticAnalyzer/Checkers/Iterator.cpp
  clang/lib/StaticAnalyzer/Checkers/Iterator.h
  clang/test/Analysis/container-modeling.cpp

Index: clang/test/Analysis/container-modeling.cpp
===
--- clang/test/Analysis/container-modeling.cpp
+++ clang/test/Analysis/container-modeling.cpp
@@ -89,6 +89,35 @@
   // expected-warning@-2{{FALSE}}
 }
 
+void size0(const std::vector& V) {
+  if (V.size() != 0)
+return;
+
+  clang_analyzer_eval(clang_analyzer_container_end(V) ==
+  clang_analyzer_container_begin(V));
+  // expected-warning@-2{{TRUE}}
+}
+
+void size1(const std::vector& V) {
+  if (V.size() != 1)
+return;
+
+  clang_analyzer_eval(clang_analyzer_container_end(V) ==
+  clang_analyzer_container_begin(V) + 1);
+  // expected-warning@-2{{TRUE}}
+}
+
+void size12(std::vector& V) {
+  if (V.size() != 1)
+return;
+
+  V.push_back(1);
+
+  clang_analyzer_eval(clang_analyzer_container_end(V) ==
+  clang_analyzer_container_begin(V) + 2);
+  // expected-warning@-2{{TRUE}}
+}
+
 
 ///
 /// C O N T A I N E R   M O D I F I E R S
Index: clang/lib/StaticAnalyzer/Checkers/Iterator.h
===
--- clang/lib/StaticAnalyzer/Checkers/Iterator.h
+++ clang/lib/StaticAnalyzer/Checkers/Iterator.h
@@ -172,6 +172,8 @@
 std::pair
 assumeComparison(ProgramStateRef State, SymbolRef Sym1, SymbolRef Sym2,
  DefinedSVal RetVal, OverloadedOperatorKind Op);
+ProgramStateRef relateSymbols(ProgramStateRef State, SymbolRef Sym1,
+  SymbolRef Sym2, bool Equal);
 bool compare(ProgramStateRef State, SymbolRef Sym1, SymbolRef Sym2,
  BinaryOperator::Opcode Opc);
 bool compare(ProgramStateRef State, NonLoc NL1, NonLoc NL2,
Index: clang/lib/StaticAnalyzer/Checkers/Iterator.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/Iterator.cpp
+++ clang/lib/StaticAnalyzer/Checkers/Iterator.cpp
@@ -16,9 +16,6 @@
 namespace ento {
 namespace iterator {
 
-ProgramStateRef relateSymbols(ProgramStateRef State, SymbolRef Sym1,
-  SymbolRef Sym2, bool Equal);
-
 bool isIteratorType(const QualType &Type) {
   if (Type->isPointerType())
 return true;
Index: clang/lib/StaticAnalyzer/Checkers/ContainerModeling.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/ContainerModeling.cpp
+++ clang/lib/StaticAnalyzer/Checkers/ContainerModeling.cpp
@@ -39,6 +39,8 @@
 SVal OldCont = UndefinedVal()) const;
   void handleEmpty(CheckerContext &C, const Expr *CE, SVal Cont,
SVal RetVal) const;
+  void handleSize(CheckerContext &C, const Expr *CE, SVal Cont,
+   SVal RetVal) const;
   void handleAssign(CheckerContext &C, const Expr *CE, SVal Cont,
 SVal RetVal) const;
   void handleClear(CheckerContext &C, const Expr *CE, SVal Cont,
@@ -84,6 +86,8 @@
 // Capacity
 {{0, "empty", 0},
  &ContainerModeling::handleEmpty},
+{{0, "size", 0},
+ &ContainerModeling::handleSize},
 
 // Modifiers
 {{0, "clear", 0},
@@ -169,6 +173,8 @@
 SymbolRef rebaseSymbol(ProgramStateRef State, SValBuilder &SVB, SymbolRef Expr,
 SymbolRef OldSym, SymbolRef NewSym);
 bool hasLiveIterators(ProgramStateRef State, const MemRegion *Cont);
+const llvm::APSInt* calculateSize(ProgramStateRef State, SymbolRef Begin,
+  SymbolRef End);
 
 } // namespace
 
@@ -445,6 +451,72 @@
   }
 }
 
+void ContainerModeling::handleSize(CheckerContext &C, const Expr *CE, SVal Cont,
+   SVal RetVal) const {
+  const auto *ContReg = Cont.getAsRegion();
+  if (!ContReg)
+return;
+
+  ContReg = ContReg->getMostDerivedObjectRegion();
+
+  auto State = C.getState();
+
+  State = createContainerBegin(State, ContReg, CE, C.getASTContext().LongTy,
+   C.getLocationCont

[PATCH] D62724: [Analyzer] Iterator Checkers - Model `size()` method of containers

2020-03-23 Thread Balogh, Ádám via Phabricator via cfe-commits
baloghadamsoftware abandoned this revision.
baloghadamsoftware added a comment.
Herald added subscribers: ASDenysPetrov, martong, steakhal.

Superseded by D76604 .


Repository:
  rC Clang

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

https://reviews.llvm.org/D62724



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


[PATCH] D76094: [clangd] Change line break behaviour for hoverinfo

2020-03-23 Thread Lorenz Junglas via Phabricator via cfe-commits
lolleko updated this revision to Diff 252006.
lolleko added a comment.

Adressed 2nd Review

The problem with the changes you proposed is that it doesn't handle paragraphs 
(\n\n).
I think the conditionals required to make that work wouldn't be much cleaner 
than the current solution.

And I do think parahraphs in comments should be retained. I agree that not 
every hard line break should be a pargraph.
But actual parahraphs should be retained e.g.:

/**
 * Condition for calling UpdateOverlaps() to initialize overlap state 
when loaded in during level streaming.
 * If set to 'UseConfigDefault', the default specified in ini 
(displayed in 'DefaultUpdateOverlapsMethodDuringLevelStreaming') will be used.
 * If overlaps are not initialized, this actor and attached components 
will not have an initial state of what objects are touching it,
 * and overlap events may only come in once one of those objects update 
overlaps themselves (for example when moving).
 * However if an object touching it *does* initialize state, both 
objects will know about their touching state with each other.
 * This can be a potentially large performance savings during level 
streaming, and is safe if the object and others initially
 * overlapping it do not need the overlap state because they will not 
trigger overlap notifications.
 * 
 * Note that if 'bGenerateOverlapEventsDuringLevelStreaming' is true, 
overlaps are always updated in this case, but that flag
 * determines whether the Begin/End overlap events are triggered.
 * 
 * @see bGenerateOverlapEventsDuringLevelStreaming, 
DefaultUpdateOverlapsMethodDuringLevelStreaming, 
GetUpdateOverlapsMethodDuringLevelStreaming()
 */

I think once proper paragraphs are in. The linebreak parsing could be rewritten 
into 2 steps:

1. Split on `\n\n` to extract actual paragraphs.
2. Use the solution you proposed to split and join new lines.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76094

Files:
  clang-tools-extra/clangd/Hover.cpp
  clang-tools-extra/clangd/Hover.h
  clang-tools-extra/clangd/unittests/HoverTests.cpp

Index: clang-tools-extra/clangd/unittests/HoverTests.cpp
===
--- clang-tools-extra/clangd/unittests/HoverTests.cpp
+++ clang-tools-extra/clangd/unittests/HoverTests.cpp
@@ -1883,6 +1883,119 @@
   }
 }
 
+TEST(Hover, DocCommentLineBreakConversion) {
+  struct Case {
+llvm::StringRef Documentation;
+llvm::StringRef ExpectedRenderMarkdown;
+llvm::StringRef ExpectedRenderPlainText;
+  } Cases[] = {{
+   "foo\n\n\nbar",
+   "foo  \nbar",
+   "foo\nbar",
+   },
+   {
+   "foo\n\n\n\tbar",
+   "foo  \nbar",
+   "foo\nbar",
+   },
+   {
+   "foo\n\n\n bar",
+   "foo  \nbar",
+   "foo\nbar",
+   },
+   {
+   "foo.\nbar",
+   "foo.  \nbar",
+   "foo.\nbar",
+   },
+   {
+   "foo:\nbar",
+   "foo:  \nbar",
+   "foo:\nbar",
+   },
+   {
+   "foo,\nbar",
+   "foo,  \nbar",
+   "foo,\nbar",
+   },
+   {
+   "foo;\nbar",
+   "foo;  \nbar",
+   "foo;\nbar",
+   },
+   {
+   "foo!\nbar",
+   "foo!  \nbar",
+   "foo!\nbar",
+   },
+   {
+   "foo?\nbar",
+   "foo?  \nbar",
+   "foo?\nbar",
+   },
+   {
+   "foo\n-bar",
+   "foo  \n-bar",
+   "foo\n-bar",
+   },
+   {
+   "foo\n*bar",
+   // TODO `*` should probably not be escaped after line break
+   "foo  \n\\*bar",
+   "foo\n*bar",
+   },
+   {
+   "foo\n@bar",
+   "foo  \n@bar",
+   "foo\n@bar",
+   },
+   {
+   "foo\n\\bar",
+   // TODO `\` should probably not be escaped after line break
+   "foo  \nbar",
+   "foo\n\\bar",
+   },
+   {
+   "foo\n>bar",
+   // TODO `>` should probably not be escaped after line break
+   "foo  \n\\>bar",
+   "foo\n>bar",
+   },
+   {
+   "foo\n#bar",
+   "foo  \n#bar"

[PATCH] D76604: [Analyzer] Model `size()` member function of containers

2020-03-23 Thread Balogh, Ádám via Phabricator via cfe-commits
baloghadamsoftware added a comment.

Supersedes D62724 .


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76604



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


[PATCH] D76606: [clang-tidy] Warn on invalid "case" configurations for readability-identifier-naming

2020-03-23 Thread Nathan James via Phabricator via cfe-commits
njames93 marked 2 inline comments as done.
njames93 added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp:154
+  llvm::errs() << "warning: Invalid case style '" << CaseValue
+   << "' for readability-identifier-naming." << CaseOptionName;
+  constexpr StringRef AcceptibleNames[] = {

Unsure about hardcoding the check-name as it could be ran under an alias. 
However there is no way for a ClangTidyCheck to get the name its ran as. 
`ClangTidyCheck::CheckName` is `private`, maybe a protected getter would be 
wise.



Comment at: 
clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp:177
+  if (EditDistance < 3)
+llvm::errs() << ": did you mean '" << Closest << "'\n";
+  else

I feel its safer not assuming the fix and instead letting the user modify their 
configuration, WDYT?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76606



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


[PATCH] D76605: [analyzer] Display the checker name in the text output

2020-03-23 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus created this revision.
Szelethus added reviewers: NoQ, baloghadamsoftware, balazske, martong, 
xazax.hun, dcoughlin, rnkovacs.
Szelethus added a project: clang.
Herald added subscribers: cfe-commits, ASDenysPetrov, steakhal, Charusso, 
gamesh411, dkrupp, donat.nagy, mikhail.ramalho, a.sidorin, szepet, whisperity.
Szelethus added a parent revision: D76509: [analyzer][NFC] Move the text output 
type to its own file, move code to PathDiagnosticConsumer creator functions.

Exactly what it says on the tin! There is no reason I think not to have this.

Also, I added test files for checkers that emit warning under the wrong name.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D76605

Files:
  clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
  clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp
  clang/test/Analysis/analyzer-config.c
  clang/test/Analysis/dispatch-once.m
  clang/test/Analysis/explain-svals.c
  clang/test/Analysis/explain-svals.cpp
  clang/test/Analysis/explain-svals.m
  clang/test/Analysis/incorrect-checker-names.cpp
  clang/test/Analysis/incorrect-checker-names.mm

Index: clang/test/Analysis/incorrect-checker-names.mm
===
--- /dev/null
+++ clang/test/Analysis/incorrect-checker-names.mm
@@ -0,0 +1,116 @@
+// RUN: %clang_analyze_cc1 -fblocks -verify %s -Wno-objc-root-class \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=nullability \
+// RUN:   -analyzer-checker=osx
+
+#include "Inputs/system-header-simulator-for-nullability.h"
+#include "os_object_base.h"
+
+struct OSIterator : public OSObject {
+  static const OSMetaClass * const metaClass;
+};
+
+@interface TestObject : NSObject
+- (int *_Nonnull)returnsNonnull;
+- (int *_Nullable)returnsNullable;
+- (int *)returnsUnspecified;
+- (void)takesNonnull:(int *_Nonnull)p;
+- (void)takesNullable:(int *_Nullable)p;
+- (void)takesUnspecified:(int *)p;
+@property(readonly, strong) NSString *stuff;
+@end
+
+TestObject * getUnspecifiedTestObject();
+TestObject *_Nonnull getNonnullTestObject();
+TestObject *_Nullable getNullableTestObject();
+
+int getRandom();
+
+typedef struct Dummy { int val; } Dummy;
+
+void takesNullable(Dummy *_Nullable);
+void takesNonnull(Dummy *_Nonnull);
+void takesUnspecified(Dummy *);
+
+Dummy *_Nullable returnsNullable();
+Dummy *_Nonnull returnsNonnull();
+Dummy *returnsUnspecified();
+int *_Nullable returnsNullableInt();
+
+template  T *eraseNullab(T *p) { return p; }
+
+void takesAttrNonnull(Dummy *p) __attribute((nonnull(1)));
+
+void testBasicRules() {
+  // FIXME: None of these should be tied to a modeling checker.
+  Dummy *p = returnsNullable();
+  int *ptr = returnsNullableInt();
+  // Make every dereference a different path to avoid sinks after errors.
+  switch (getRandom()) {
+  case 0: {
+Dummy &r = *p; // expected-warning {{Nullable pointer is dereferenced [nullability.NullabilityBase]}}
+  } break;
+  case 1: {
+int b = p->val; // expected-warning {{Nullable pointer is dereferenced [nullability.NullabilityBase]}}
+  } break;
+  case 2: {
+int stuff = *ptr; // expected-warning {{Nullable pointer is dereferenced [nullability.NullabilityBase]}}
+  } break;
+  case 3:
+takesNonnull(p); // expected-warning {{Nullable pointer is passed to a callee that requires a non-null 1st parameter [nullability.NullabilityBase]}}
+break;
+  case 4: {
+Dummy d;
+takesNullable(&d);
+Dummy dd(d);
+break;
+  }
+  case 5: takesAttrNonnull(p); break; // expected-warning {{Nullable pointer is passed to a callee that requires a non-null [nullability.NullabilityBase]}}
+  default: { Dummy d = *p; } break; // expected-warning {{Nullable pointer is dereferenced [nullability.NullabilityBase]}}
+  }
+  if (p) {
+takesNonnull(p);
+if (getRandom()) {
+  Dummy &r = *p;
+} else {
+  int b = p->val;
+}
+  }
+  Dummy *q = 0;
+  if (getRandom()) {
+takesNullable(q);
+  // FIXME: This shouldn't be tied to a modeling checker.
+takesNonnull(q); // expected-warning {{Null passed to a callee that requires a non-null 1st parameter [nullability.NullabilityBase]}}
+  }
+  Dummy a;
+  Dummy *_Nonnull nonnull = &a;
+  // FIXME: This shouldn't be tied to a modeling checker.
+  nonnull = q; // expected-warning {{Null assigned to a pointer which is expected to have non-null value [nullability.NullabilityBase]}}
+  q = &a;
+  takesNullable(q);
+  takesNonnull(q);
+}
+
+typedef int NSInteger;
+typedef struct _NSZone NSZone;
+@class NSInvocation, NSMethodSignature, NSCoder, NSString, NSEnumerator;
+@class NSDictionary;
+@interface NSError : NSObject  {}
++ (id)errorWithDomain:(NSString *)domain code:(NSInteger)code userInfo:(NSDictionary *)dict;
+@end
+
+struct __CFError {};
+typedef struct __CFError* CFErrorRef;
+
+void foo(CFErrorRef* error) { // expected-warning{{Function accepting CFErrorRef* should have a non-void return value to indicate whether or not an error occurred [osx.c

[PATCH] D76606: [clang-tidy] Warn on invalid "case" configurations for readability-identifier-naming

2020-03-23 Thread Nathan James via Phabricator via cfe-commits
njames93 created this revision.
njames93 added reviewers: aaron.ballman, alexfh.
Herald added subscribers: cfe-commits, xazax.hun.
Herald added a project: clang.
njames93 marked 2 inline comments as done.
njames93 added a project: clang-tools-extra.
njames93 added a comment.

I'm not too sure how many other checks are like this, but I feel that this 
functionality could maybe be brought out of this check and into the Options to 
let more checks that take enum like configurations to use it.




Comment at: 
clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp:154
+  llvm::errs() << "warning: Invalid case style '" << CaseValue
+   << "' for readability-identifier-naming." << CaseOptionName;
+  constexpr StringRef AcceptibleNames[] = {

Unsure about hardcoding the check-name as it could be ran under an alias. 
However there is no way for a ClangTidyCheck to get the name its ran as. 
`ClangTidyCheck::CheckName` is `private`, maybe a protected getter would be 
wise.



Comment at: 
clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp:177
+  if (EditDistance < 3)
+llvm::errs() << ": did you mean '" << Closest << "'\n";
+  else

I feel its safer not assuming the fix and instead letting the user modify their 
configuration, WDYT?


Issue a warning (and potential fix hint) when an invalid case value is supplied 
to readability-identifier-naming configuration.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D76606

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


Index: 
clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-case-validation.cpp
===
--- /dev/null
+++ 
clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-case-validation.cpp
@@ -0,0 +1,16 @@
+// RUN: clang-tidy %s -checks=readability-identifier-naming \
+// RUN:   -config="{CheckOptions: [\
+// RUN:   {key: readability-identifier-naming.FunctionCase, value: camelback}, 
\
+// RUN:   {key: readability-identifier-naming.VariableCase, value: camelBack}, 
\
+// RUN:   {key: readability-identifier-naming.ClassCase, value: UUPER_CASE}, \
+// RUN:   {key: readability-identifier-naming.StructCase, value: CAMEL}, \
+// RUN:   {key: readability-identifier-naming.EnumCase, value: AnY_cASe}, \
+// RUN:   ]}" 2>&1 | FileCheck %s --implicit-check-not warning
+
+
+// CHECK-DAG: warning: Invalid case style 'camelback' for 
readability-identifier-naming.FunctionCase: did you mean 'camelBack'{{$}}
+// CHECK-DAG: warning: Invalid case style 'UUPER_CASE' for 
readability-identifier-naming.ClassCase: did you mean 'UPPER_CASE'{{$}}
+// Don't try to suggest an alternative for 'CAMEL'
+// CHECK-DAG: warning: Invalid case style 'CAMEL' for 
readability-identifier-naming.StructCase{{$}}
+// This fails on the EditDistance, but as it matches ignoring case suggest the 
correct value
+// CHECK-DAG: warning: Invalid case style 'AnY_cASe' for 
readability-identifier-naming.EnumCase: did you mean 'aNy_CasE'{{$}}
Index: clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
===
--- clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
+++ clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
@@ -95,6 +95,15 @@
 };
 
 #undef NAMING_KEYS
+
+#define CASE_KEYS(m) \
+m("aNy_CasE", CT_AnyCase) \
+m("lower_case", CT_LowerCase) \
+m("UPPER_CASE", CT_UpperCase) \
+m("camelBack", CT_CamelBack) \
+m("CamelCase", CT_CamelCase) \
+m("Camel_Snake_Case", CT_CamelSnakeCase) \
+m("camel_Snake_Back", CT_CamelSnakeBack)
 // clang-format on
 
 namespace {
@@ -131,19 +140,44 @@
   IgnoreMainLikeFunctions(Options.get("IgnoreMainLikeFunctions", 0)) {
   auto const fromString = [](StringRef Str) {
 return llvm::StringSwitch>(Str)
-.Case("aNy_CasE", CT_AnyCase)
-.Case("lower_case", CT_LowerCase)
-.Case("UPPER_CASE", CT_UpperCase)
-.Case("camelBack", CT_CamelBack)
-.Case("CamelCase", CT_CamelCase)
-.Case("Camel_Snake_Case", CT_CamelSnakeCase)
-.Case("camel_Snake_Back", CT_CamelSnakeBack)
-.Default(llvm::None);
+#define CASE(NAME, ENUM) .Case(NAME, ENUM)
+CASE_KEYS(CASE)
+#undef CASE
+.Default(llvm::None);
   };
-
   for (auto const &Name : StyleNames) {
-auto const caseOptional =
-fromString(Options.get((Name + "Case").str(), ""));
+auto CaseOptionName = (Name + "Case").str();
+auto CaseValue = Options.get(CaseOptionName, "");
+auto const caseOptional = fromString(CaseValue);
+if (!caseOptional && !CaseValue.empty()) {
+  llvm::errs() << "warning: Invalid case style '" << CaseValue
+ 

[PATCH] D75844: [clang] Set begin loc on GNU attribute parsed attrs

2020-03-23 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder marked an inline comment as done.
tbaeder added a comment.

Thanks, I'll take a look at the tests.




Comment at: clang/test/SemaCXX/switch-implicit-fallthrough.cpp:110-114
+case 26:
+  return 0;
+__attribute__((fallthrough)); // expected-warning{{fallthrough annotation 
in unreachable code}}
+case 27:
+  break;

aaron.ballman wrote:
> This test seems unrelated to the patch, or am I misunderstanding something?
This is the test that prompted me to write this patch - before this patch, the 
error message has an invalid loc. I guess I should remove this here and move it 
over to the source ranges tests and also test that is has the right source 
range.


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

https://reviews.llvm.org/D75844



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


[PATCH] D76606: [clang-tidy] Warn on invalid "case" configurations for readability-identifier-naming

2020-03-23 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

I'm not too sure how many other checks are like this, but I feel that this 
functionality could maybe be brought out of this check and into the Options to 
let more checks that take enum like configurations to use it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76606



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


[PATCH] D31342: Add ParsedAttrInfo::handleDeclAttribute

2020-03-23 Thread John Brawn via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGfa0320dd8d5a: Add ParsedAttrInfo::handleDeclAttribute 
(authored by john.brawn).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D31342

Files:
  clang/docs/ClangPlugins.rst
  clang/docs/InternalsManual.rst
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Sema/ParsedAttr.h
  clang/lib/Sema/ParsedAttr.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/utils/TableGen/ClangAttrEmitter.cpp

Index: clang/utils/TableGen/ClangAttrEmitter.cpp
===
--- clang/utils/TableGen/ClangAttrEmitter.cpp
+++ clang/utils/TableGen/ClangAttrEmitter.cpp
@@ -3661,6 +3661,20 @@
   OS << "}\n\n";
 }
 
+static void GenerateHandleDeclAttribute(const Record &Attr, raw_ostream &OS) {
+  // Only generate if Attr can be handled simply.
+  if (!Attr.getValueAsBit("SimpleHandler"))
+return;
+
+  // Generate a function which just converts from ParsedAttr to the Attr type.
+  OS << "virtual AttrHandling handleDeclAttribute(Sema &S, Decl *D,";
+  OS << "const ParsedAttr &Attr) const {\n";
+  OS << "  D->addAttr(::new (S.Context) " << Attr.getName();
+  OS << "Attr(S.Context, Attr));\n";
+  OS << "  return AttributeApplied;\n";
+  OS << "}\n\n";
+}
+
 static bool IsKnownToGCC(const Record &Attr) {
   // Look at the spellings for this subject; if there are any spellings which
   // claim to be known to GCC, the attribute is known to GCC.
@@ -3742,6 +3756,7 @@
 GenerateTargetRequirements(Attr, Dupes, OS);
 GenerateSpellingIndexToSemanticSpelling(Attr, OS);
 PragmaAttributeSupport.generateStrictConformsTo(*I->second, OS);
+GenerateHandleDeclAttribute(Attr, OS);
 OS << "static const ParsedAttrInfo" << I->first << " Instance;\n";
 OS << "};\n";
 OS << "const ParsedAttrInfo" << I->first << " ParsedAttrInfo" << I->first
Index: clang/lib/Sema/SemaDeclAttr.cpp
===
--- clang/lib/Sema/SemaDeclAttr.cpp
+++ clang/lib/Sema/SemaDeclAttr.cpp
@@ -6747,6 +6747,8 @@
 
   switch (AL.getKind()) {
   default:
+if (AL.getInfo().handleDeclAttribute(S, D, AL) != ParsedAttrInfo::NotHandled)
+  break;
 if (!AL.isStmtAttr()) {
   // Type attributes are handled elsewhere; silently move on.
   assert(AL.isTypeAttr() && "Non-type attribute not handled");
@@ -6769,15 +6771,9 @@
 handleSimpleAttributeWithExclusions(S, D, AL);
 break;
-  case ParsedAttr::AT_NoMips16:
-handleSimpleAttribute(S, D, AL);
-break;
   case ParsedAttr::AT_MicroMips:
 handleSimpleAttributeWithExclusions(S, D, AL);
 break;
-  case ParsedAttr::AT_NoMicroMips:
-handleSimpleAttribute(S, D, AL);
-break;
   case ParsedAttr::AT_MipsLongCall:
 handleSimpleAttributeWithExclusions(
 S, D, AL);
@@ -6813,9 +6809,6 @@
   case ParsedAttr::AT_WebAssemblyImportName:
 handleWebAssemblyImportNameAttr(S, D, AL);
 break;
-  case ParsedAttr::AT_IBAction:
-handleSimpleAttribute(S, D, AL);
-break;
   case ParsedAttr::AT_IBOutlet:
 handleIBOutlet(S, D, AL);
 break;
@@ -6840,9 +6833,6 @@
   case ParsedAttr::AT_AlwaysInline:
 handleAlwaysInlineAttr(S, D, AL);
 break;
-  case ParsedAttr::AT_Artificial:
-handleSimpleAttribute(S, D, AL);
-break;
   case ParsedAttr::AT_AnalyzerNoReturn:
 handleAnalyzerNoReturnAttr(S, D, AL);
 break;
@@ -6874,9 +6864,6 @@
   case ParsedAttr::AT_Constructor:
 handleConstructorAttr(S, D, AL);
 break;
-  case ParsedAttr::AT_CXX11NoReturn:
-handleSimpleAttribute(S, D, AL);
-break;
   case ParsedAttr::AT_Deprecated:
 handleDeprecatedAttr(S, D, AL);
 break;
@@ -6904,15 +6891,9 @@
   case ParsedAttr::AT_OptimizeNone:
 handleOptimizeNoneAttr(S, D, AL);
 break;
-  case ParsedAttr::AT_FlagEnum:
-handleSimpleAttribute(S, D, AL);
-break;
   case ParsedAttr::AT_EnumExtensibility:
 handleEnumExtensibilityAttr(S, D, AL);
 break;
-  case ParsedAttr::AT_Flatten:
-handleSimpleAttribute(S, D, AL);
-break;
   case ParsedAttr::AT_SYCLKernel:
 handleSYCLKernelAttr(S, D, AL);
 break;
@@ -6948,27 +6929,9 @@
   case ParsedAttr::AT_Restrict:
 handleRestrictAttr(S, D, AL);
 break;
-  case ParsedAttr::AT_LifetimeBound:
-handleSimpleAttribute(S, D, AL);
-break;
-  case ParsedAttr::AT_MayAlias:
-handleSimpleAttribute(S, D, AL);
-break;
   case ParsedAttr::AT_Mode:
 handleModeAttr(S, D, AL);
 break;
-  case ParsedAttr::AT_NoAlias:
-handleSimpleAttribute(S, D, AL);
-break;
-  case ParsedAttr::AT_NoCommon:
-handleSimpleAttribute(S, D, AL);
-break;
-  case ParsedAttr::AT_NoSplitStack:
-handleSimpleAttribute(S, D, AL);
-break;
-  case ParsedAttr::AT_NoUniqueAddress:
-handleSimpleAttribute(S, D, AL);
-break;
   case ParsedAttr::AT_NonNull:
 if (auto *PVD = dyn_cas

[PATCH] D76607: [clang-query] Add replace command

2020-03-23 Thread Alexander Timin via Phabricator via cfe-commits
altimin created this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

DO NOT SUBMIT: Early prototype


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D76607

Files:
  clang-tools-extra/clang-query/Query.cpp
  clang-tools-extra/clang-query/Query.h
  clang-tools-extra/clang-query/QueryParser.cpp

Index: clang-tools-extra/clang-query/QueryParser.cpp
===
--- clang-tools-extra/clang-query/QueryParser.cpp
+++ clang-tools-extra/clang-query/QueryParser.cpp
@@ -161,6 +161,7 @@
   PQK_Let,
   PQK_Match,
   PQK_Set,
+  PQK_Replace,
   PQK_Unlet,
   PQK_Quit,
   PQK_Enable,
@@ -202,6 +203,8 @@
   .Case("let", PQK_Let)
   .Case("m", PQK_Match, /*IsCompletion=*/false)
   .Case("match", PQK_Match)
+  .Case("r", PQK_Replace, /*IsCompletion=*/false)
+  .Case("replace",  PQK_Replace)
   .Case("q", PQK_Quit,  /*IsCompletion=*/false)
   .Case("quit", PQK_Quit)
   .Case("set", PQK_Set)
@@ -265,6 +268,20 @@
 return Q;
   }
 
+  case PQK_Replace: {
+Diagnostics Diag;
+auto MatcherAndReplacementSource = Line.split(";");
+auto MatcherSource = MatcherAndReplacementSource.first.ltrim();
+Optional Matcher = Parser::parseMatcherExpression(
+MatcherSource, nullptr, &QS.NamedValues, &Diag);
+if (!Matcher) {
+  fprintf(stderr, "### Failed to construct matcher");
+  return makeInvalidQueryFromDiagnostics(Diag);
+}
+auto *Q = new ReplaceQuery(MatcherAndReplacementSource.second.trim(), *Matcher);
+return Q;
+  }
+
   case PQK_Set: {
 StringRef VarStr;
 ParsedQueryVariable Var =
Index: clang-tools-extra/clang-query/Query.h
===
--- clang-tools-extra/clang-query/Query.h
+++ clang-tools-extra/clang-query/Query.h
@@ -26,6 +26,7 @@
   QK_Help,
   QK_Let,
   QK_Match,
+  QK_Replace,
   QK_SetBool,
   QK_SetOutputKind,
   QK_EnableOutputKind,
@@ -98,6 +99,19 @@
   static bool classof(const Query *Q) { return Q->Kind == QK_Match; }
 };
 
+/// Query for "replace MATCHER REPLACEMENT"
+struct ReplaceQuery : Query {
+  ReplaceQuery(StringRef ReplacementSource, const ast_matchers::dynamic::DynTypedMatcher &Matcher)
+  : Query(QK_Replace), Matcher(Matcher), ReplacementSource(ReplacementSource) {}
+  bool run(llvm::raw_ostream &OS, QuerySession &QS) const override;
+
+  ast_matchers::dynamic::DynTypedMatcher Matcher;
+
+  StringRef ReplacementSource;
+
+  static bool classof(const Query *Q) { return Q->Kind == QK_Replace; }
+};
+
 struct LetQuery : Query {
   LetQuery(StringRef Name, const ast_matchers::dynamic::VariantValue &Value)
   : Query(QK_Let), Name(Name), Value(Value) {}
Index: clang-tools-extra/clang-query/Query.cpp
===
--- clang-tools-extra/clang-query/Query.cpp
+++ clang-tools-extra/clang-query/Query.cpp
@@ -9,10 +9,21 @@
 #include "Query.h"
 #include "QuerySession.h"
 #include "clang/AST/ASTDumper.h"
+#include "clang/AST/ExprConcepts.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Basic/CharInfo.h"
+#include "clang/Basic/LLVM.h"
+#include "clang/Basic/LangOptions.h"
 #include "clang/Frontend/ASTUnit.h"
 #include "clang/Frontend/TextDiagnostic.h"
+#include "clang/Sema/DeclSpec.h"
+#include "clang/Tooling/Core/Diagnostic.h"
+#include "clang/Tooling/Core/Replacement.h"
+#include "clang/Tooling/DiagnosticsYaml.h"
+#include "clang/Tooling/ReplacementsYaml.h"
+#include "llvm/ADT/None.h"
 #include "llvm/Support/raw_ostream.h"
+#include "llvm/Support/YAMLTraits.h"
 
 using namespace clang::ast_matchers;
 using namespace clang::ast_matchers::dynamic;
@@ -162,6 +173,179 @@
   return true;
 }
 
+namespace {
+
+class ReplacementParser {
+ public:
+  ReplacementParser(StringRef ReplacementPattern, const ast_matchers::internal::BoundNodesMap::IDToNodeMap& BoundNodes, SourceManager& SourceManager):
+ReplacementPattern(ReplacementPattern), BoundNodes(BoundNodes), SM(SourceManager) {
+  Result.reserve(ReplacementPattern.size());
+}
+
+  Optional Parse() {
+while (!StreamFinished() && !Failed) {
+  char Char = ReadChar();
+
+  if (Char == '$') {
+if (StreamFinished()) {
+  Fail("$ should be either be escaped ($$) or be a part of a lookup instruction ($(name))");
+  continue;
+}
+if (GetCurrentChar() == '$') {
+  // Skip the second $.
+  ReadChar();
+  Result.append(1, Char);
+  continue;
+}
+Result.append(LookUpValueForBoundName(ParseBoundName()));
+  } else {
+Result.append(1, Char);
+  }
+}
+
+if (Failed)
+  return llvm::None;
+return Result;
+  }
+
+  std::string getError() {
+ 

[clang] 78e2a3c - [clang-format] Reflow long C# generic type constraints correctly

2020-03-23 Thread Jonathan Coe via cfe-commits

Author: Jonathan Coe
Date: 2020-03-23T13:38:21Z
New Revision: 78e2a3c678463caeec1524baa96cdeb6fcdb48be

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

LOG: [clang-format] Reflow long C# generic type constraints correctly

Summary:
Align sequential generic type constraints on a type.

Indent sequential generic type constraints on different types as continuations.

Do not allow '(' and '<' within a generic type constraint to open new scopes.

Reviewers: krasimir

Subscribers: cfe-commits, MyDeveloperDay

Tags: #clang-format, #clang

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

Added: 


Modified: 
clang/lib/Format/ContinuationIndenter.cpp
clang/lib/Format/ContinuationIndenter.h
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/ContinuationIndenter.cpp 
b/clang/lib/Format/ContinuationIndenter.cpp
index 9a6d7877efaa..d2397dbfeb87 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -634,6 +634,7 @@ void ContinuationIndenter::addTokenOnCurrentLine(LineState 
&State, bool DryRun,
 State.Stack.back().NoLineBreak = true;
 
   if (Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign &&
+  !State.Stack.back().IsCSharpGenericTypeConstraint &&
   Previous.opensScope() && Previous.isNot(TT_ObjCMethodExpr) &&
   (Current.isNot(TT_LineComment) || Previous.BlockKind == BK_BracedInit))
 State.Stack.back().Indent = State.Column + Spaces;
@@ -715,6 +716,8 @@ void ContinuationIndenter::addTokenOnCurrentLine(LineState 
&State, bool DryRun,
   } else if (Previous.is(TT_InheritanceColon)) {
 State.Stack.back().Indent = State.Column;
 State.Stack.back().LastSpace = State.Column;
+  } else if (Current.is(TT_CSharpGenericTypeConstraintColon)) {
+State.Stack.back().ColonPos = State.Column;
   } else if (Previous.opensScope()) {
 // If a function has a trailing call, indent all parameters from the
 // opening parenthesis. This avoids confusing indents like:
@@ -924,7 +927,13 @@ unsigned ContinuationIndenter::addTokenOnNewLine(LineState 
&State,
 unsigned ContinuationIndenter::getNewLineColumn(const LineState &State) {
   if (!State.NextToken || !State.NextToken->Previous)
 return 0;
+
   FormatToken &Current = *State.NextToken;
+
+  if (State.Stack.back().IsCSharpGenericTypeConstraint &&
+  Current.isNot(TT_CSharpGenericTypeConstraint))
+return State.Stack.back().ColonPos + 2;
+
   const FormatToken &Previous = *Current.Previous;
   // If we are continuing an expression, we want to use the continuation 
indent.
   unsigned ContinuationIndent =
@@ -1106,9 +1115,11 @@ unsigned 
ContinuationIndenter::moveStateToNextToken(LineState &State,
   assert(State.Stack.size());
   const FormatToken &Current = *State.NextToken;
 
+  if (Current.is(TT_CSharpGenericTypeConstraint))
+State.Stack.back().IsCSharpGenericTypeConstraint = true;
   if (Current.isOneOf(tok::comma, TT_BinaryOperator))
 State.Stack.back().NoLineBreakInOperand = false;
-  if (Current.is(TT_InheritanceColon))
+  if (Current.isOneOf(TT_InheritanceColon, 
TT_CSharpGenericTypeConstraintColon))
 State.Stack.back().AvoidBinPacking = true;
   if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator)) {
 if (State.Stack.back().FirstLessLess == 0)
@@ -1329,6 +1340,11 @@ void 
ContinuationIndenter::moveStatePastScopeOpener(LineState &State,
   if (!Current.opensScope())
 return;
 
+  // Don't allow '<' or '(' in C# generic type constraints to start new scopes.
+  if (Current.isOneOf(tok::less, tok::l_paren) &&
+  State.Stack.back().IsCSharpGenericTypeConstraint)
+return;
+
   if (Current.MatchingParen && Current.BlockKind == BK_Block) {
 moveStateToNewBlock(State);
 return;
@@ -1393,6 +1409,7 @@ void 
ContinuationIndenter::moveStatePastScopeOpener(LineState &State,
 (State.Line->Type == LT_ObjCDecl && ObjCBinPackProtocolList);
 
 AvoidBinPacking =
+(State.Stack.back().IsCSharpGenericTypeConstraint) ||
 (Style.Language == FormatStyle::LK_JavaScript && EndsInComma) ||
 (State.Line->MustBeDeclaration && !BinPackDeclaration) ||
 (!State.Line->MustBeDeclaration && !Style.BinPackArguments) ||

diff  --git a/clang/lib/Format/ContinuationIndenter.h 
b/clang/lib/Format/ContinuationIndenter.h
index 11df619e0f40..ab116d5468e8 100644
--- a/clang/lib/Format/ContinuationIndenter.h
+++ b/clang/lib/Format/ContinuationIndenter.h
@@ -208,7 +208,8 @@ struct ParenState {
 LastOperatorWrapped(true), ContainsLineBreak(false),
 ContainsUnwrappedBuilder(false), AlignColons(true),
 ObjCSelectorNameFound(false), HasMultipleNestedBlocks(false),
-NestedBlo

[clang-tools-extra] 7693a9b - [clang-tidy] Fix RenamerClangTidy handling qualified TypeLocs

2020-03-23 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-03-23T13:45:34Z
New Revision: 7693a9b9314083eafd9b5b1e19b02aac06962eb2

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

LOG: [clang-tidy] Fix RenamerClangTidy handling qualified TypeLocs

Summary:
Previously if a type was accessed with a qualifier, RenamerClangTidy wouldn't 
rename the TypeLoc, this patch addresses this shortfall by trying to find the 
Unqualified TypeLoc first. Also fixed a broken test case that was dependent on 
this broken behaviour.

Example:
```
struct a{};

void foo(const a&);
void foo(a&);
void foo(a);
void foo(a&&);
void foo(const a);
```
exec `-checks=readability-identifier-naming --config="{CheckOptions: [{key: 
readability-identifier-naming.StructCase, value: CamelCase}]}" -fix`
Current Behaviour:
```
struct A{};

void foo(const a&);
void foo(A&);
void foo(A);
void foo(A&&);
void foo(const a);
```
Proposed new behaviour:
```
struct A{};

void foo(const A&);
void foo(A&);
void foo(A);
void foo(A&&);
void foo(const A);
```

Reviewers: aaron.ballman, gribozavr2, alexfh

Reviewed By: aaron.ballman

Subscribers: xazax.hun, cfe-commits

Tags: #clang

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

Added: 


Modified: 
clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp

clang-tools-extra/test/clang-tidy/checkers/bugprone-reserved-identifier-invert.cpp
clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp 
b/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
index 21d304e1a438..3523cf5dcf16 100644
--- a/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
+++ b/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
@@ -203,14 +203,15 @@ void RenamerClangTidyCheck::check(const 
MatchFinder::MatchResult &Result) {
   }
 
   if (const auto *Loc = Result.Nodes.getNodeAs("typeLoc")) {
+UnqualTypeLoc Unqual = Loc->getUnqualifiedLoc();
 NamedDecl *Decl = nullptr;
-if (const auto &Ref = Loc->getAs())
+if (const auto &Ref = Unqual.getAs())
   Decl = Ref.getDecl();
-else if (const auto &Ref = Loc->getAs())
+else if (const auto &Ref = Unqual.getAs())
   Decl = Ref.getDecl();
-else if (const auto &Ref = Loc->getAs())
+else if (const auto &Ref = Unqual.getAs())
   Decl = Ref.getDecl();
-else if (const auto &Ref = Loc->getAs())
+else if (const auto &Ref = Unqual.getAs())
   Decl = Ref.getDecl();
 // further TypeLocs handled below
 

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone-reserved-identifier-invert.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone-reserved-identifier-invert.cpp
index f8a2662bebf1..501f6dd13dc5 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone-reserved-identifier-invert.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone-reserved-identifier-invert.cpp
@@ -57,7 +57,7 @@ template 
 inline reference_wrapper
 cref(const Up &u) noexcept {
   // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: declaration uses identifier 
'u', which is not a reserved identifier [bugprone-reserved-identifier]
-  // CHECK-FIXES: {{^}}cref(const Up &__u) noexcept {{{$}}
+  // CHECK-FIXES: {{^}}cref(const _Up &__u) noexcept {{{$}}
   return reference_wrapper(u);
 }
 

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
index 908281391064..7983bb30ca64 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
@@ -532,3 +532,16 @@ using namespace FOO_NS;
 
 using namespace FOO_NS::InlineNamespace;
 // CHECK-FIXES: {{^}}using namespace foo_ns::inline_namespace;
+
+void QualifiedTypeLocTest(THIS___Structure);
+// CHECK-FIXES: {{^}}void QualifiedTypeLocTest(this_structure);{{$}}
+void QualifiedTypeLocTest(THIS___Structure &);
+// CHECK-FIXES: {{^}}void QualifiedTypeLocTest(this_structure &);{{$}}
+void QualifiedTypeLocTest(THIS___Structure &&);
+// CHECK-FIXES: {{^}}void QualifiedTypeLocTest(this_structure &&);{{$}}
+void QualifiedTypeLocTest(const THIS___Structure);
+// CHECK-FIXES: {{^}}void QualifiedTypeLocTest(const this_structure);{{$}}
+void QualifiedTypeLocTest(const THIS___Structure &);
+// CHECK-FIXES: {{^}}void QualifiedTypeLocTest(const this_structure &);{{$}}
+void QualifiedTypeLocTest(volatile THIS___Structure &);
+// CHECK-FIXES: {{^}}void QualifiedTypeLocTest(volatile this_structure &);{{$}}



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

[PATCH] D76140: [InlineFunction] update attributes during inlining

2020-03-23 Thread Anna Thomas via Phabricator via cfe-commits
anna marked an inline comment as done.
anna added inline comments.



Comment at: llvm/lib/Transforms/Utils/InlineFunction.cpp:1172
+  if (NumInstChecked++ > MaxInstCheckedForThrow ||
+  isGuaranteedToTransferExecutionToSuccessor(&I))
+return true;

lebedev.ri wrote:
> anna wrote:
> > lebedev.ri wrote:
> > > anna wrote:
> > > > Noticed while adding couple more tests, there are 2 bugs here:
> > > > 1. the `isGuaranteedToTransferExecutionToSuccessor` check should be 
> > > > inverted
> > > > 2.  make_range should be until the return instruction - so we do not 
> > > > want `std::prev` on the returnInstruction. what's needed is: 
> > > > `make_range(RVal->getIterator(), RInst->getIterator())`
> > > > This means that from the callsite until (and excluding) the return 
> > > > instruction should be guaranteed to transfer execution to successor - 
> > > > only then we can backward propagate the attribute to that callsite.
> > > Are you aware of `llvm::isValidAssumeForContext()`?
> > > All this (including pitfalls) sound awfully close to that function.
> > as stated in a previous comment (https://reviews.llvm.org/D76140#1922292), 
> > adding `Assumes` here for simple cases seems like an overkill. It has 
> > significant IR churn and it also adds a use for something which can be 
> > easily inferred. 
> > Consider optimizations that depend on facts such as `hasOneUse` or a 
> > limited number of uses. We will now be inhibiting those optimizations. 
> While i venomously disagree with the avoidance of the usage of one versatile 
> interface
> and hope things will change once there's more progress on attributor & assume 
> bundles,
> in this case, as it can be seen even from the signature of the 
> `isValidAssumeForContext()` function,
> it implies/forces nothing about using assumes, but only performs a validity 
> checking,
> similar to the `MayContainThrowingOrExitingCall()`
> 
> https://github.com/llvm/llvm-project/blob/ca04d0c8fd269978be1c13fe1241172cdfe6a6ea/llvm/lib/Analysis/ValueTracking.cpp#L603
> 
> That being said, i haven't reviewed this code so maybe there's some 
> differences here
> that make that function unapplicable here.
> 
`isValidAssumeForContext(Inv, CxtI, DT)` does not force anything about assumes, 
but AFAICT all code which uses this function either has some sort of guard in 
the caller that the instruction is an assume. Also, the comments in the code 
state that it is for an assume. In fact, I believe if we intend to use that 
function more widely for other purposes, we should rename the function before 
using it (just a thought), and currently we should assert that `Inv` is an 
assume. It captures the intent of the function.

That being said, I checked the code in `isValidAssumeForContext` and it does 
not fit the bill here for multiple reasons. We either do:
1. `isValidAssumeForContext(RVal /* Inv */, RInst /* CxtI  */)` which fails 
when we do not have DT and just return true when RVal comes before RInst - this 
is always the case, since RVal will come before RInst.
2. `isValidAssumeForContext(RInst /* Inv*/, RVal /* CxtI*/)` and it fails at 
the `!isEphemeralValueOf(Inv /* RI */, CxtI /* RV*/)` check.  
(By fail here, I mean, it does not have the same behaviour as 
`MayContainThrowingOrExitingCall`).



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76140



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


[PATCH] D76607: [clang-query] Add replace command

2020-03-23 Thread Alexander Timin via Phabricator via cfe-commits
altimin updated this revision to Diff 252016.
altimin added a comment.

Format


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76607

Files:
  clang-tools-extra/clang-query/Query.cpp
  clang-tools-extra/clang-query/Query.h
  clang-tools-extra/clang-query/QueryParser.cpp

Index: clang-tools-extra/clang-query/QueryParser.cpp
===
--- clang-tools-extra/clang-query/QueryParser.cpp
+++ clang-tools-extra/clang-query/QueryParser.cpp
@@ -78,7 +78,8 @@
 
 if (WordCompletionPos == StringRef::npos)
   Switch.Case(CaseStr, Value);
-else if (CaseStr.size() != 0 && IsCompletion && WordCompletionPos <= CaseStr.size() &&
+else if (CaseStr.size() != 0 && IsCompletion &&
+ WordCompletionPos <= CaseStr.size() &&
  CaseStr.substr(0, WordCompletionPos) ==
  Word.substr(0, WordCompletionPos))
   P->Completions.push_back(LineEditor::Completion(
@@ -161,6 +162,7 @@
   PQK_Let,
   PQK_Match,
   PQK_Set,
+  PQK_Replace,
   PQK_Unlet,
   PQK_Quit,
   PQK_Enable,
@@ -202,7 +204,9 @@
   .Case("let", PQK_Let)
   .Case("m", PQK_Match, /*IsCompletion=*/false)
   .Case("match", PQK_Match)
-  .Case("q", PQK_Quit,  /*IsCompletion=*/false)
+  .Case("r", PQK_Replace, /*IsCompletion=*/false)
+  .Case("replace", PQK_Replace)
+  .Case("q", PQK_Quit, /*IsCompletion=*/false)
   .Case("quit", PQK_Quit)
   .Case("set", PQK_Set)
   .Case("enable", PQK_Enable)
@@ -265,6 +269,21 @@
 return Q;
   }
 
+  case PQK_Replace: {
+Diagnostics Diag;
+auto MatcherAndReplacementSource = Line.split(";");
+auto MatcherSource = MatcherAndReplacementSource.first.ltrim();
+Optional Matcher = Parser::parseMatcherExpression(
+MatcherSource, nullptr, &QS.NamedValues, &Diag);
+if (!Matcher) {
+  fprintf(stderr, "### Failed to construct matcher");
+  return makeInvalidQueryFromDiagnostics(Diag);
+}
+auto *Q =
+new ReplaceQuery(MatcherAndReplacementSource.second.trim(), *Matcher);
+return Q;
+  }
+
   case PQK_Set: {
 StringRef VarStr;
 ParsedQueryVariable Var =
Index: clang-tools-extra/clang-query/Query.h
===
--- clang-tools-extra/clang-query/Query.h
+++ clang-tools-extra/clang-query/Query.h
@@ -26,6 +26,7 @@
   QK_Help,
   QK_Let,
   QK_Match,
+  QK_Replace,
   QK_SetBool,
   QK_SetOutputKind,
   QK_EnableOutputKind,
@@ -98,6 +99,21 @@
   static bool classof(const Query *Q) { return Q->Kind == QK_Match; }
 };
 
+/// Query for "replace MATCHER REPLACEMENT"
+struct ReplaceQuery : Query {
+  ReplaceQuery(StringRef ReplacementSource,
+   const ast_matchers::dynamic::DynTypedMatcher &Matcher)
+  : Query(QK_Replace), Matcher(Matcher),
+ReplacementSource(ReplacementSource) {}
+  bool run(llvm::raw_ostream &OS, QuerySession &QS) const override;
+
+  ast_matchers::dynamic::DynTypedMatcher Matcher;
+
+  StringRef ReplacementSource;
+
+  static bool classof(const Query *Q) { return Q->Kind == QK_Replace; }
+};
+
 struct LetQuery : Query {
   LetQuery(StringRef Name, const ast_matchers::dynamic::VariantValue &Value)
   : Query(QK_Let), Name(Name), Value(Value) {}
Index: clang-tools-extra/clang-query/Query.cpp
===
--- clang-tools-extra/clang-query/Query.cpp
+++ clang-tools-extra/clang-query/Query.cpp
@@ -9,9 +9,20 @@
 #include "Query.h"
 #include "QuerySession.h"
 #include "clang/AST/ASTDumper.h"
+#include "clang/AST/ExprConcepts.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Basic/CharInfo.h"
+#include "clang/Basic/LLVM.h"
+#include "clang/Basic/LangOptions.h"
 #include "clang/Frontend/ASTUnit.h"
 #include "clang/Frontend/TextDiagnostic.h"
+#include "clang/Sema/DeclSpec.h"
+#include "clang/Tooling/Core/Diagnostic.h"
+#include "clang/Tooling/Core/Replacement.h"
+#include "clang/Tooling/DiagnosticsYaml.h"
+#include "clang/Tooling/ReplacementsYaml.h"
+#include "llvm/ADT/None.h"
+#include "llvm/Support/YAMLTraits.h"
 #include "llvm/Support/raw_ostream.h"
 
 using namespace clang::ast_matchers;
@@ -147,7 +158,8 @@
   const ASTContext &Ctx = AST->getASTContext();
   const SourceManager &SM = Ctx.getSourceManager();
   ASTDumper Dumper(OS, &Ctx.getCommentCommandTraits(), &SM,
-SM.getDiagnostics().getShowColors(), Ctx.getPrintingPolicy());
+   SM.getDiagnostics().getShowColors(),
+   Ctx.getPrintingPolicy());
   Dumper.Visit(BI->second);
   OS << "\n";
 }
@@ -162,

[PATCH] D76509: [analyzer][NFC] Move the text output type to its own file, move code to PathDiagnosticConsumer creator functions

2020-03-23 Thread Gabor Marton via Phabricator via cfe-commits
martong added inline comments.



Comment at: clang/include/clang/StaticAnalyzer/Core/Analyses.def:17
 
-ANALYSIS_STORE(RegionStore, "region", "Use region-based analyzer store", 
CreateRegionStoreManager)
+ANALYSIS_STORE(RegionStore, "region", "Use region-based analyzer store",
+   CreateRegionStoreManager)

Yay! I am a big fun of the 80 col limit! :)



Comment at: clang/include/clang/StaticAnalyzer/Core/Analyses.def:61
+
+ANALYSIS_DIAGNOSTICS(TEXT_MINIMAL, "text-minimal",
+ "Emits minimal diagnostics to stderr, stating only the "

Just out of curiosity: is there a way to know which one is the default?



Comment at: clang/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp:140
+
+  // FIXME: HTML is currently our default output type, but if the output
+  // directory isn't specified, it acts like if it was in the minimal text

Actually, now I wonder where should we document the default output type ... I 
am pretty sure it should be done somewhere where it is obvious, maybe in 
`Analyses.def`?



Comment at: clang/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp:142
+  // directory isn't specified, it acts like if it was in the minimal text
+  // output mode. This doesn't make much sense, we should have the minimal text
+  // as our default. In the case of backward compatibility concerns, this could

Man, I understand you pain now, this is really muddled, do you plan to sort 
this out in an upcoming patch?



Comment at: clang/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp:148
+  // TODO: Emit an error here.
+  if (OutputDir.empty())
+return;

Would be an `assert` better here?



Comment at: clang/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp:148
+  // TODO: Emit an error here.
+  if (OutputDir.empty())
+return;

martong wrote:
> Would be an `assert` better here?
```
 // if the output
  // directory isn't specified, it acts like if it was in the minimal text
  // output mode.
```
So, why don't we do this check **before** calling 
createTextMinimalPathDiagnosticConsumer ?




Comment at: clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp:1
+//===--- TextDiagnostics.cpp - Text Diagnostics for Paths ---*- C++ 
-*-===//
+//

Is this just a blind copy (and rename) from `AnalysisConsumer`, or should I 
take a deeper look into anything here?



Comment at: clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp:156
 #include "clang/StaticAnalyzer/Core/Analyses.def"
-}
-  }
+default:
+  llvm_unreachable("Unkown analyzer output type!");

Some build bots will not compile if you handle all cases in the swtich and you 
still have a `default`, beware.



Comment at: clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp:348
   void reportAnalyzerProgress(StringRef S);
-};
+}; // namespace
 } // end anonymous namespace

Either the `;` is redundant or this is not the end of a namespace.


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

https://reviews.llvm.org/D76509



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


[PATCH] D76054: [clang-apply-replacements] No longer deduplucates replacements from the same TU

2020-03-23 Thread Nathan James via Phabricator via cfe-commits
njames93 added inline comments.



Comment at: clang-tools-extra/test/clang-apply-replacements/identical2.cpp:3
+// RUN: grep -Ev "// *[A-Z-]+:" %S/Inputs/identical2/identical2.cpp > 
%T/Inputs/identical2/identical2.cpp
+// RUN: sed "s#\$(path)#%/T/Inputs/identical2#" 
%S/Inputs/identical2/file1.yaml > %T/Inputs/identical2/file1.yaml
+// RUN: sed "s#\$(path)#%/T/Inputs/identical2#" 
%S/Inputs/identical2/file2.yaml > %T/Inputs/identical2/file2.yaml

ymandel wrote:
> Why is this `%/T` rather than `%T`? I realize it is the same in 
> `identical.cpp`, but just want to understand what I'm reading...
It's like that in most of the checks, not sure why but wanted to keep it 
consistent.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76054



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


[PATCH] D76054: [clang-apply-replacements] No longer deduplucates replacements from the same TU

2020-03-23 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 252017.
njames93 marked 5 inline comments as done.
njames93 added a comment.

- Address reviewer comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76054

Files:
  clang-tools-extra/clang-apply-replacements/lib/Tooling/ApplyReplacements.cpp
  
clang-tools-extra/test/clang-apply-replacements/Inputs/identical-in-TU/file1.yaml
  
clang-tools-extra/test/clang-apply-replacements/Inputs/identical-in-TU/file2.yaml
  
clang-tools-extra/test/clang-apply-replacements/Inputs/identical-in-TU/identical-in-TU.cpp
  clang-tools-extra/test/clang-apply-replacements/identical-in-TU.cpp

Index: clang-tools-extra/test/clang-apply-replacements/identical-in-TU.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-apply-replacements/identical-in-TU.cpp
@@ -0,0 +1,11 @@
+// RUN: mkdir -p %T/Inputs/identical-in-TU
+
+// RUN: grep -Ev "// *[A-Z-]+:" %S/Inputs/identical-in-TU/identical-in-TU.cpp > %T/Inputs/identical-in-TU/identical-in-TU.cpp
+// RUN: sed "s#\$(path)#%/T/Inputs/identical-in-TU#" %S/Inputs/identical-in-TU/file1.yaml > %T/Inputs/identical-in-TU/file1.yaml
+// RUN: sed "s#\$(path)#%/T/Inputs/identical-in-TU#" %S/Inputs/identical-in-TU/file2.yaml > %T/Inputs/identical-in-TU/file2.yaml
+// RUN: clang-apply-replacements %T/Inputs/identical-in-TU
+// RUN: FileCheck -input-file=%T/Inputs/identical-in-TU/identical-in-TU.cpp %S/Inputs/identical-in-TU/identical-in-TU.cpp
+
+// Similar to identical test but each yaml file contains the same fix twice. 
+// This check ensures that only the duplicated replacements in a single yaml 
+// file are applied twice. Addresses PR45150.
Index: clang-tools-extra/test/clang-apply-replacements/Inputs/identical-in-TU/identical-in-TU.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-apply-replacements/Inputs/identical-in-TU/identical-in-TU.cpp
@@ -0,0 +1,2 @@
+class MyType {};
+// CHECK: class MyType00 {};
Index: clang-tools-extra/test/clang-apply-replacements/Inputs/identical-in-TU/file2.yaml
===
--- /dev/null
+++ clang-tools-extra/test/clang-apply-replacements/Inputs/identical-in-TU/file2.yaml
@@ -0,0 +1,19 @@
+---
+MainSourceFile: identical-in-TU.cpp
+Diagnostics:
+  - DiagnosticName: test-identical-insertion
+DiagnosticMessage:
+  Message: Fix
+  FilePath: $(path)/identical-in-TU.cpp
+  FileOffset: 12
+  Replacements:
+- FilePath:$(path)/identical-in-TU.cpp
+  Offset:  12
+  Length:  0
+  ReplacementText: '0'
+- FilePath:$(path)/identical-in-TU.cpp
+  Offset:  12
+  Length:  0
+  ReplacementText: '0'
+...
+
Index: clang-tools-extra/test/clang-apply-replacements/Inputs/identical-in-TU/file1.yaml
===
--- /dev/null
+++ clang-tools-extra/test/clang-apply-replacements/Inputs/identical-in-TU/file1.yaml
@@ -0,0 +1,19 @@
+---
+MainSourceFile: identical_in_TU.cpp
+Diagnostics:
+  - DiagnosticName: test-identical-insertion
+DiagnosticMessage:
+  Message: Fix
+  FilePath: $(path)/identical_in_TU.cpp
+  FileOffset: 12
+  Replacements:
+- FilePath:$(path)/identical_in_TU.cpp
+  Offset:  12
+  Length:  0
+  ReplacementText: '0'
+- FilePath:$(path)/identical_in_TU.cpp
+  Offset:  12
+  Length:  0
+  ReplacementText: '0'
+...
+
Index: clang-tools-extra/clang-apply-replacements/lib/Tooling/ApplyReplacements.cpp
===
--- clang-tools-extra/clang-apply-replacements/lib/Tooling/ApplyReplacements.cpp
+++ clang-tools-extra/clang-apply-replacements/lib/Tooling/ApplyReplacements.cpp
@@ -143,18 +143,26 @@
   llvm::DenseMap>
   GroupedReplacements;
 
-  // Deduplicate identical replacements in diagnostics.
+  // Deduplicate identical replacements in diagnostics unless they are from the
+  // same TU.
   // FIXME: Find an efficient way to deduplicate on diagnostics level.
-  llvm::DenseMap>
+  llvm::DenseMap>
   DiagReplacements;
 
-  auto AddToGroup = [&](const tooling::Replacement &R, bool FromDiag) {
+  auto AddToGroup = [&](const tooling::Replacement &R,
+const tooling::TranslationUnitDiagnostics *SourceTU) {
 // Use the file manager to deduplicate paths. FileEntries are
 // automatically canonicalized.
 if (auto Entry = SM.getFileManager().getFile(R.getFilePath())) {
-  if (FromDiag) {
+  if (SourceTU) {
 auto &Replaces = DiagReplacements[*Entry];
-if (!Replaces.insert(R).second)
+auto It = Replaces.find(R);
+if (It =

[PATCH] D76384: Move FPFeatures from BinaryOperator bitfields to Trailing storage

2020-03-23 Thread Melanie Blower via Phabricator via cfe-commits
mibintc added a comment.

In D76384#1934785 , @rjmccall wrote:

> Let's make this patch be purely a representation change.  I wouldn't expect 
> *any* test changes from that; if there are, we should understand why.  You 
> can then add the stuff about tracking whether there's a pragma in a separate 
> patch.


OK, some of the tests show ConditionalOperator in the IR matching. Since that 
operator is necessarily getting merged into BinaryOperator those tests will 
have to change. I'll see about changing the srcpos for the conditional 
assignment operator so i can undo the srcpos changes in those tests.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76384



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


[PATCH] D76605: [analyzer] Display the checker name in the text output

2020-03-23 Thread Gabor Marton via Phabricator via cfe-commits
martong added inline comments.



Comment at: clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp:98
   const PathDiagnostic *PD = *I;
+  std::string WarningMsg =
+  (ShouldDisplayCheckerName ? " [" + PD->getCheckerName() + "]" : "")

`StringRef`? `getCheckerName()` returns with `StringRef`...



Comment at: clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp:112
 reportPiece(NoteID, Piece->getLocation().asLocation(),
-Piece->getString(), Piece->getRanges(), 
Piece->getFixits());
+Piece->getString().str(), Piece->getRanges(),
+Piece->getFixits());

Why the `.str()` ?



Comment at: clang/test/Analysis/incorrect-checker-names.mm:1
+// RUN: %clang_analyze_cc1 -fblocks -verify %s -Wno-objc-root-class \
+// RUN:   -analyzer-checker=core \

This seems like a copy of an existing test file, though I don't know which. 
Wouldn't it be better to adjust the original test file?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76605



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


[PATCH] D76597: [clang-format] Reflow long C# generic type constraints correctly

2020-03-23 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG78e2a3c67846: [clang-format] Reflow long C# generic type 
constraints correctly (authored by Jonathan Coe ).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76597

Files:
  clang/lib/Format/ContinuationIndenter.cpp
  clang/lib/Format/ContinuationIndenter.h
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/FormatTestCSharp.cpp

Index: clang/unittests/Format/FormatTestCSharp.cpp
===
--- clang/unittests/Format/FormatTestCSharp.cpp
+++ clang/unittests/Format/FormatTestCSharp.cpp
@@ -687,6 +687,14 @@
   where T : IMyInterface { doThing(); }
 })",
Style);
+
+  verifyFormat(R"(//
+class ItemFactory
+where T : new(),
+  IAnInterface,
+  IAnotherInterface,
+  IAnotherInterfaceStill {})",
+   Style);
 }
 
 } // namespace format
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -3620,6 +3620,9 @@
 if (Left.isOneOf(TT_CSharpNamedArgumentColon, TT_AttributeColon) ||
 Right.isOneOf(TT_CSharpNamedArgumentColon, TT_AttributeColon))
   return false;
+// Only break after commas for generic type constraints.
+if (Line.First->is(TT_CSharpGenericTypeConstraint))
+  return Left.is(TT_CSharpGenericTypeConstraintComma);
   } else if (Style.Language == FormatStyle::LK_Java) {
 if (Left.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
  Keywords.kw_implements))
Index: clang/lib/Format/ContinuationIndenter.h
===
--- clang/lib/Format/ContinuationIndenter.h
+++ clang/lib/Format/ContinuationIndenter.h
@@ -208,7 +208,8 @@
 LastOperatorWrapped(true), ContainsLineBreak(false),
 ContainsUnwrappedBuilder(false), AlignColons(true),
 ObjCSelectorNameFound(false), HasMultipleNestedBlocks(false),
-NestedBlockInlined(false), IsInsideObjCArrayLiteral(false) {}
+NestedBlockInlined(false), IsInsideObjCArrayLiteral(false),
+IsCSharpGenericTypeConstraint(false) {}
 
   /// \brief The token opening this parenthesis level, or nullptr if this level
   /// is opened by fake parenthesis.
@@ -329,6 +330,8 @@
   /// array literal.
   bool IsInsideObjCArrayLiteral : 1;
 
+  bool IsCSharpGenericTypeConstraint : 1;
+
   bool operator<(const ParenState &Other) const {
 if (Indent != Other.Indent)
   return Indent < Other.Indent;
@@ -366,6 +369,8 @@
   return ContainsUnwrappedBuilder;
 if (NestedBlockInlined != Other.NestedBlockInlined)
   return NestedBlockInlined;
+if (IsCSharpGenericTypeConstraint != Other.IsCSharpGenericTypeConstraint)
+  return IsCSharpGenericTypeConstraint;
 return false;
   }
 };
Index: clang/lib/Format/ContinuationIndenter.cpp
===
--- clang/lib/Format/ContinuationIndenter.cpp
+++ clang/lib/Format/ContinuationIndenter.cpp
@@ -634,6 +634,7 @@
 State.Stack.back().NoLineBreak = true;
 
   if (Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign &&
+  !State.Stack.back().IsCSharpGenericTypeConstraint &&
   Previous.opensScope() && Previous.isNot(TT_ObjCMethodExpr) &&
   (Current.isNot(TT_LineComment) || Previous.BlockKind == BK_BracedInit))
 State.Stack.back().Indent = State.Column + Spaces;
@@ -715,6 +716,8 @@
   } else if (Previous.is(TT_InheritanceColon)) {
 State.Stack.back().Indent = State.Column;
 State.Stack.back().LastSpace = State.Column;
+  } else if (Current.is(TT_CSharpGenericTypeConstraintColon)) {
+State.Stack.back().ColonPos = State.Column;
   } else if (Previous.opensScope()) {
 // If a function has a trailing call, indent all parameters from the
 // opening parenthesis. This avoids confusing indents like:
@@ -924,7 +927,13 @@
 unsigned ContinuationIndenter::getNewLineColumn(const LineState &State) {
   if (!State.NextToken || !State.NextToken->Previous)
 return 0;
+
   FormatToken &Current = *State.NextToken;
+
+  if (State.Stack.back().IsCSharpGenericTypeConstraint &&
+  Current.isNot(TT_CSharpGenericTypeConstraint))
+return State.Stack.back().ColonPos + 2;
+
   const FormatToken &Previous = *Current.Previous;
   // If we are continuing an expression, we want to use the continuation indent.
   unsigned ContinuationIndent =
@@ -1106,9 +1115,11 @@
   assert(State.Stack.size());
   const FormatToken &Current = *State.NextToken;
 
+  if (Current.is(TT_CSharpGenericTypeConstraint))
+State.Stack.back().IsCSharpGenericTypeConstraint = true;
   if (Current.isOneOf(tok::comma, TT_BinaryOperator))
 State.Stack.back().NoLineBreakInOperand

[PATCH] D76549: [clang-tidy] Fix RenamerClangTidy handling qualified TypeLocs

2020-03-23 Thread Nathan James via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG7693a9b93140: [clang-tidy] Fix RenamerClangTidy handling 
qualified TypeLocs (authored by njames93).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76549

Files:
  clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
  
clang-tools-extra/test/clang-tidy/checkers/bugprone-reserved-identifier-invert.cpp
  clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp


Index: 
clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
@@ -532,3 +532,16 @@
 
 using namespace FOO_NS::InlineNamespace;
 // CHECK-FIXES: {{^}}using namespace foo_ns::inline_namespace;
+
+void QualifiedTypeLocTest(THIS___Structure);
+// CHECK-FIXES: {{^}}void QualifiedTypeLocTest(this_structure);{{$}}
+void QualifiedTypeLocTest(THIS___Structure &);
+// CHECK-FIXES: {{^}}void QualifiedTypeLocTest(this_structure &);{{$}}
+void QualifiedTypeLocTest(THIS___Structure &&);
+// CHECK-FIXES: {{^}}void QualifiedTypeLocTest(this_structure &&);{{$}}
+void QualifiedTypeLocTest(const THIS___Structure);
+// CHECK-FIXES: {{^}}void QualifiedTypeLocTest(const this_structure);{{$}}
+void QualifiedTypeLocTest(const THIS___Structure &);
+// CHECK-FIXES: {{^}}void QualifiedTypeLocTest(const this_structure &);{{$}}
+void QualifiedTypeLocTest(volatile THIS___Structure &);
+// CHECK-FIXES: {{^}}void QualifiedTypeLocTest(volatile this_structure &);{{$}}
Index: 
clang-tools-extra/test/clang-tidy/checkers/bugprone-reserved-identifier-invert.cpp
===
--- 
clang-tools-extra/test/clang-tidy/checkers/bugprone-reserved-identifier-invert.cpp
+++ 
clang-tools-extra/test/clang-tidy/checkers/bugprone-reserved-identifier-invert.cpp
@@ -57,7 +57,7 @@
 inline reference_wrapper
 cref(const Up &u) noexcept {
   // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: declaration uses identifier 
'u', which is not a reserved identifier [bugprone-reserved-identifier]
-  // CHECK-FIXES: {{^}}cref(const Up &__u) noexcept {{{$}}
+  // CHECK-FIXES: {{^}}cref(const _Up &__u) noexcept {{{$}}
   return reference_wrapper(u);
 }
 
Index: clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
===
--- clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
+++ clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
@@ -203,14 +203,15 @@
   }
 
   if (const auto *Loc = Result.Nodes.getNodeAs("typeLoc")) {
+UnqualTypeLoc Unqual = Loc->getUnqualifiedLoc();
 NamedDecl *Decl = nullptr;
-if (const auto &Ref = Loc->getAs())
+if (const auto &Ref = Unqual.getAs())
   Decl = Ref.getDecl();
-else if (const auto &Ref = Loc->getAs())
+else if (const auto &Ref = Unqual.getAs())
   Decl = Ref.getDecl();
-else if (const auto &Ref = Loc->getAs())
+else if (const auto &Ref = Unqual.getAs())
   Decl = Ref.getDecl();
-else if (const auto &Ref = Loc->getAs())
+else if (const auto &Ref = Unqual.getAs())
   Decl = Ref.getDecl();
 // further TypeLocs handled below
 


Index: clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
@@ -532,3 +532,16 @@
 
 using namespace FOO_NS::InlineNamespace;
 // CHECK-FIXES: {{^}}using namespace foo_ns::inline_namespace;
+
+void QualifiedTypeLocTest(THIS___Structure);
+// CHECK-FIXES: {{^}}void QualifiedTypeLocTest(this_structure);{{$}}
+void QualifiedTypeLocTest(THIS___Structure &);
+// CHECK-FIXES: {{^}}void QualifiedTypeLocTest(this_structure &);{{$}}
+void QualifiedTypeLocTest(THIS___Structure &&);
+// CHECK-FIXES: {{^}}void QualifiedTypeLocTest(this_structure &&);{{$}}
+void QualifiedTypeLocTest(const THIS___Structure);
+// CHECK-FIXES: {{^}}void QualifiedTypeLocTest(const this_structure);{{$}}
+void QualifiedTypeLocTest(const THIS___Structure &);
+// CHECK-FIXES: {{^}}void QualifiedTypeLocTest(const this_structure &);{{$}}
+void QualifiedTypeLocTest(volatile THIS___Structure &);
+// CHECK-FIXES: {{^}}void QualifiedTypeLocTest(volatile this_structure &);{{$}}
Index: clang-tools-extra/test/clang-tidy/checkers/bugprone-reserved-identifier-invert.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/bugprone-reserved-identifier-invert.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone-reserved-identifier-invert.cpp
@@ -57,7 +5

[clang] 60bad94 - [Analyzer] Iterator Modeling - Model `std::advance()`, `std::prev()` and `std::next()`

2020-03-23 Thread Adam Balogh via cfe-commits

Author: Adam Balogh
Date: 2020-03-23T15:29:55+01:00
New Revision: 60bad941a1c1b745f570da8251f2ba9ee8b7d06e

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

LOG: [Analyzer] Iterator Modeling - Model `std::advance()`, `std::prev()` and 
`std::next()`

Whenever the analyzer budget runs out just at the point where
`std::advance()`, `std::prev()` or `std::next()` is invoked the function
are not inlined. This results in strange behavior such as
`std::prev(v.end())` equals `v.end()`. To prevent this model these
functions if they were not inlined. It may also happend that although
`std::advance()` is inlined but a function it calls inside (e.g.
`__advance()` in some implementations) is not. This case is also handled
in this patch.

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

Added: 


Modified: 
clang/lib/StaticAnalyzer/Checkers/IteratorModeling.cpp
clang/test/Analysis/Inputs/system-header-simulator-cxx.h
clang/test/Analysis/iterator-modelling.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/IteratorModeling.cpp 
b/clang/lib/StaticAnalyzer/Checkers/IteratorModeling.cpp
index 955a40b0d4b7..9a813b0a1a45 100644
--- a/clang/lib/StaticAnalyzer/Checkers/IteratorModeling.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/IteratorModeling.cpp
@@ -86,6 +86,15 @@ class IteratorModeling
 : public Checker,
  check::Bind, check::LiveSymbols, check::DeadSymbols> {
 
+  using AdvanceFn = void (IteratorModeling::*)(CheckerContext &, const Expr *,
+   SVal, SVal, SVal) const;
+
+  void handleOverloadedOperator(CheckerContext &C, const CallEvent &Call,
+OverloadedOperatorKind Op) const;
+  void handleAdvanceLikeFunction(CheckerContext &C, const CallEvent &Call,
+ const Expr *OrigExpr,
+ const AdvanceFn *Handler) const;
+
   void handleComparison(CheckerContext &C, const Expr *CE, SVal RetVal,
 const SVal &LVal, const SVal &RVal,
 OverloadedOperatorKind Op) const;
@@ -99,13 +108,39 @@ class IteratorModeling
   void handleRandomIncrOrDecr(CheckerContext &C, const Expr *CE,
   OverloadedOperatorKind Op, const SVal &RetVal,
   const SVal &LHS, const SVal &RHS) const;
+  void handleAdvance(CheckerContext &C, const Expr *CE, SVal RetVal, SVal Iter,
+ SVal Amount) const;
+  void handlePrev(CheckerContext &C, const Expr *CE, SVal RetVal, SVal Iter,
+  SVal Amount) const;
+  void handleNext(CheckerContext &C, const Expr *CE, SVal RetVal, SVal Iter,
+  SVal Amount) const;
   void assignToContainer(CheckerContext &C, const Expr *CE, const SVal &RetVal,
  const MemRegion *Cont) const;
+  bool noChangeInAdvance(CheckerContext &C, SVal Iter, const Expr *CE) const;
   void printState(raw_ostream &Out, ProgramStateRef State, const char *NL,
   const char *Sep) const override;
 
+  // std::advance, std::prev & std::next
+  CallDescriptionMap AdvanceLikeFunctions = {
+  // template
+  // void advance(InputIt& it, Distance n);
+  {{{"std", "advance"}, 2}, &IteratorModeling::handleAdvance},
+
+  // template
+  // BidirIt prev(
+  //   BidirIt it,
+  //   typename std::iterator_traits::
diff erence_type n = 1);
+  {{{"std", "prev"}, 2}, &IteratorModeling::handlePrev},
+
+  // template
+  // ForwardIt next(
+  //   ForwardIt it,
+  //   typename std::iterator_traits::
diff erence_type n = 1);
+  {{{"std", "next"}, 2}, &IteratorModeling::handleNext},
+  };
+
 public:
-  IteratorModeling() {}
+  IteratorModeling() = default;
 
   void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
   void checkBind(SVal Loc, SVal Val, const Stmt *S, CheckerContext &C) const;
@@ -123,6 +158,7 @@ ProgramStateRef relateSymbols(ProgramStateRef State, 
SymbolRef Sym1,
   SymbolRef Sym2, bool Equal);
 bool isBoundThroughLazyCompoundVal(const Environment &Env,
const MemRegion *Reg);
+const ExplodedNode *findCallEnter(const ExplodedNode *Node, const Expr *Call);
 
 } // namespace
 
@@ -135,101 +171,52 @@ void IteratorModeling::checkPostCall(const CallEvent 
&Call,
 
   if (Func->isOverloadedOperator()) {
 const auto Op = Func->getOverloadedOperator();
-if (isSimpleComparisonOperator(Op)) {
-  const auto *OrigExpr = Call.getOriginExpr();
-  if (!OrigExpr)
-return;
-
-  if (const auto *InstCall = dyn_cast(&Call)) {
-handleComparison(C, OrigExpr, Call.getReturnValue(),
- InstCall->

[clang] 5e1a026 - [clang-format] Do not indent C# array initialisers as continuations

2020-03-23 Thread Jonathan Coe via cfe-commits

Author: Jonathan Coe
Date: 2020-03-23T14:33:10Z
New Revision: 5e1a026c2d81e83e2b88cc6b6f27fbefbfe0de16

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

LOG: [clang-format] Do not indent C# array initialisers as continuations

Summary: Flag '= {' as a braced init list when parsing C# code.

Reviewers: krasimir

Reviewed By: krasimir

Subscribers: cfe-commits, MyDeveloperDay

Tags: #clang-format, #clang

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

Added: 


Modified: 
clang/lib/Format/UnwrappedLineParser.cpp
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index e2a6389cb26d..d8202bd61458 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -1460,6 +1460,11 @@ void UnwrappedLineParser::parseStructuralElement() {
 
   nextToken();
   if (FormatTok->Tok.is(tok::l_brace)) {
+// Block kind should probably be set to BK_BracedInit for any language.
+// C# needs this change to ensure that array initialisers and object
+// initialisers are indented the same way.
+if (Style.isCSharp())
+  FormatTok->BlockKind = BK_BracedInit;
 nextToken();
 parseBracedList();
   } else if (Style.Language == FormatStyle::LK_Proto &&
@@ -1652,7 +1657,7 @@ bool UnwrappedLineParser::tryToParseBracedList() {
 bool UnwrappedLineParser::parseBracedList(bool ContinueOnSemicolons,
   tok::TokenKind ClosingBraceKind) {
   bool HasError = false;
-
+  
   // FIXME: Once we have an expression parser in the UnwrappedLineParser,
   // replace this by using parseAssigmentExpression() inside.
   do {

diff  --git a/clang/unittests/Format/FormatTestCSharp.cpp 
b/clang/unittests/Format/FormatTestCSharp.cpp
index a0f60ce799d2..0b770b4dfd3c 100644
--- a/clang/unittests/Format/FormatTestCSharp.cpp
+++ b/clang/unittests/Format/FormatTestCSharp.cpp
@@ -562,6 +562,17 @@ var myDict = new Dictionary {
Style);
 }
 
+TEST_F(FormatTestCSharp, CSharpArrayInitializers) {
+  FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
+  
+  verifyFormat(R"(//
+private MySet[] setPoints = {
+  new Point(),
+  new Point(),
+};)",
+   Style);
+}
+
 TEST_F(FormatTestCSharp, CSharpNamedArguments) {
   FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
 



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


[PATCH] D76323: [AST] Fix handling of long double and bool in __builtin_bit_cast

2020-03-23 Thread Erik Pilkington via Phabricator via cfe-commits
erik.pilkington updated this revision to Diff 252023.
erik.pilkington marked 5 inline comments as done.
erik.pilkington added a comment.

Add tests for `bit_cast((char)1)`;


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

https://reviews.llvm.org/D76323

Files:
  clang/include/clang/Basic/DiagnosticASTKinds.td
  clang/lib/AST/ExprConstant.cpp
  clang/test/SemaCXX/constexpr-builtin-bit-cast.cpp

Index: clang/test/SemaCXX/constexpr-builtin-bit-cast.cpp
===
--- clang/test/SemaCXX/constexpr-builtin-bit-cast.cpp
+++ clang/test/SemaCXX/constexpr-builtin-bit-cast.cpp
@@ -23,6 +23,10 @@
 template 
 constexpr To bit_cast(const From &from) {
   static_assert(sizeof(To) == sizeof(From));
+  // expected-note@+9 {{cannot be represented in type 'bool'}}
+#ifdef __x86_64
+  // expected-note@+7 {{or 'std::byte'; '__int128' is invalid}}
+#endif
 #ifdef __CHAR_UNSIGNED__
   // expected-note@+4 2 {{indeterminate value can only initialize an object of type 'unsigned char', 'char', or 'std::byte'; 'signed char' is invalid}}
 #else
@@ -397,3 +401,65 @@
 };
 constexpr IdentityInUnion identity3a = {42};
 constexpr unsigned char identity3b = __builtin_bit_cast(unsigned char, identity3a.n);
+
+namespace test_bool {
+
+constexpr bool test_bad_bool = bit_cast('A'); // expected-error {{must be initialized by a constant expression}} expected-note{{in call}}
+
+static_assert(round_trip(true), "");
+static_assert(round_trip(false), "");
+static_assert(round_trip(false), "");
+
+static_assert(round_trip((char)0), "");
+static_assert(round_trip((char)1), "");
+}
+
+namespace test_long_double {
+#ifdef __x86_64
+constexpr __int128_t test_cast_to_int128 = bit_cast<__int128_t>((long double)0); // expected-error{{must be initialized by a constant expression}} expected-note{{in call}}
+
+constexpr long double ld = 3.1425926539;
+
+struct bytes {
+  unsigned char d[16];
+};
+
+static_assert(round_trip(ld), "");
+
+static_assert(round_trip(10.0L));
+
+constexpr bool f(bool read_uninit) {
+  bytes b = bit_cast(ld);
+  unsigned char ld_bytes[10] = {
+0x0,  0x48, 0x9f, 0x49, 0xf0,
+0x3c, 0x20, 0xc9, 0x0,  0x40,
+  };
+
+  for (int i = 0; i != 10; ++i)
+if (ld_bytes[i] != b.d[i])
+  return false;
+
+  if (read_uninit && b.d[10]) // expected-note{{read of uninitialized object is not allowed in a constant expression}}
+return false;
+
+  return true;
+}
+
+static_assert(f(/*read_uninit=*/false), "");
+static_assert(f(/*read_uninit=*/true), ""); // expected-error{{static_assert expression is not an integral constant expression}} expected-note{{in call to 'f(true)'}}
+
+constexpr bytes ld539 = {
+  0x0, 0x0,  0x0,  0x0,
+  0x0, 0x0,  0xc0, 0x86,
+  0x8, 0x40, 0x0,  0x0,
+  0x0, 0x0,  0x0,  0x0,
+};
+
+constexpr long double fivehundredandthirtynine = 539.0;
+
+static_assert(bit_cast(ld539) == fivehundredandthirtynine, "");
+
+#else
+static_assert(round_trip<__int128_t>(34.0L));
+#endif
+}
Index: clang/lib/AST/ExprConstant.cpp
===
--- clang/lib/AST/ExprConstant.cpp
+++ clang/lib/AST/ExprConstant.cpp
@@ -6361,7 +6361,14 @@
 
   bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
 APSInt AsInt(Val.bitcastToAPInt());
-return visitInt(AsInt, Ty, Offset);
+const llvm::fltSemantics &Semantics = Info.Ctx.getFloatTypeSemantics(Ty);
+unsigned NumBits = APFloat::semanticsSizeInBits(Semantics);
+assert(NumBits % 8 == 0);
+CharUnits Width = CharUnits::fromQuantity(NumBits / 8);
+SmallVector Bytes(Width.getQuantity());
+llvm::StoreIntToMemory(AsInt, &*Bytes.begin(), Width.getQuantity());
+Buffer.writeObject(Offset, Bytes);
+return true;
   }
 
 public:
@@ -6395,6 +6402,13 @@
 return None;
   }
 
+  llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) {
+Info.FFDiag(BCE->getBeginLoc(),
+diag::note_constexpr_bit_cast_unrepresentable_value)
+<< Ty << Val.toString(/*Radix=*/10);
+return None;
+  }
+
   Optional visit(const BuiltinType *T, CharUnits Offset,
   const EnumType *EnumSugar = nullptr) {
 if (T->isNullPtrType()) {
@@ -6405,6 +6419,20 @@
 }
 
 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
+
+// Work around floating point types that contain unused padding bytes. This
+// is really just `long double` on x86, which is the only fundamental type
+// with padding bytes.
+if (T->isRealFloatingType()) {
+  const llvm::fltSemantics &Semantics =
+  Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
+  unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
+  assert(NumBits % 8 == 0);
+  CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
+  if (NumBytes != SizeOf)
+SizeOf = NumBytes;
+}
+
 SmallVector Bytes;
 if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
   // If this is std::byte 

[PATCH] D76520: [CUDA][HIP] Add -Xarch_device and -Xarch_host options

2020-03-23 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added a comment.

In D76520#1934341 , @tra wrote:

> Does it handle options with values? E.g. if I want to pass 
> `-mframe-pointer=none` ? I vaguely recall the current -Xarch_* implementation 
> had some limitations. 
>  It may be worth adding a test for that.


-Xarch_ works with driver options having value, e.g. `-fcf-protection=branch`. 
I added a test for that.

`-mframe-pointer=none` is a cc1 option. That's why it cannot be passed by 
-Xarch_. If it is made a driver option it can be passed.


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

https://reviews.llvm.org/D76520



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


[PATCH] D76520: [CUDA][HIP] Add -Xarch_device and -Xarch_host options

2020-03-23 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl updated this revision to Diff 252024.
yaxunl added a comment.

Add a test for passing options with value


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

https://reviews.llvm.org/D76520

Files:
  clang/include/clang/Driver/Options.td
  clang/include/clang/Driver/ToolChain.h
  clang/lib/Driver/Compilation.cpp
  clang/lib/Driver/ToolChain.cpp
  clang/lib/Driver/ToolChains/Cuda.cpp
  clang/lib/Driver/ToolChains/HIP.cpp
  clang/test/Driver/hip-options.hip

Index: clang/test/Driver/hip-options.hip
===
--- clang/test/Driver/hip-options.hip
+++ clang/test/Driver/hip-options.hip
@@ -13,3 +13,16 @@
 // RUN:   -mllvm -amdgpu-early-inline-all=true  %s 2>&1 | \
 // RUN:   FileCheck -check-prefix=MLLVM %s
 // MLLVM-NOT: "-mllvm"{{.*}}"-amdgpu-early-inline-all=true"{{.*}}"-mllvm"{{.*}}"-amdgpu-early-inline-all=true"
+
+// RUN: %clang -### -Xarch_device -g -nogpulib --cuda-gpu-arch=gfx900 \
+// RUN:   -Xarch_device -fcf-protection=branch \
+// RUN:   --cuda-gpu-arch=gfx906  %s 2>&1 | FileCheck -check-prefix=DEV %s
+// DEV: clang{{.*}} "-fcuda-is-device" {{.*}} "-debug-info-kind={{.*}}" {{.*}} "-fcf-protection=branch"
+// DEV: clang{{.*}} "-fcuda-is-device" {{.*}} "-debug-info-kind={{.*}}" {{.*}} "-fcf-protection=branch"
+// DEV-NOT: clang{{.*}} {{.*}} "-debug-info-kind={{.*}}"
+
+// RUN: %clang -### -Xarch_host -g -nogpulib --cuda-gpu-arch=gfx900 \
+// RUN:   --cuda-gpu-arch=gfx906  %s 2>&1 | FileCheck -check-prefix=HOST %s
+// HOST-NOT: clang{{.*}} "-fcuda-is-device" {{.*}} "-debug-info-kind={{.*}}"
+// HOST-NOT: clang{{.*}} "-fcuda-is-device" {{.*}} "-debug-info-kind={{.*}}"
+// HOST: clang{{.*}} "-debug-info-kind={{.*}}"
Index: clang/lib/Driver/ToolChains/HIP.cpp
===
--- clang/lib/Driver/ToolChains/HIP.cpp
+++ clang/lib/Driver/ToolChains/HIP.cpp
@@ -378,12 +378,6 @@
   const OptTable &Opts = getDriver().getOpts();
 
   for (Arg *A : Args) {
-if (A->getOption().matches(options::OPT_Xarch__)) {
-  // Skip this argument unless the architecture matches BoundArch.
-  if (BoundArch.empty() || A->getValue(0) != BoundArch)
-continue;
-  TranslateXarchArgs(Args, A, DAL);
-}
 DAL->append(A);
   }
 
Index: clang/lib/Driver/ToolChains/Cuda.cpp
===
--- clang/lib/Driver/ToolChains/Cuda.cpp
+++ clang/lib/Driver/ToolChains/Cuda.cpp
@@ -800,12 +800,6 @@
   }
 
   for (Arg *A : Args) {
-if (A->getOption().matches(options::OPT_Xarch__)) {
-  // Skip this argument unless the architecture matches BoundArch
-  if (BoundArch.empty() || A->getValue(0) != BoundArch)
-continue;
-  TranslateXarchArgs(Args, A, DAL);
-}
 DAL->append(A);
   }
 
Index: clang/lib/Driver/ToolChain.cpp
===
--- clang/lib/Driver/ToolChain.cpp
+++ clang/lib/Driver/ToolChain.cpp
@@ -1103,11 +1103,17 @@
   return nullptr;
 }
 
-void ToolChain::TranslateXarchArgs(const llvm::opt::DerivedArgList &Args,
-   llvm::opt::Arg *&A,
-   llvm::opt::DerivedArgList *DAL) const {
+void ToolChain::TranslateXarchArgs(
+const llvm::opt::DerivedArgList &Args, llvm::opt::Arg *&A,
+llvm::opt::DerivedArgList *DAL,
+SmallVectorImpl *AllocatedArgs) const {
   const OptTable &Opts = getDriver().getOpts();
-  unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
+  unsigned ValuePos = 1;
+  if (A->getOption().matches(options::OPT_Xarch_device) ||
+  A->getOption().matches(options::OPT_Xarch_host))
+ValuePos = 0;
+
+  unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(ValuePos));
   unsigned Prev = Index;
   std::unique_ptr XarchArg(Opts.ParseOneArg(Args, Index));
 
@@ -1130,5 +1136,49 @@
   }
   XarchArg->setBaseArg(A);
   A = XarchArg.release();
-  DAL->AddSynthesizedArg(A);
+  if (!AllocatedArgs)
+DAL->AddSynthesizedArg(A);
+  else
+AllocatedArgs->push_back(A);
+}
+
+llvm::opt::DerivedArgList *ToolChain::TranslateXarchArgs(
+const llvm::opt::DerivedArgList &Args, StringRef BoundArch,
+Action::OffloadKind OFK,
+SmallVectorImpl *AllocatedArgs) const {
+  DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
+  bool Modified = false;
+
+  bool IsGPU = OFK == Action::OFK_Cuda || OFK == Action::OFK_HIP;
+  for (Arg *A : Args) {
+bool NeedTrans = false;
+bool Skip = false;
+if (A->getOption().matches(options::OPT_Xarch_device)) {
+  NeedTrans = IsGPU;
+  Skip = !IsGPU;
+} else if (A->getOption().matches(options::OPT_Xarch_host)) {
+  NeedTrans = !IsGPU;
+  Skip = IsGPU;
+} else if (A->getOption().matches(options::OPT_Xarch__) && IsGPU) {
+  // Do not translate -Xarch_ options for non CUDA/HIP toolchain since
+  // they may need special translation.
+  // Skip this argument unless the arch

[PATCH] D31343: Add an attribute plugin example

2020-03-23 Thread Jasmin Fazlic via Phabricator via cfe-commits
Jasmin added a comment.

Hello John!

I was encouraged by Erich after a talk I had with him and Aaron on IRC to 
contact you about an use case for this plugin.

I wanted to use user-specified/unknown attributes to annotate code and was told 
that they are not propagated through
the AST and therefore it is not possible at the moment to use them for that 
purpose. Aaron's and Erich's idea was to
allow kind of no-op attributes in the plugin so that the compiler would not 
issue a warning about the unknown attribute.
This would be helpful for the user being able to define a list of attributes 
the user knows and expects, so that a compilation
would not be spammed unnecessarily and misspelled attributes would still stand 
out.

Being able to get the cursor or displayName of the attribute would essentially 
be enough to use it in tooling.

We can use __attribute__((annotate(smth))) at the time being to achieve the 
same goal, but it is much more writing to do
and also vendor specific. Being able to do the same with attributes would give 
them a real purpose, other than having
to be accepted and not causing an error. Also they have to be supported by the 
language and we don't have to use
macros to annotate the code.

To summarize it would be nice to have:

- user supplied unknown attributes to suppress a warning
- unknown attributes propagated in the AST

I hope I summarized this correctly and could get through the gist of this idea.

Looking forward to hearing from you.

Best regards, Jasmin


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

https://reviews.llvm.org/D31343



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


[PATCH] D76610: [ARM,CDE] Implement predicated Q-register CDE intrinsics

2020-03-23 Thread Mikhail Maltsev via Phabricator via cfe-commits
miyuki created this revision.
miyuki added reviewers: simon_tatham, MarkMurrayARM, ostannard, dmgreen.
Herald added subscribers: cfe-commits, danielkiss, hiraditya, kristof.beyls.
Herald added a project: clang.

This patch implements the following CDE intrinsics:

  T __arm_vcx1q_m(int coproc, T inactive, uint32_t imm, mve_pred_t p);
  T __arm_vcx2q_m(int coproc, T inactive, U n, uint32_t imm, mve_pred_t p);
  T __arm_vcx3q_m(int coproc, T inactive, U n, V m, uint32_t imm, mve_pred_t p);
  
  T __arm_vcx1qa_m(int coproc, T acc, uint32_t imm, mve_pred_t p);
  T __arm_vcx2qa_m(int coproc, T acc, U n, uint32_t imm, mve_pred_t p);
  T __arm_vcx3qa_m(int coproc, T acc, U n, V m, uint32_t imm, mve_pred_t p);

The intrinsics are not part of the released ACLE spec, but internally at
Arm we have reached consensus to add them to the next ACLE release.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D76610

Files:
  clang/include/clang/Basic/arm_cde.td
  clang/test/CodeGen/arm-cde-vec.c
  llvm/include/llvm/IR/IntrinsicsARM.td
  llvm/lib/Target/ARM/ARMInstrCDE.td
  llvm/test/CodeGen/Thumb2/cde-vec.ll

Index: llvm/test/CodeGen/Thumb2/cde-vec.ll
===
--- llvm/test/CodeGen/Thumb2/cde-vec.ll
+++ llvm/test/CodeGen/Thumb2/cde-vec.ll
@@ -1,5 +1,5 @@
 ; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
-; RUN: llc -mtriple=thumbv8.1m.main -mattr=+cdecp0 -mattr=+cdecp1 -mattr=+mve -verify-machineinstrs -o - %s | FileCheck %s
+; RUN: llc -mtriple=thumbv8.1m.main -mattr=+cdecp0 -mattr=+cdecp1 -mattr=+mve.fp -verify-machineinstrs -o - %s | FileCheck %s
 
 declare <16 x i8> @llvm.arm.cde.vcx1q(i32 immarg, i32 immarg)
 declare <16 x i8> @llvm.arm.cde.vcx1qa(i32 immarg, <16 x i8>, i32 immarg)
@@ -112,3 +112,103 @@
   %2 = call <16 x i8> @llvm.arm.cde.vcx3qa(i32 1, <16 x i8> %acc, <16 x i8> %0, <16 x i8> %1, i32 13)
   ret <16 x i8> %2
 }
+
+declare <16 x i1> @llvm.arm.mve.pred.i2v.v16i1(i32)
+declare <8 x i1> @llvm.arm.mve.pred.i2v.v8i1(i32)
+declare <4 x i1> @llvm.arm.mve.pred.i2v.v4i1(i32)
+declare <8 x i16> @llvm.arm.cde.vcx1q.predicated.v8i16.v8i1(i32 immarg, <8 x i16>, i32 immarg, <8 x i1>)
+declare <16 x i8> @llvm.arm.cde.vcx1qa.predicated.v16i8.v16i1(i32 immarg, <16 x i8>, i32 immarg, <16 x i1>)
+declare <4 x i32> @llvm.arm.cde.vcx2q.predicated.v4i32.v4i1(i32 immarg, <4 x i32>, <16 x i8>, i32 immarg, <4 x i1>)
+declare <4 x float> @llvm.arm.cde.vcx2qa.predicated.v4f32.v4i1(i32 immarg, <4 x float>, <16 x i8>, i32 immarg, <4 x i1>)
+declare <2 x i64> @llvm.arm.cde.vcx3q.predicated.v2i64.v4i1(i32 immarg, <2 x i64>, <16 x i8>, <16 x i8>, i32 immarg, <4 x i1>)
+declare <4 x float> @llvm.arm.cde.vcx3qa.predicated.v4f32.v4i1(i32 immarg, <4 x float>, <16 x i8>, <16 x i8>, i32 immarg, <4 x i1>)
+
+define arm_aapcs_vfpcc <8 x i16> @test_vcx1q_m(<8 x i16> %inactive, i16 zeroext %p) {
+; CHECK-LABEL: test_vcx1q_m:
+; CHECK:   @ %bb.0: @ %entry
+; CHECK-NEXT:vmsr p0, r0
+; CHECK-NEXT:vpst
+; CHECK-NEXT:vcx1t p0, q0, #
+; CHECK-NEXT:bx lr
+entry:
+  %0 = zext i16 %p to i32
+  %1 = call <8 x i1> @llvm.arm.mve.pred.i2v.v8i1(i32 %0)
+  %2 = call <8 x i16> @llvm.arm.cde.vcx1q.predicated.v8i16.v8i1(i32 0, <8 x i16> %inactive, i32 , <8 x i1> %1)
+  ret <8 x i16> %2
+}
+
+define arm_aapcs_vfpcc <16 x i8> @test_vcx1qa_m(<16 x i8> %acc, i16 zeroext %p) {
+; CHECK-LABEL: test_vcx1qa_m:
+; CHECK:   @ %bb.0: @ %entry
+; CHECK-NEXT:vmsr p0, r0
+; CHECK-NEXT:vpst
+; CHECK-NEXT:vcx1at p1, q0, #1112
+; CHECK-NEXT:bx lr
+entry:
+  %0 = zext i16 %p to i32
+  %1 = call <16 x i1> @llvm.arm.mve.pred.i2v.v16i1(i32 %0)
+  %2 = call <16 x i8> @llvm.arm.cde.vcx1qa.predicated.v16i8.v16i1(i32 1, <16 x i8> %acc, i32 1112, <16 x i1> %1)
+  ret <16 x i8> %2
+}
+
+define arm_aapcs_vfpcc <4 x i32> @test_vcx2q_m(<4 x i32> %inactive, <4 x float> %n, i16 zeroext %p) {
+; CHECK-LABEL: test_vcx2q_m:
+; CHECK:   @ %bb.0: @ %entry
+; CHECK-NEXT:vmsr p0, r0
+; CHECK-NEXT:vpst
+; CHECK-NEXT:vcx2t p0, q0, q1, #111
+; CHECK-NEXT:bx lr
+entry:
+  %0 = bitcast <4 x float> %n to <16 x i8>
+  %1 = zext i16 %p to i32
+  %2 = call <4 x i1> @llvm.arm.mve.pred.i2v.v4i1(i32 %1)
+  %3 = call <4 x i32> @llvm.arm.cde.vcx2q.predicated.v4i32.v4i1(i32 0, <4 x i32> %inactive, <16 x i8> %0, i32 111, <4 x i1> %2)
+  ret <4 x i32> %3
+}
+
+define arm_aapcs_vfpcc <4 x float> @test_vcx2qa_m(<4 x float> %acc, <8 x half> %n, i16 zeroext %p) {
+; CHECK-LABEL: test_vcx2qa_m:
+; CHECK:   @ %bb.0: @ %entry
+; CHECK-NEXT:vmsr p0, r0
+; CHECK-NEXT:vpst
+; CHECK-NEXT:vcx2at p0, q0, q1, #112
+; CHECK-NEXT:bx lr
+entry:
+  %0 = bitcast <8 x half> %n to <16 x i8>
+  %1 = zext i16 %p to i32
+  %2 = call <4 x i1> @llvm.arm.mve.pred.i2v.v4i1(i32 %1)
+  %3 = call <4 x float> @llvm.arm.cde.vcx2qa.predicated.v4f32.v4i1(i32 0, <4 x float> %acc, <16 x i8> %0, i32 112, <4 x i1> %2)
+  ret <4 x float> %3
+}
+
+define arm_aapcs_vfpcc

[PATCH] D76323: [AST] Fix handling of long double and bool in __builtin_bit_cast

2020-03-23 Thread Erik Pilkington via Phabricator via cfe-commits
erik.pilkington added inline comments.



Comment at: clang/lib/AST/ExprConstant.cpp:6365
+const llvm::fltSemantics &Semantics = Info.Ctx.getFloatTypeSemantics(Ty);
+unsigned NumBits = APFloat::semanticsSizeInBits(Semantics);
+assert(NumBits % 8 == 0);

ldionne wrote:
> `semanticsSizeInBits` is the number of bits actually used in the type?
Yeah



Comment at: clang/test/SemaCXX/constexpr-builtin-bit-cast.cpp:226-250
 typedef decltype(nullptr) nullptr_t;
 
 #ifdef __CHAR_UNSIGNED__
 // expected-note@+5 {{indeterminate value can only initialize an object of 
type 'unsigned char', 'char', or 'std::byte'; 'unsigned long' is invalid}}
 #else
 // expected-note@+3 {{indeterminate value can only initialize an object of 
type 'unsigned char' or 'std::byte'; 'unsigned long' is invalid}}
 #endif

>>! In D76323#1933791, @jfb wrote:
> Maybe you should test `nullptr` as well, given that it's all padding?

There are some existing `nullptr` padding tests here ^^^, which seem to cover 
this.



Comment at: clang/test/SemaCXX/constexpr-builtin-bit-cast.cpp:407
+
+constexpr bool test_bad_bool = bit_cast('A'); // expected-error {{must 
be initialized by a constant expression}} expected-note{{in call}}
+

jfb wrote:
> Sanity-check: `0` and `1` work? IIRC we had a discussion about whether 
> `false` was `0` and `true` was `1`, and we concluded that `false` was indeed 
> `0` but `true` wasn't specified to be `1`.
Yeah, they work, I added a test in the update. I don't think it really matters 
that `true` could technically be `2` in the standard here, since the 
representation on our implementation is always `1`.


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

https://reviews.llvm.org/D76323



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


[PATCH] D75760: [clang-format] Do not indent C# array initialisers as continuations

2020-03-23 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir accepted this revision.
krasimir added a comment.
This revision is now accepted and ready to land.

This is OK with the comment in the code. Thank you!


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

https://reviews.llvm.org/D75760



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


[PATCH] D75760: [clang-format] Do not indent C# array initialisers as continuations

2020-03-23 Thread Jonathan B Coe via Phabricator via cfe-commits
jbcoe updated this revision to Diff 252028.
jbcoe added a comment.

Rebase and update patch.


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

https://reviews.llvm.org/D75760

Files:
  clang/lib/Format/UnwrappedLineParser.cpp
  clang/unittests/Format/FormatTestCSharp.cpp


Index: clang/unittests/Format/FormatTestCSharp.cpp
===
--- clang/unittests/Format/FormatTestCSharp.cpp
+++ clang/unittests/Format/FormatTestCSharp.cpp
@@ -562,6 +562,17 @@
Style);
 }
 
+TEST_F(FormatTestCSharp, CSharpArrayInitializers) {
+  FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
+  
+  verifyFormat(R"(//
+private MySet[] setPoints = {
+  new Point(),
+  new Point(),
+};)",
+   Style);
+}
+
 TEST_F(FormatTestCSharp, CSharpNamedArguments) {
   FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
 
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -1460,6 +1460,11 @@
 
   nextToken();
   if (FormatTok->Tok.is(tok::l_brace)) {
+// Block kind should probably be set to BK_BracedInit for any language.
+// C# needs this change to ensure that array initialisers and object
+// initialisers are indented the same way.
+if (Style.isCSharp())
+  FormatTok->BlockKind = BK_BracedInit;
 nextToken();
 parseBracedList();
   } else if (Style.Language == FormatStyle::LK_Proto &&
@@ -1652,7 +1657,7 @@
 bool UnwrappedLineParser::parseBracedList(bool ContinueOnSemicolons,
   tok::TokenKind ClosingBraceKind) {
   bool HasError = false;
-
+  
   // FIXME: Once we have an expression parser in the UnwrappedLineParser,
   // replace this by using parseAssigmentExpression() inside.
   do {


Index: clang/unittests/Format/FormatTestCSharp.cpp
===
--- clang/unittests/Format/FormatTestCSharp.cpp
+++ clang/unittests/Format/FormatTestCSharp.cpp
@@ -562,6 +562,17 @@
Style);
 }
 
+TEST_F(FormatTestCSharp, CSharpArrayInitializers) {
+  FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
+  
+  verifyFormat(R"(//
+private MySet[] setPoints = {
+  new Point(),
+  new Point(),
+};)",
+   Style);
+}
+
 TEST_F(FormatTestCSharp, CSharpNamedArguments) {
   FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
 
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -1460,6 +1460,11 @@
 
   nextToken();
   if (FormatTok->Tok.is(tok::l_brace)) {
+// Block kind should probably be set to BK_BracedInit for any language.
+// C# needs this change to ensure that array initialisers and object
+// initialisers are indented the same way.
+if (Style.isCSharp())
+  FormatTok->BlockKind = BK_BracedInit;
 nextToken();
 parseBracedList();
   } else if (Style.Language == FormatStyle::LK_Proto &&
@@ -1652,7 +1657,7 @@
 bool UnwrappedLineParser::parseBracedList(bool ContinueOnSemicolons,
   tok::TokenKind ClosingBraceKind) {
   bool HasError = false;
-
+  
   // FIXME: Once we have an expression parser in the UnwrappedLineParser,
   // replace this by using parseAssigmentExpression() inside.
   do {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D76572: Replace `T(x)` with `reinterpret_cast(x)` everywhere it means reinterpret_cast. No functional change

2020-03-23 Thread Arthur O'Dwyer via Phabricator via cfe-commits
Quuxplusone added a comment.

In D76572#1936191 , @grandinj wrote:

> Libreoffice has a similar clang-tidy-style cast-checker [for C-style casts] 
> here:
>
> https://cgit.freedesktop.org/libreoffice/core/tree/compilerplugins/clang/cstylecast.cxx
>  
> https://cgit.freedesktop.org/libreoffice/core/tree/compilerplugins/clang/test/cstylecast.cxx


Nice. Does LibreOffice have anything (either in clang-tidy or in a paper 
guideline) against `T(x)`-style casts? E.g.

  struct PB {};
  struct D : private PB {};
  using FloatRef = float&;
  using IntPtr = int*;
  using PBPtr = PB*;
  int i = 42;
  const int *cpi = &i;
  D *pd = nullptr;
  float& f = FloatRef(i);  // reinterpret_cast
  int *pi = IntPtr(cpi);  // const_cast
  PB *pb = PBPtr(pd);  // cast to private base


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76572



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


[PATCH] D76605: [analyzer] Display the checker name in the text output

2020-03-23 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus marked 3 inline comments as done.
Szelethus added inline comments.



Comment at: clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp:98
   const PathDiagnostic *PD = *I;
+  std::string WarningMsg =
+  (ShouldDisplayCheckerName ? " [" + PD->getCheckerName() + "]" : "")

martong wrote:
> `StringRef`? `getCheckerName()` returns with `StringRef`...
Mind that we're constructing a string here from a bunch of smaller ones, we 
need an owning container. With that said, I could use a string stream instead.



Comment at: clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp:112
 reportPiece(NoteID, Piece->getLocation().asLocation(),
-Piece->getString(), Piece->getRanges(), 
Piece->getFixits());
+Piece->getString().str(), Piece->getRanges(),
+Piece->getFixits());

martong wrote:
> Why the `.str()` ?
`StringRef` no longer converts to `std::string` implicitly.



Comment at: clang/test/Analysis/incorrect-checker-names.mm:1
+// RUN: %clang_analyze_cc1 -fblocks -verify %s -Wno-objc-root-class \
+// RUN:   -analyzer-checker=core \

martong wrote:
> This seems like a copy of an existing test file, though I don't know which. 
> Wouldn't it be better to adjust the original test file?
Good observation, these test cases are indeed copied from other files. The 
justification behind it however is to highlight that these are the checkers 
that need fixing. Adding `FIXME`s to other thousand-line test files don't grab 
the attention enough :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76605



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


[PATCH] D75760: [clang-format] Do not indent C# array initialisers as continuations

2020-03-23 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG5e1a026c2d81: [clang-format] Do not indent C# array 
initialisers as continuations (authored by Jonathan Coe 
).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D75760

Files:
  clang/lib/Format/UnwrappedLineParser.cpp
  clang/unittests/Format/FormatTestCSharp.cpp


Index: clang/unittests/Format/FormatTestCSharp.cpp
===
--- clang/unittests/Format/FormatTestCSharp.cpp
+++ clang/unittests/Format/FormatTestCSharp.cpp
@@ -562,6 +562,17 @@
Style);
 }
 
+TEST_F(FormatTestCSharp, CSharpArrayInitializers) {
+  FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
+  
+  verifyFormat(R"(//
+private MySet[] setPoints = {
+  new Point(),
+  new Point(),
+};)",
+   Style);
+}
+
 TEST_F(FormatTestCSharp, CSharpNamedArguments) {
   FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
 
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -1460,6 +1460,11 @@
 
   nextToken();
   if (FormatTok->Tok.is(tok::l_brace)) {
+// Block kind should probably be set to BK_BracedInit for any language.
+// C# needs this change to ensure that array initialisers and object
+// initialisers are indented the same way.
+if (Style.isCSharp())
+  FormatTok->BlockKind = BK_BracedInit;
 nextToken();
 parseBracedList();
   } else if (Style.Language == FormatStyle::LK_Proto &&
@@ -1652,7 +1657,7 @@
 bool UnwrappedLineParser::parseBracedList(bool ContinueOnSemicolons,
   tok::TokenKind ClosingBraceKind) {
   bool HasError = false;
-
+  
   // FIXME: Once we have an expression parser in the UnwrappedLineParser,
   // replace this by using parseAssigmentExpression() inside.
   do {


Index: clang/unittests/Format/FormatTestCSharp.cpp
===
--- clang/unittests/Format/FormatTestCSharp.cpp
+++ clang/unittests/Format/FormatTestCSharp.cpp
@@ -562,6 +562,17 @@
Style);
 }
 
+TEST_F(FormatTestCSharp, CSharpArrayInitializers) {
+  FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
+  
+  verifyFormat(R"(//
+private MySet[] setPoints = {
+  new Point(),
+  new Point(),
+};)",
+   Style);
+}
+
 TEST_F(FormatTestCSharp, CSharpNamedArguments) {
   FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
 
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -1460,6 +1460,11 @@
 
   nextToken();
   if (FormatTok->Tok.is(tok::l_brace)) {
+// Block kind should probably be set to BK_BracedInit for any language.
+// C# needs this change to ensure that array initialisers and object
+// initialisers are indented the same way.
+if (Style.isCSharp())
+  FormatTok->BlockKind = BK_BracedInit;
 nextToken();
 parseBracedList();
   } else if (Style.Language == FormatStyle::LK_Proto &&
@@ -1652,7 +1657,7 @@
 bool UnwrappedLineParser::parseBracedList(bool ContinueOnSemicolons,
   tok::TokenKind ClosingBraceKind) {
   bool HasError = false;
-
+  
   // FIXME: Once we have an expression parser in the UnwrappedLineParser,
   // replace this by using parseAssigmentExpression() inside.
   do {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D76572: Replace `T(x)` with `reinterpret_cast(x)` everywhere it means reinterpret_cast. No functional change

2020-03-23 Thread Arthur O'Dwyer via Phabricator via cfe-commits
Quuxplusone updated this revision to Diff 252031.
Quuxplusone added a comment.

@jhenderson: Updated! clang-format's suggested linebreaks look horrendous to 
me, but if this makes that buildbot happy, okay... I guess the moral of the 
story is "deeply nested expressions that also use lots of reinterpret_casts, 
should be avoided," and I can't argue with that. ;)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76572

Files:
  clang/lib/CodeGen/CGCall.h
  llvm/include/llvm/IR/SymbolTableListTraits.h
  llvm/include/llvm/Object/Binary.h
  llvm/lib/CodeGen/AsmPrinter/OcamlGCPrinter.cpp
  llvm/lib/Object/COFFObjectFile.cpp
  llvm/lib/Object/ELFObjectFile.cpp
  llvm/lib/Object/XCOFFObjectFile.cpp
  llvm/lib/Target/Hexagon/HexagonCommonGEP.cpp
  llvm/lib/Transforms/Instrumentation/DataFlowSanitizer.cpp
  llvm/tools/llvm-readobj/ELFDumper.cpp

Index: llvm/tools/llvm-readobj/ELFDumper.cpp
===
--- llvm/tools/llvm-readobj/ELFDumper.cpp
+++ llvm/tools/llvm-readobj/ELFDumper.cpp
@@ -443,7 +443,9 @@
   const ELFFile *Obj = ObjF->getELFFile();
   unsigned SecNdx = Sec - &cantFail(Obj->sections()).front();
 
-  if (uintptr_t(Obj->base() + Sec->sh_offset) % sizeof(uint16_t) != 0)
+  if (reinterpret_cast(Obj->base() + Sec->sh_offset) %
+  sizeof(uint16_t) !=
+  0)
 return createError("the SHT_GNU_versym section with index " +
Twine(SecNdx) + " is misaligned");
 
@@ -522,7 +524,7 @@
  Twine(SecNdx) + ": version definition " + Twine(I) +
  " goes past the end of the section");
 
-if (uintptr_t(VerdefBuf) % sizeof(uint32_t) != 0)
+if (reinterpret_cast(VerdefBuf) % sizeof(uint32_t) != 0)
   return createError(
   "invalid SHT_GNU_verdef section with index " + Twine(SecNdx) +
   ": found a misaligned version definition entry at offset 0x" +
@@ -545,7 +547,7 @@
 
 const uint8_t *VerdauxBuf = VerdefBuf + D->vd_aux;
 for (unsigned J = 0; J < D->vd_cnt; ++J) {
-  if (uintptr_t(VerdauxBuf) % sizeof(uint32_t) != 0)
+  if (reinterpret_cast(VerdauxBuf) % sizeof(uint32_t) != 0)
 return createError("invalid SHT_GNU_verdef section with index " +
Twine(SecNdx) +
": found a misaligned auxiliary entry at offset 0x" +
@@ -597,7 +599,7 @@
  Twine(SecNdx) + ": version dependency " + Twine(I) +
  " goes past the end of the section");
 
-if (uintptr_t(VerneedBuf) % sizeof(uint32_t) != 0)
+if (reinterpret_cast(VerneedBuf) % sizeof(uint32_t) != 0)
   return createError(
   "invalid SHT_GNU_verneed section with index " + Twine(SecNdx) +
   ": found a misaligned version dependency entry at offset 0x" +
@@ -624,7 +626,7 @@
 
 const uint8_t *VernauxBuf = VerneedBuf + Verneed->vn_aux;
 for (unsigned J = 0; J < Verneed->vn_cnt; ++J) {
-  if (uintptr_t(VernauxBuf) % sizeof(uint32_t) != 0)
+  if (reinterpret_cast(VernauxBuf) % sizeof(uint32_t) != 0)
 return createError("invalid SHT_GNU_verneed section with index " +
Twine(SecNdx) +
": found a misaligned auxiliary entry at offset 0x" +
Index: llvm/lib/Transforms/Instrumentation/DataFlowSanitizer.cpp
===
--- llvm/lib/Transforms/Instrumentation/DataFlowSanitizer.cpp
+++ llvm/lib/Transforms/Instrumentation/DataFlowSanitizer.cpp
@@ -619,14 +619,15 @@
 ArgTLS = nullptr;
 GetArgTLSTy = FunctionType::get(PointerType::getUnqual(ArgTLSTy), false);
 GetArgTLS = ConstantExpr::getIntToPtr(
-ConstantInt::get(IntptrTy, uintptr_t(GetArgTLSPtr)),
+ConstantInt::get(IntptrTy, reinterpret_cast(GetArgTLSPtr)),
 PointerType::getUnqual(GetArgTLSTy));
   }
   if (GetRetvalTLSPtr) {
 RetvalTLS = nullptr;
 GetRetvalTLSTy = FunctionType::get(PointerType::getUnqual(ShadowTy), false);
 GetRetvalTLS = ConstantExpr::getIntToPtr(
-ConstantInt::get(IntptrTy, uintptr_t(GetRetvalTLSPtr)),
+ConstantInt::get(IntptrTy,
+ reinterpret_cast(GetRetvalTLSPtr)),
 PointerType::getUnqual(GetRetvalTLSTy));
   }
 
Index: llvm/lib/Target/Hexagon/HexagonCommonGEP.cpp
===
--- llvm/lib/Target/Hexagon/HexagonCommonGEP.cpp
+++ llvm/lib/Target/Hexagon/HexagonCommonGEP.cpp
@@ -482,10 +482,11 @@
   // determining equality. The only purpose of the ordering is to eliminate
   // duplication due to the commutativity of equality/non-equality.
 static NodePair node_pair(GepNode *N1, GepNode *N2) {
-uintptr_t P1 = uintptr_t(N1), P2 = uintptr_t(N2);
-if (P1 <= P2)
-  return std::make_pair(N1, N2);
-return std::make_pair(N2, N1);
+  uintptr_t P1

[PATCH] D76361: [Analyzer] Iterator Modeling - Model `std::advance()`, `std::prev()` and `std::next()`

2020-03-23 Thread Balogh, Ádám via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
baloghadamsoftware marked 4 inline comments as done.
Closed by commit rG60bad941a1c1: [Analyzer] Iterator Modeling - Model 
`std::advance()`, `std::prev()` and `std… (authored by baloghadamsoftware).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76361

Files:
  clang/lib/StaticAnalyzer/Checkers/IteratorModeling.cpp
  clang/test/Analysis/Inputs/system-header-simulator-cxx.h
  clang/test/Analysis/iterator-modelling.cpp

Index: clang/test/Analysis/iterator-modelling.cpp
===
--- clang/test/Analysis/iterator-modelling.cpp
+++ clang/test/Analysis/iterator-modelling.cpp
@@ -2,6 +2,12 @@
 
 // RUN: %clang_analyze_cc1 -std=c++11 -analyzer-checker=core,cplusplus,debug.DebugIteratorModeling,debug.ExprInspection -analyzer-config aggressive-binary-operation-simplification=true -analyzer-config c++-container-inlining=true -DINLINE=1 %s -verify
 
+// RUN: %clang_analyze_cc1 -std=c++11 -analyzer-checker=core,cplusplus,debug.DebugIteratorModeling,debug.ExprInspection -analyzer-config aggressive-binary-operation-simplification=true -analyzer-config c++-container-inlining=true -DINLINE=1 -DSTD_ADVANCE_INLINE_LEVEL=0 %s -verify
+
+// RUN: %clang_analyze_cc1 -std=c++11 -analyzer-checker=core,cplusplus,debug.DebugIteratorModeling,debug.ExprInspection -analyzer-config aggressive-binary-operation-simplification=true -analyzer-config c++-container-inlining=true -DINLINE=1 -DSTD_ADVANCE_INLINE_LEVEL=1 %s -verify
+
+// RUN: %clang_analyze_cc1 -std=c++11 -analyzer-checker=core,cplusplus,debug.DebugIteratorModeling,debug.ExprInspection -analyzer-config aggressive-binary-operation-simplification=true -analyzer-config c++-container-inlining=true -DINLINE=1 -DSTD_ADVANCE_INLINE_LEVEL=2 %s -verify
+
 // RUN: %clang_analyze_cc1 -std=c++11 -analyzer-checker=core,cplusplus,alpha.cplusplus.IteratorModeling,debug.ExprInspection -analyzer-config aggressive-binary-operation-simplification=true %s 2>&1 | FileCheck %s
 
 #include "Inputs/system-header-simulator-cxx.h"
@@ -233,6 +239,68 @@
   clang_analyzer_express(clang_analyzer_iterator_position(i2)); //expected-warning{{$v.end() - 1}}
 }
 
+/// std::advance(), std::prev(), std::next()
+
+void std_advance_minus(const std::vector &v) {
+  auto i = v.end();
+
+  clang_analyzer_denote(clang_analyzer_container_end(v), "$v.end()");
+
+  std::advance(i, -1);
+
+  clang_analyzer_express(clang_analyzer_iterator_position(i)); //expected-warning{{$v.end() - 1}}
+}
+
+void std_advance_plus(const std::vector &v) {
+  auto i = v.begin();
+
+  clang_analyzer_denote(clang_analyzer_container_begin(v), "$v.begin()");
+
+  std::advance(i, 1);
+
+  clang_analyzer_express(clang_analyzer_iterator_position(i)); //expected-warning{{$v.begin() + 1}}
+}
+
+void std_prev(const std::vector &v) {
+  auto i = v.end();
+
+  clang_analyzer_denote(clang_analyzer_container_end(v), "$v.end()");
+
+  auto j = std::prev(i);
+
+  clang_analyzer_express(clang_analyzer_iterator_position(j)); //expected-warning{{$v.end() - 1}}
+}
+
+void std_prev2(const std::vector &v) {
+  auto i = v.end();
+
+  clang_analyzer_denote(clang_analyzer_container_end(v), "$v.end()");
+
+  auto j = std::prev(i, 2);
+
+  clang_analyzer_express(clang_analyzer_iterator_position(j)); //expected-warning{{$v.end() - 2}}
+}
+
+void std_next(const std::vector &v) {
+  auto i = v.begin();
+
+  clang_analyzer_denote(clang_analyzer_container_begin(v), "$v.begin()");
+
+  auto j = std::next(i);
+
+  clang_analyzer_express(clang_analyzer_iterator_position(j)); //expected-warning{{$v.begin() + 1}}
+}
+
+void std_next2(const std::vector &v) {
+  auto i = v.begin();
+
+  clang_analyzer_denote(clang_analyzer_container_begin(v), "$v.begin()");
+
+  auto j = std::next(i, 2);
+
+  clang_analyzer_express(clang_analyzer_iterator_position(j)); //expected-warning{{$v.begin() + 2}}
+}
+
 
 ///
 /// C O N T A I N E R   A S S I G N M E N T S
Index: clang/test/Analysis/Inputs/system-header-simulator-cxx.h
===
--- clang/test/Analysis/Inputs/system-header-simulator-cxx.h
+++ clang/test/Analysis/Inputs/system-header-simulator-cxx.h
@@ -757,31 +757,66 @@
 }
 
 template 
-void __advance (BidirectionalIterator& it, Distance n,
-std::bidirectional_iterator_tag) {
+void __advance(BidirectionalIterator& it, Distance n,
+   std::bidirectional_iterator_tag)
+#if !defined(STD_ADVANCE_INLINE_LEVEL) || STD_ADVANCE_INLINE_LEVEL > 2
+{
   if (n >= 0) while(n-- > 0) ++it; else while (n++<0) --it;
 }
+#else
+;
+#endif
 
 template 
-void __advance (RandomAccessIterator& it, Distance n,
-std::random_access_iterator_tag) {
+void __advance(RandomAccessIterator& it, Distance n,
+   std::

[PATCH] D76612: [Matrix] Add draft specification for matrix support in Clang.

2020-03-23 Thread Florian Hahn via Phabricator via cfe-commits
fhahn created this revision.
fhahn added reviewers: rsmith, anemet, Bigcheese, dexonsmith.
Herald added a subscriber: tschuett.
Herald added a project: clang.

This patch documents the planned matrix support in Clang, based on the
draft specification discussed on cfe-dev in the 'Matrix Support in
Clang' thread.

Latest draft spec sent to cfe-dev: 
http://lists.llvm.org/pipermail/cfe-dev/2020-February/064742.html
Discussion thread January: 
http://lists.llvm.org/pipermail/cfe-dev/2020-January/064206.html
Discussion thread March: 
http://lists.llvm.org/pipermail/cfe-dev/2020-March/064834.html


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D76612

Files:
  clang/docs/LanguageExtensions.rst
  clang/docs/MatrixSupport.rst

Index: clang/docs/MatrixSupport.rst
===
--- /dev/null
+++ clang/docs/MatrixSupport.rst
@@ -0,0 +1,301 @@
+==
+Matrix Support
+==
+
+.. contents::
+   :local:
+
+.. _matrixsupport:
+
+Clang provides a language extension that allows users to express high-level
+matrix math on the C/C++ level. The draft specification can be found :ref:`below `.
+
+Note that the implementation is currently in progress.
+
+.. _matrixsupport-draftspec:
+
+Draft Specification
+===
+
+Matrix Type Attribute
+-
+
+The *attribute-token* ``matrix_type`` is used to declare a matrix type. It shall
+appear at most once in each *attribute-list*. The attribute shall only appertain
+to a *typedef-name* of a typedef of a non-volatile type that is a *signed 
+integer type*, an *unsigned integer type*, or a *floating-point type*. An
+*attribute-argument-clause* must be present and it shall have the form:
+
+``(constant-expression, constant-expression)``
+
+Both *constant-expressions* shall be a positive non-zero integral constant
+expressions. The maximum of the product of the constants is implementation
+defined. If that implementation defined limit is exceeded, the program is
+ill-formed.
+
+An *attribute* of the form ``matrix_type(R, C)`` forms a matrix type with an
+element type of the cv-qualified type the attribute appertains to and *R* rows
+and *C* columns.
+
+If a declaration of a *typedef-name* has a ``matrix_type`` attribute, then all
+declaration of that *typedef-name* shall have a matrix_type attribute with the
+same element type, number of rows, and number of columns.
+
+Matrix Type
+---
+
+A matrix type has an underlying *element type*, a constant number of rows, and
+a constant number of columns. Matrix types with the same element type, rows,
+and columns are the same type. A value of a matrix type contains ``rows *
+columns`` values of the *element type* laid out in column-major order without
+padding in a way compatible with an array of at least that many elements of the
+underlying *element type*.
+
+A matrix type is a *scalar type* with the same alignment as its underlying
+element type, but objects of matrix type are not usable in constant
+expressions.
+
+TODO: Allow reinterpret_cast from pointer to element type. Make aliasing work.
+
+TODO: Does it make sense to allow M::element_type, M::rows, and M::columns
+where M is a matrix type? We don’t support this anywhere else, but it’s
+convenient. The alternative is using template deduction to extract this
+information.
+
+Future Work: Initialization syntax.
+
+Future Work: Conversions between matrix types with const qualified and
+unqualified element types.
+
+Standard Conversions
+
+
+The standard conversions are extended as follows.
+
+For integral promotions, floating-point promotion, integral conversions,
+floating-point conversions, and floating-integral conversions: apply the rules
+to the underlying type of the matrix type. The resulting type is a matrix type
+with that underlying element type. The resulting value is as follows:
+
+* If the original value was of matrix type, each element is converted element
+  by element.
+* If the original value was not of matrix type, each element takes the value of
+  the original value.
+
+Arithmetic Conversions
+--
+
+The usual arithmetic conversions are extended as follows.
+
+Insert at the start:
+
+* If either operand is of matrix type, apply the usual arithmetic conversions
+  using its underlying element type. The resulting type is a matrix type with
+  that underlying element type.
+
+Matrix Type Element Access Operator
+---
+
+An expression of the form ``postfix-expression [expression][expression]`` where
+the ``postfix-expression`` is of matrix type is a matrix element access
+expression. ``expression`` shall not be a comma expression, and shall be a
+prvalue of unscoped enumeration or integral type. Given the expression
+``E1[E2][E3]`` the result is an lvalue of the same type as the underlying
+element type of the matrix that refers to the value at E2 row and E3 column in
+the ma

[PATCH] D73541: [Clang] Added method getTokenLocations to StringLiteral

2020-03-23 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

Ping??


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D73541



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


[PATCH] D76509: [analyzer][NFC] Move the text output type to its own file, move code to PathDiagnosticConsumer creator functions

2020-03-23 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus marked 15 inline comments as done.
Szelethus added a comment.

Thanks, @martong!




Comment at: clang/include/clang/StaticAnalyzer/Core/Analyses.def:61
+
+ANALYSIS_DIAGNOSTICS(TEXT_MINIMAL, "text-minimal",
+ "Emits minimal diagnostics to stderr, stating only the "

martong wrote:
> Just out of curiosity: is there a way to know which one is the default?
Not from this file, unfortunately. You need to go to `AnalyzerOptions.h`. It 
would be great if we were able to list the possible options as well as the 
default value (similarly to `-analyzer-config`s), but I don't have plant to do 
it myself anytime soon.



Comment at: clang/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp:140
+
+  // FIXME: HTML is currently our default output type, but if the output
+  // directory isn't specified, it acts like if it was in the minimal text

martong wrote:
> Actually, now I wonder where should we document the default output type ... I 
> am pretty sure it should be done somewhere where it is obvious, maybe in 
> `Analyses.def`?
`AnalyzerOptions.h`.



Comment at: clang/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp:142
+  // directory isn't specified, it acts like if it was in the minimal text
+  // output mode. This doesn't make much sense, we should have the minimal text
+  // as our default. In the case of backward compatibility concerns, this could

martong wrote:
> Man, I understand you pain now, this is really muddled, do you plan to sort 
> this out in an upcoming patch?
Allow me to indulge you with the relieving fix found in D76510 :)



Comment at: clang/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp:148
+  // TODO: Emit an error here.
+  if (OutputDir.empty())
+return;

martong wrote:
> martong wrote:
> > Would be an `assert` better here?
> ```
>  // if the output
>   // directory isn't specified, it acts like if it was in the minimal text
>   // output mode.
> ```
> So, why don't we do this check **before** calling 
> createTextMinimalPathDiagnosticConsumer ?
> 
  if (OutputDir.empty())
return;

  createTextMinimalPathDiagnosticConsumer(AnalyzerOpts, C, OutputDir, PP, CTU);
  C.push_back(new HTMLDiagnostics(AnalyzerOpts, OutputDir, PP, true));

Otherwise this would be a functional //and// breaking change. Mind that in this 
patch, HTML is still our default output type. If I were to move the text 
diagnostics below this line, we would no longer emit any diagnostics to stderr. 
I actually had the same idea, got ~670 breaking test :^)

  if (OutputDir.empty()) {
createTextMinimalPathDiagnosticConsumer(AnalyzerOpts, C, OutputDir, PP, 
CTU);
return;
  }

  C.push_back(new HTMLDiagnostics(AnalyzerOpts, OutputDir, PP, true));

With this code, we would no longer emit to stderr, only to HTML, should an 
output directory be specified.



Comment at: clang/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp:148
+  // TODO: Emit an error here.
+  if (OutputDir.empty())
+return;

Szelethus wrote:
> martong wrote:
> > martong wrote:
> > > Would be an `assert` better here?
> > ```
> >  // if the output
> >   // directory isn't specified, it acts like if it was in the minimal text
> >   // output mode.
> > ```
> > So, why don't we do this check **before** calling 
> > createTextMinimalPathDiagnosticConsumer ?
> > 
>   if (OutputDir.empty())
> return;
> 
>   createTextMinimalPathDiagnosticConsumer(AnalyzerOpts, C, OutputDir, PP, 
> CTU);
>   C.push_back(new HTMLDiagnostics(AnalyzerOpts, OutputDir, PP, true));
> 
> Otherwise this would be a functional //and// breaking change. Mind that in 
> this patch, HTML is still our default output type. If I were to move the text 
> diagnostics below this line, we would no longer emit any diagnostics to 
> stderr. I actually had the same idea, got ~670 breaking test :^)
> 
>   if (OutputDir.empty()) {
> createTextMinimalPathDiagnosticConsumer(AnalyzerOpts, C, OutputDir, PP, 
> CTU);
> return;
>   }
> 
>   C.push_back(new HTMLDiagnostics(AnalyzerOpts, OutputDir, PP, true));
> 
> With this code, we would no longer emit to stderr, only to HTML, should an 
> output directory be specified.
> Would be an assert better here?

No, the point of the patch is to handle user errors (such as setting the output 
type to html but forgetting to supply the output location) in these factory 
functions. An assert would've been appropriate if I left 
`AnalysisConsumer::DigestAnalyzerOptions` untouched, as previously, that is 
where we checked such inconsistencies.



Comment at: clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp:1
+//===--- TextDiagnostics.cpp - Text Diagnostics for Paths ---*- C++ 
-*-===//
+//

martong wrote:
> Is this just a blind copy (and rename) from `AnalysisConsumer`, or should I 
> take a deeper look into anything here?
Well, almost:

* Moved the i

[PATCH] D76355: [Syntax] Build mapping from AST to syntax tree nodes

2020-03-23 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr2 added inline comments.



Comment at: clang/include/clang/Tooling/Syntax/Tree.h:129
 
+  void SetRole(NodeRole NR);
+

`setRole()` (in new code).



Comment at: clang/lib/Tooling/Syntax/BuildTree.cpp:975
+  const syntax::Token *TemplateKW,
+  syntax::SimpleDeclaration *InnerDeclaration) {
 assert(!ExternKW || ExternKW->kind() == tok::kw_extern);

hlopko wrote:
> gribozavr2 wrote:
> > Add a `Decl *From` parameter and pass it through to `Builder.foldNode()` 
> > below?
> Done, but to get rid of all nullptr parents in BuildTree.cpp we'd have to 
> implement support for Types in the AST mapping. Let's not do that in this 
> patch.
For consistency with, for example, `foldTemplateDeclaration`, I think `Decl 
*From` should be the last parameter.



Comment at: clang/lib/Tooling/Syntax/BuildTree.cpp:264
 
+  /// getRange() finds the syntax tokens corresponding to the \p SourceRange.
+  llvm::ArrayRef getRange(SourceRange Range) const {

Don't repeat the function name in comments.

`/// Finds the syntax tokens that correspond to the provided \c SourceRange.`



Comment at: clang/lib/Tooling/Syntax/BuildTree.cpp:270
+
   /// getRange() finds the syntax tokens corresponding to the passed source
   /// locations.

Ditto.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76355



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


[PATCH] D76572: Replace `T(x)` with `reinterpret_cast(x)` everywhere it means reinterpret_cast. No functional change

2020-03-23 Thread Noel Grandin via Phabricator via cfe-commits
grandinj added a comment.

In D76572#1936861 , @Quuxplusone wrote:

> Nice. Does LibreOffice have anything (either in clang-tidy or in a paper 
> guideline) against `T(x)`-style casts? E.g.


No, we don't have very many of those in our codebase, so we have left them 
alone.
Our plugin is designed to convert c-style casts to modern C++ casts.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76572



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


[PATCH] D72281: [Matrix] Add matrix type to Clang.

2020-03-23 Thread Florian Hahn via Phabricator via cfe-commits
fhahn updated this revision to Diff 252043.
fhahn added a comment.

Rebased


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D72281

Files:
  clang/include/clang/AST/ASTContext.h
  clang/include/clang/AST/RecursiveASTVisitor.h
  clang/include/clang/AST/Type.h
  clang/include/clang/AST/TypeLoc.h
  clang/include/clang/AST/TypeProperties.td
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Basic/LangOptions.def
  clang/include/clang/Basic/TypeNodes.td
  clang/include/clang/Driver/Options.td
  clang/include/clang/Sema/Sema.h
  clang/include/clang/Serialization/TypeBitCodes.def
  clang/lib/AST/ASTContext.cpp
  clang/lib/AST/ASTStructuralEquivalence.cpp
  clang/lib/AST/ExprConstant.cpp
  clang/lib/AST/ItaniumMangle.cpp
  clang/lib/AST/MicrosoftMangle.cpp
  clang/lib/AST/Type.cpp
  clang/lib/AST/TypePrinter.cpp
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/lib/CodeGen/CGDebugInfo.h
  clang/lib/CodeGen/CGExpr.cpp
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/CodeGen/CodeGenTypes.cpp
  clang/lib/CodeGen/ItaniumCXXABI.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaLookup.cpp
  clang/lib/Sema/SemaTemplate.cpp
  clang/lib/Sema/SemaTemplateDeduction.cpp
  clang/lib/Sema/SemaType.cpp
  clang/lib/Sema/TreeTransform.h
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/test/CodeGen/matrix-type.c
  clang/test/CodeGenCXX/matrix-type.cpp
  clang/test/SemaCXX/matrix-type.cpp
  clang/tools/libclang/CIndex.cpp

Index: clang/tools/libclang/CIndex.cpp
===
--- clang/tools/libclang/CIndex.cpp
+++ clang/tools/libclang/CIndex.cpp
@@ -1798,6 +1798,8 @@
 DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
 DEFAULT_TYPELOC_IMPL(Vector, Type)
 DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
+DEFAULT_TYPELOC_IMPL(Matrix, Type)
+DEFAULT_TYPELOC_IMPL(DependentSizedMatrix, Type)
 DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
 DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
 DEFAULT_TYPELOC_IMPL(Record, TagType)
Index: clang/test/SemaCXX/matrix-type.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/matrix-type.cpp
@@ -0,0 +1,53 @@
+// RUN: %clang_cc1 -fsyntax-only -pedantic -fenable-matrix -std=c++11 -verify -triple x86_64-apple-darwin %s
+
+using matrix_double_t = double __attribute__((matrix_type(6, 6)));
+using matrix_float_t = float __attribute__((matrix_type(6, 6)));
+using matrix_int_t = int __attribute__((matrix_type(6, 6)));
+
+void matrix_var_dimensions(int Rows, unsigned Columns, char C) {
+  using matrix1_t = int __attribute__((matrix_type(Rows, 1)));// expected-error{{matrix_type attribute requires an integer constant}}
+  using matrix2_t = int __attribute__((matrix_type(1, Columns))); // expected-error{{matrix_type attribute requires an integer constant}}
+  using matrix3_t = int __attribute__((matrix_type(C, C)));   // expected-error{{matrix_type attribute requires an integer constant}}
+  using matrix4_t = int __attribute__((matrix_type(-1, 1)));  // expected-error{{vector size too large}}
+  using matrix5_t = int __attribute__((matrix_type(1, -1)));  // expected-error{{vector size too large}}
+  using matrix6_t = int __attribute__((matrix_type(0, 1)));   // expected-error{{zero vector size}}
+  using matrix7_t = int __attribute__((matrix_type(1, 0)));   // expected-error{{zero vector size}}
+  using matrix7_t = int __attribute__((matrix_type(char, 0)));// expected-error{{expected '(' for function-style cast or type construction}}
+}
+
+struct S1 {};
+
+void matrix_unsupported_element_type() {
+  using matrix1_t = char *__attribute__((matrix_type(1, 1))); // expected-error{{invalid matrix element type 'char *'}}
+  using matrix2_t = S1 __attribute__((matrix_type(1, 1)));// expected-error{{invalid matrix element type 'S1'}}
+}
+
+template  // expected-note{{declared here}}
+void matrix_template_1() {
+  using matrix1_t = float __attribute__((matrix_type(T, T))); // expected-error{{'T' does not refer to a value}}
+}
+
+template  // expected-note{{declared here}}
+void matrix_template_2() {
+  using matrix1_t = float __attribute__((matrix_type(C, C))); // expected-error{{'C' does not refer to a value}}
+}
+
+template 
+void matrix_template_3() {
+  using matrix1_t = float __attribute__((matrix_type(Rows, Cols))); // expected-error{{zero vector size}}
+}
+
+void instantiate_template_3() {
+  matrix_template_3<1, 10>();
+  matrix_template_3<0, 10>(); // expected-note{{in instantiation of function template specialization 'matrix_template_3<0, 10>' requested here}}
+}
+
+template 
+void matrix_template_4() {
+  using matrix1_t = float __attribute__((matrix_type(Rows, Cols))); // expected-error{{vector size too

[PATCH] D76355: [Syntax] Build mapping from AST to syntax tree nodes

2020-03-23 Thread Marcel Hlopko via Phabricator via cfe-commits
hlopko added a comment.

PTAL.




Comment at: clang/lib/Tooling/Syntax/BuildTree.cpp:173
+private:
+  // Keys are either Stmt* or Decl*.
+  llvm::DenseMap Nodes;

gribozavr2 wrote:
> The comment is not needed anymore.
Clang tidy complains when I remove it :/


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76355



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


[PATCH] D69330: [AST] Add RecoveryExpr to retain expressions on semantic errors

2020-03-23 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 252046.
hokein added a comment.

- add -frecovery-ast cc1 option
- defer changes for existing tests.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69330

Files:
  clang/include/clang/AST/ComputeDependence.h
  clang/include/clang/AST/Expr.h
  clang/include/clang/AST/RecursiveASTVisitor.h
  clang/include/clang/Basic/LangOptions.def
  clang/include/clang/Basic/StmtNodes.td
  clang/include/clang/Driver/CC1Options.td
  clang/include/clang/Sema/Sema.h
  clang/include/clang/Serialization/ASTBitCodes.h
  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/StmtPrinter.cpp
  clang/lib/AST/StmtProfile.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/lib/Parse/ParseExpr.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaExceptionSpec.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/TreeTransform.h
  clang/lib/Serialization/ASTReaderStmt.cpp
  clang/lib/Serialization/ASTWriterDecl.cpp
  clang/lib/Serialization/ASTWriterStmt.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
  clang/test/AST/ast-dump-expr-errors.cpp
  clang/test/AST/ast-dump-recovery.cpp
  clang/test/Index/getcursor-recovery.cpp
  clang/test/SemaTemplate/recovery-tree-transform.cpp
  clang/tools/libclang/CXCursor.cpp

Index: clang/tools/libclang/CXCursor.cpp
===
--- clang/tools/libclang/CXCursor.cpp
+++ clang/tools/libclang/CXCursor.cpp
@@ -292,6 +292,7 @@
   case Stmt::ObjCDictionaryLiteralClass:
   case Stmt::ObjCBoxedExprClass:
   case Stmt::ObjCSubscriptRefExprClass:
+  case Stmt::RecoveryExprClass:
 K = CXCursor_UnexposedExpr;
 break;
 
Index: clang/test/SemaTemplate/recovery-tree-transform.cpp
===
--- /dev/null
+++ clang/test/SemaTemplate/recovery-tree-transform.cpp
@@ -0,0 +1,4 @@
+// RUN: %clang_cc1 -verify -frecovery-ast %s
+
+template int *p = &void(T::error); // expected-error{{cannot take the address of an rvalue}} expected-error{{type 'int' cannot be used prior to '::'}}
+int *q = p; // expected-note{{in instantiation of variable template specialization 'p' requested here}}
Index: clang/test/Index/getcursor-recovery.cpp
===
--- /dev/null
+++ clang/test/Index/getcursor-recovery.cpp
@@ -0,0 +1,16 @@
+int foo(int, int);
+int foo(int, double);
+int x;
+
+void testTypedRecoveryExpr() {
+  // Inner foo() is a RecoveryExpr, outer foo() is an overloaded call.
+  foo(x, foo(x));
+}
+// RUN: c-index-test -cursor-at=%s:7:3 %s -Xclang -frecovery-ast | FileCheck -check-prefix=OUTER-FOO %s
+// OUTER-FOO: OverloadedDeclRef=foo[2:5, 1:5]
+// RUN: c-index-test -cursor-at=%s:7:7 %s -Xclang -frecovery-ast | FileCheck -check-prefix=OUTER-X %s
+// OUTER-X: DeclRefExpr=x:3:5
+// RUN: c-index-test -cursor-at=%s:7:10 %s -Xclang -frecovery-ast | FileCheck -check-prefix=INNER-FOO %s
+// INNER-FOO: OverloadedDeclRef=foo[2:5, 1:5]
+// RUN: c-index-test -cursor-at=%s:7:14 %s -Xclang -frecovery-ast | FileCheck -check-prefix=INNER-X %s
+// INNER-X: DeclRefExpr=x:3:5
Index: clang/test/AST/ast-dump-recovery.cpp
===
--- /dev/null
+++ clang/test/AST/ast-dump-recovery.cpp
@@ -0,0 +1,74 @@
+// RUN: not %clang_cc1 -triple x86_64-unknown-unknown -Wno-unused-value -fcxx-exceptions -std=gnu++17 -frecovery-ast -ast-dump %s | FileCheck -strict-whitespace %s
+
+int some_func(int *);
+
+// CHECK: VarDecl {{.*}} invalid_call
+// CHECK-NEXT:`-RecoveryExpr {{.*}} contains-errors
+// CHECK-NEXT:  |-UnresolvedLookupExpr {{.*}} 'some_func'
+// CHECK-NEXT:  `-IntegerLiteral {{.*}} 123
+int invalid_call = some_func(123);
+
+int ambig_func(double);
+int ambig_func(float);
+
+// CHECK: VarDecl {{.*}} ambig_call
+// CHECK-NEXT:`-RecoveryExpr {{.*}} contains-errors
+// CHECK-NEXT:  |-UnresolvedLookupExpr {{.*}} 'ambig_func'
+// CHECK-NEXT:  `-IntegerLiteral {{.*}} 123
+int ambig_call = ambig_func(123);
+
+// CHECK: VarDecl {{.*}} unresolved_call1
+// CHECK-NEXT:`-RecoveryExpr {{.*}} contains-errors
+// CHECK-NEXT:  `-UnresolvedLookupExpr {{.*}} 'bar'
+int unresolved_call1 = bar();
+
+// CHECK: VarDecl {{.*}} unresolved_call2
+// CHECK-NEXT:`-CallExpr {{.*}} contains-errors
+// CHECK-NEXT:  |-UnresolvedLookupExpr {{.*}} 'bar'
+// CHECK-NEXT:  |-RecoveryExpr {{.*}} contains-errors
+// CHECK-NEXT:  | `-UnresolvedLookupExpr {{.*}} 'baz'
+// CHECK-NEXT:   `-RecoveryExpr {{.*}} contains-errors
+// CHECK-NEXT: `-UnresolvedLookupExpr {{.*}} 'qux'
+int unresolved_call2 = bar(baz(), qux());
+
+constexpr int a = 10;
+
+// CHECK: VarDecl {{.*}} postfix_inc
+// CHECK-NEXT:`-RecoveryExpr {{.*}} contains-errors
+// CHECK-NEXT:  `-DeclRefExpr {{.*}} 'a'
+int postfix_

[PATCH] D76510: [analyzer] Change the default output type to PD_TEXT_MINIMAL, error if an output loc is missing for PathDiagConsumers that need it

2020-03-23 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus marked an inline comment as done.
Szelethus added inline comments.



Comment at: clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp:26
 #include "clang/CrossTU/CrossTranslationUnit.h"
+#include "clang/Driver/DriverDiagnostic.h"
 #include "clang/Frontend/CompilerInstance.h"

baloghadamsoftware wrote:
> Why?
Woops. I rebased this on a patch that moves `TextDiagnostics` to its own file 
and forgot about this. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76510



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


[PATCH] D76355: [Syntax] Build mapping from AST to syntax tree nodes

2020-03-23 Thread Marcel Hlopko via Phabricator via cfe-commits
hlopko updated this revision to Diff 252045.
hlopko marked 5 inline comments as done.
hlopko added a comment.

Address comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76355

Files:
  clang/include/clang/Tooling/Syntax/Tree.h
  clang/lib/Tooling/Syntax/BuildTree.cpp
  clang/lib/Tooling/Syntax/Mutations.cpp
  clang/lib/Tooling/Syntax/Tree.cpp

Index: clang/lib/Tooling/Syntax/Tree.cpp
===
--- clang/lib/Tooling/Syntax/Tree.cpp
+++ clang/lib/Tooling/Syntax/Tree.cpp
@@ -58,22 +58,33 @@
 
 syntax::Node::Node(NodeKind Kind)
 : Parent(nullptr), NextSibling(nullptr), Kind(static_cast(Kind)),
-  Role(static_cast(NodeRole::Detached)), Original(false),
-  CanModify(false) {}
+  Role(0), Original(false), CanModify(false) {
+  this->setRole(NodeRole::Detached);
+}
 
 bool syntax::Node::isDetached() const { return role() == NodeRole::Detached; }
 
+void syntax::Node::setRole(NodeRole NR) {
+  this->Role = static_cast(NR);
+}
+
 bool syntax::Tree::classof(const Node *N) { return N->kind() > NodeKind::Leaf; }
 
 void syntax::Tree::prependChildLowLevel(Node *Child, NodeRole Role) {
-  assert(Child->Parent == nullptr);
-  assert(Child->NextSibling == nullptr);
   assert(Child->role() == NodeRole::Detached);
   assert(Role != NodeRole::Detached);
 
+  Child->setRole(Role);
+  prependChildLowLevel(Child);
+}
+
+void syntax::Tree::prependChildLowLevel(Node *Child) {
+  assert(Child->Parent == nullptr);
+  assert(Child->NextSibling == nullptr);
+  assert(Child->role() != NodeRole::Detached);
+
   Child->Parent = this;
   Child->NextSibling = this->FirstChild;
-  Child->Role = static_cast(Role);
   this->FirstChild = Child;
 }
 
@@ -94,7 +105,7 @@
N != End;) {
 auto *Next = N->NextSibling;
 
-N->Role = static_cast(NodeRole::Detached);
+N->setRole(NodeRole::Detached);
 N->Parent = nullptr;
 N->NextSibling = nullptr;
 if (N->Original)
Index: clang/lib/Tooling/Syntax/Mutations.cpp
===
--- clang/lib/Tooling/Syntax/Mutations.cpp
+++ clang/lib/Tooling/Syntax/Mutations.cpp
@@ -35,7 +35,7 @@
 assert(!New->isDetached());
 assert(Role != NodeRole::Detached);
 
-New->Role = static_cast(Role);
+New->setRole(Role);
 auto *P = Anchor->parent();
 P->replaceChildRangeLowLevel(Anchor, Anchor, New);
 
Index: clang/lib/Tooling/Syntax/BuildTree.cpp
===
--- clang/lib/Tooling/Syntax/BuildTree.cpp
+++ clang/lib/Tooling/Syntax/BuildTree.cpp
@@ -25,6 +25,8 @@
 #include "clang/Tooling/Syntax/Tokens.h"
 #include "clang/Tooling/Syntax/Tree.h"
 #include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/PointerUnion.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/ScopeExit.h"
 #include "llvm/ADT/SmallVector.h"
@@ -34,6 +36,7 @@
 #include "llvm/Support/FormatVariadic.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/raw_ostream.h"
+#include 
 #include 
 
 using namespace clang;
@@ -145,6 +148,30 @@
   return SourceRange(Start, End);
 }
 
+namespace {
+/// All AST hierarchy roots that can be represented as pointers.
+using ASTPtr = llvm::PointerUnion;
+/// Maintains a mapping from AST to syntax tree nodes. This class will get more
+/// complicated as we support more kinds of AST nodes, e.g. TypeLocs.
+/// FIXME: expose this as public API.
+class ASTToSyntaxMapping {
+public:
+  void add(ASTPtr From, syntax::Tree *To) {
+assert(To != nullptr);
+assert(!From.isNull());
+
+bool Added = Nodes.insert({From, To}).second;
+(void)Added;
+assert(Added && "mapping added twice");
+  }
+
+  syntax::Tree *find(ASTPtr P) const { return Nodes.lookup(P); }
+
+private:
+  llvm::DenseMap Nodes;
+};
+} // namespace
+
 /// A helper class for constructing the syntax tree while traversing a clang
 /// AST.
 ///
@@ -172,7 +199,18 @@
 
   /// Populate children for \p New node, assuming it covers tokens from \p
   /// Range.
-  void foldNode(llvm::ArrayRef Range, syntax::Tree *New);
+  void foldNode(llvm::ArrayRef Range, syntax::Tree *New,
+ASTPtr From) {
+assert(New);
+Pending.foldChildren(Arena, Range, New);
+if (From)
+  Mapping.add(From, New);
+  }
+  void foldNode(llvm::ArrayRef Range, syntax::Tree *New,
+TypeLoc L) {
+// FIXME: add mapping for TypeLocs
+foldNode(Range, New, nullptr);
+  }
 
   /// Must be called with the range of each `DeclaratorDecl`. Ensures the
   /// corresponding declarator nodes are covered by `SimpleDeclaration`.
@@ -195,8 +233,10 @@
   /// Set role for \p T.
   void markChildToken(const syntax::Token *T, NodeRole R);
 
-  /// Set role for the node that spans exactly \p Range.
-  void markChild(llvm::ArrayRef Range, NodeRole R);
+  /// Set role for \p N.
+  void markChild(syntax::Nod

[PATCH] D76534: [clang/docs] Fix various sphinx warnings/errors in docs.

2020-03-23 Thread Florian Hahn via Phabricator via cfe-commits
fhahn added a comment.

In D76534#1934943 , @rjmccall wrote:

> Is the option issue causing the documentation to be wrong in any way, or does 
> it just produce a warning?  If the latter, we could raise this issue with 
> them.


I think it just produces a warning, it looks like sphinx still creates unique 
labels, e.g. 
https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-flto 
for `-flto` and 
https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang1-flto
 for `-flto=`. But LLVM/Clang defaults to SPHINX_WARNINGS_AS_ERRORS=ON and 
there are quite a few instances of this warning.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76534



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


[clang] a711a3a - [Syntax] Build mapping from AST to syntax tree nodes

2020-03-23 Thread Dmitri Gribenko via cfe-commits

Author: Marcel Hlopko
Date: 2020-03-23T16:22:14+01:00
New Revision: a711a3a46039154c38eade8bef1138b77fdb05ee

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

LOG: [Syntax] Build mapping from AST to syntax tree nodes

Summary:
Copy of https://reviews.llvm.org/D72446, submitting with Ilya's permission.

Only used to assign roles to child nodes for now. This is more efficient
than doing range-based queries.

In the future, will be exposed in the public API of syntax trees.

Reviewers: gribozavr2

Reviewed By: gribozavr2

Subscribers: cfe-commits

Tags: #clang

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

Added: 


Modified: 
clang/include/clang/Tooling/Syntax/Tree.h
clang/lib/Tooling/Syntax/BuildTree.cpp
clang/lib/Tooling/Syntax/Mutations.cpp
clang/lib/Tooling/Syntax/Tree.cpp

Removed: 




diff  --git a/clang/include/clang/Tooling/Syntax/Tree.h 
b/clang/include/clang/Tooling/Syntax/Tree.h
index 8702fe60ce1b..bc581004c46e 100644
--- a/clang/include/clang/Tooling/Syntax/Tree.h
+++ b/clang/include/clang/Tooling/Syntax/Tree.h
@@ -126,6 +126,8 @@ class Node {
   // FactoryImpl sets CanModify flag.
   friend class FactoryImpl;
 
+  void setRole(NodeRole NR);
+
   Tree *Parent;
   Node *NextSibling;
   unsigned Kind : 16;
@@ -171,8 +173,11 @@ class Tree : public Node {
   /// Prepend \p Child to the list of children and and sets the parent pointer.
   /// A very low-level operation that does not check any invariants, only used
   /// by TreeBuilder and FactoryImpl.
-  /// EXPECTS: Role != NodeRoleDetached.
+  /// EXPECTS: Role != Detached.
   void prependChildLowLevel(Node *Child, NodeRole Role);
+  /// Like the previous overload, but does not set role for \p Child.
+  /// EXPECTS: Child->Role != Detached
+  void prependChildLowLevel(Node *Child);
   friend class TreeBuilder;
   friend class FactoryImpl;
 

diff  --git a/clang/lib/Tooling/Syntax/BuildTree.cpp 
b/clang/lib/Tooling/Syntax/BuildTree.cpp
index a09ac1c53e34..4103a4d92c7d 100644
--- a/clang/lib/Tooling/Syntax/BuildTree.cpp
+++ b/clang/lib/Tooling/Syntax/BuildTree.cpp
@@ -25,6 +25,8 @@
 #include "clang/Tooling/Syntax/Tokens.h"
 #include "clang/Tooling/Syntax/Tree.h"
 #include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/PointerUnion.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/ScopeExit.h"
 #include "llvm/ADT/SmallVector.h"
@@ -34,6 +36,7 @@
 #include "llvm/Support/FormatVariadic.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/raw_ostream.h"
+#include 
 #include 
 
 using namespace clang;
@@ -145,6 +148,30 @@ static SourceRange getDeclaratorRange(const SourceManager 
&SM, TypeLoc T,
   return SourceRange(Start, End);
 }
 
+namespace {
+/// All AST hierarchy roots that can be represented as pointers.
+using ASTPtr = llvm::PointerUnion;
+/// Maintains a mapping from AST to syntax tree nodes. This class will get more
+/// complicated as we support more kinds of AST nodes, e.g. TypeLocs.
+/// FIXME: expose this as public API.
+class ASTToSyntaxMapping {
+public:
+  void add(ASTPtr From, syntax::Tree *To) {
+assert(To != nullptr);
+assert(!From.isNull());
+
+bool Added = Nodes.insert({From, To}).second;
+(void)Added;
+assert(Added && "mapping added twice");
+  }
+
+  syntax::Tree *find(ASTPtr P) const { return Nodes.lookup(P); }
+
+private:
+  llvm::DenseMap Nodes;
+};
+} // namespace
+
 /// A helper class for constructing the syntax tree while traversing a clang
 /// AST.
 ///
@@ -172,7 +199,18 @@ class syntax::TreeBuilder {
 
   /// Populate children for \p New node, assuming it covers tokens from \p
   /// Range.
-  void foldNode(llvm::ArrayRef Range, syntax::Tree *New);
+  void foldNode(llvm::ArrayRef Range, syntax::Tree *New,
+ASTPtr From) {
+assert(New);
+Pending.foldChildren(Arena, Range, New);
+if (From)
+  Mapping.add(From, New);
+  }
+  void foldNode(llvm::ArrayRef Range, syntax::Tree *New,
+TypeLoc L) {
+// FIXME: add mapping for TypeLocs
+foldNode(Range, New, nullptr);
+  }
 
   /// Must be called with the range of each `DeclaratorDecl`. Ensures the
   /// corresponding declarator nodes are covered by `SimpleDeclaration`.
@@ -195,8 +233,10 @@ class syntax::TreeBuilder {
   /// Set role for \p T.
   void markChildToken(const syntax::Token *T, NodeRole R);
 
-  /// Set role for the node that spans exactly \p Range.
-  void markChild(llvm::ArrayRef Range, NodeRole R);
+  /// Set role for \p N.
+  void markChild(syntax::Node *N, NodeRole R);
+  /// Set role for the syntax node matching \p N.
+  void markChild(ASTPtr N, NodeRole R);
   /// Set role for the delayed node that spans exactly \p Range.
   void markDelayedChild(llvm::ArrayRef Range, NodeRole R);
   /// Set r

  1   2   3   >