[PATCH] D131632: [clang] Enable output of SARIF diagnostics

2022-08-26 Thread Douglas Yung via Phabricator via cfe-commits
dyung added inline comments.



Comment at: clang/test/Frontend/sarif-diagnostics.cpp:8
+// Omit filepath to llvm project directory
+// CHECK: 
clang/test/Frontend/sarif-diagnostics.cpp"},"mimeType":"text/plain","roles":["resultFile"]}],"columnKind":"unicodeCodePoints","results":[{"level":"error","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":1,"startColumn":1,"startLine":12}}}],"message":{"text":"'main'
 must return 
'int'"},"ruleId":"3465","ruleIndex":0},{"level":"error","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":11,"startColumn":11,"startLine":13}}}],"message":{"text":"use
 of undeclared identifier 
'hello'"},"ruleId":"4604","ruleIndex":1},{"level":"error","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":17,"startColumn":17,"startLine":15}}}],"message":{"text":"invalid
 digit 'a' in decimal 
constant"},"ruleId":"898","ruleIndex":2},{"level":"warning","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":5,"startColumn":5,"startLine":19}}}],"message":{"text":"misleading
 indentation; statement is not part of the previous 
'if'"},"ruleId":"1806","ruleIndex":3},{"level":"note","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":3,"startColumn":3,"startLine":17}}}],"message":{"text":"previous
 statement is 
here"},"ruleId":"1730","ruleIndex":4},{"level":"warning","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":10,"startColumn":10,"startLine":18}}}],"message":{"text":"unused
 variable 
'Yes'"},"ruleId":"6539","ruleIndex":5},{"level":"error","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":12,"startColumn":12,"startLine":21}}}],"message":{"text":"use
 of undeclared identifier 
'hi'"},"ruleId":"4604","ruleIndex":6},{"level":"error","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":1,"startColumn":1,"startLine":23}}}],"message":{"text":"extraneous
 closing brace 
('}')"},"ruleId":"1399","ruleIndex":7},{"level":"error","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":6,"endLine":27,"startColumn":5,"startLine":27}}},{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":10,"endLine":27,"startColumn":9,"startLine":27}}},{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":7,"startColumn":7,"startLine":27}}}],"message":{"text":"invalid
 operands to binary expression ('t1' and 
't1')"},"ruleId":"4539","ruleIndex":8}],"tool":{"driver":{"fullName":"","informationUri":"https://clang.llvm.org/docs/UsersManual.html","language":"en-US","name":"clang","rules":[{"defaultConfiguration":{"enabled":true,"level":"error","rank":50},"fullDescription":{"text":""},"id":"3465","name":""},{"defaultConfiguration":{"enabled":true,"level":"error","rank":50},"fullDescription":{"text":""},"id":"4604","name":""},{"defaultConfiguration":{"enabled":true,"level":"error","rank":50},"fullDescription":{"text":""},"id":"898","name":""},{"defaultConfiguration":{"enabled":true,"level":"warning","rank":-1},"fullDescription":{"text":""},"id":"1806","name":""},{"defaultConfiguration":{"enabled":true,"level":"note","rank":-1},"fullDescription":{"text":""},"id":"1730","name":""},{"defaultConfiguration":{"enabled":true,"level":"warning","rank":-1},"fullDescription":{"text":""},"id":"6539","name":""},{"defaultConfiguration":{"enabled":true,"level":"error","rank":50},"fullDescription":{"text":""},"id":"4604","name":""},{"defaultConfiguration":{"enabled":true,"level":"error","rank":50},"fullDescription":{"text":""},"id":"1399","name":""},{"defaultConfiguration":{"enabled":true,"level":"error","rank":50},"fullDescription":{"text":""},"id":"4539","name":""}],"version":"16.0.0"}}}],"version":"2.1.0"}
+// CHECK: 2 warnings and 6 errors generated.

dyung wrote:
> Can this CHECK line be broken into smaller pieces? This test is failing on 
> our internal bot, and I'm going crosseyed trying to figure out what the 
> difference is because the line is 3741 characters long!
Is there any significance to the "ruleId" and "Id" values in this test? If not, 
can we just use a regex to check for a number? Our internal build with private 
changes is failing due to slightly different numbers in some of the "ruleId" 
fields


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131632

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


[PATCH] D131632: [clang] Enable output of SARIF diagnostics

2022-08-26 Thread Douglas Yung via Phabricator via cfe-commits
dyung added inline comments.



Comment at: clang/test/Frontend/sarif-diagnostics.cpp:8
+// Omit filepath to llvm project directory
+// CHECK: 
clang/test/Frontend/sarif-diagnostics.cpp"},"mimeType":"text/plain","roles":["resultFile"]}],"columnKind":"unicodeCodePoints","results":[{"level":"error","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":1,"startColumn":1,"startLine":12}}}],"message":{"text":"'main'
 must return 
'int'"},"ruleId":"3465","ruleIndex":0},{"level":"error","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":11,"startColumn":11,"startLine":13}}}],"message":{"text":"use
 of undeclared identifier 
'hello'"},"ruleId":"4604","ruleIndex":1},{"level":"error","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":17,"startColumn":17,"startLine":15}}}],"message":{"text":"invalid
 digit 'a' in decimal 
constant"},"ruleId":"898","ruleIndex":2},{"level":"warning","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":5,"startColumn":5,"startLine":19}}}],"message":{"text":"misleading
 indentation; statement is not part of the previous 
'if'"},"ruleId":"1806","ruleIndex":3},{"level":"note","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":3,"startColumn":3,"startLine":17}}}],"message":{"text":"previous
 statement is 
here"},"ruleId":"1730","ruleIndex":4},{"level":"warning","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":10,"startColumn":10,"startLine":18}}}],"message":{"text":"unused
 variable 
'Yes'"},"ruleId":"6539","ruleIndex":5},{"level":"error","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":12,"startColumn":12,"startLine":21}}}],"message":{"text":"use
 of undeclared identifier 
'hi'"},"ruleId":"4604","ruleIndex":6},{"level":"error","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":1,"startColumn":1,"startLine":23}}}],"message":{"text":"extraneous
 closing brace 
('}')"},"ruleId":"1399","ruleIndex":7},{"level":"error","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":6,"endLine":27,"startColumn":5,"startLine":27}}},{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":10,"endLine":27,"startColumn":9,"startLine":27}}},{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":7,"startColumn":7,"startLine":27}}}],"message":{"text":"invalid
 operands to binary expression ('t1' and 
't1')"},"ruleId":"4539","ruleIndex":8}],"tool":{"driver":{"fullName":"","informationUri":"https://clang.llvm.org/docs/UsersManual.html","language":"en-US","name":"clang","rules":[{"defaultConfiguration":{"enabled":true,"level":"error","rank":50},"fullDescription":{"text":""},"id":"3465","name":""},{"defaultConfiguration":{"enabled":true,"level":"error","rank":50},"fullDescription":{"text":""},"id":"4604","name":""},{"defaultConfiguration":{"enabled":true,"level":"error","rank":50},"fullDescription":{"text":""},"id":"898","name":""},{"defaultConfiguration":{"enabled":true,"level":"warning","rank":-1},"fullDescription":{"text":""},"id":"1806","name":""},{"defaultConfiguration":{"enabled":true,"level":"note","rank":-1},"fullDescription":{"text":""},"id":"1730","name":""},{"defaultConfiguration":{"enabled":true,"level":"warning","rank":-1},"fullDescription":{"text":""},"id":"6539","name":""},{"defaultConfiguration":{"enabled":true,"level":"error","rank":50},"fullDescription":{"text":""},"id":"4604","name":""},{"defaultConfiguration":{"enabled":true,"level":"error","rank":50},"fullDescription":{"text":""},"id":"1399","name":""},{"defaultConfiguration":{"enabled":true,"level":"error","rank":50},"fullDescription":{"text":""},"id":"4539","name":""}],"version":"16.0.0"}}}],"version":"2.1.0"}
+// CHECK: 2 warnings and 6 errors generated.

Can this CHECK line be broken into smaller pieces? This test is failing on our 
internal bot, and I'm going crosseyed trying to figure out what the difference 
is because the line is 3741 characters long!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131632

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


[PATCH] D132136: [clang] Perform implicit lvalue-to-rvalue cast with new interpreter

2022-08-26 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder added a comment.

In D132136#3751702 , @erichkeane 
wrote:

> Would be great if we had a better test here... is there anything we can do to 
> validate this is happening other than checking for that one note?

`EvaluateAsRValue` is called from `Expr::EvaluateAsRValue()`, so I think it 
would be possible to write a unittest for this. But I think that would be a lot 
of effort just to test this. There is even 
`unittests/AST/EvaluateAsRValueTest.cpp` already, but it tests the wrong thing 
:(


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

https://reviews.llvm.org/D132136

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


[PATCH] D132739: [clang][Interp] Implement IntegralToBoolean casts

2022-08-26 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder marked an inline comment as done.
tbaeder added inline comments.



Comment at: clang/lib/AST/Interp/Boolean.h:90
+  template  static Boolean from(T Value) {
+if constexpr (std::is_integral::value)
+  return Boolean(Value != 0);

shafik wrote:
> This should work for `floating_point` as well.
We don't do floating point values yet.



Comment at: clang/lib/AST/Interp/Boolean.h:91
+if constexpr (std::is_integral::value)
+  return Boolean(Value != 0);
+return Boolean(static_cast(Value) != 0);

shafik wrote:
> Why the `!= 0` shouldn't these all implicitly convert to `bool` with 
> appropriate values?
Not 100% sure why this was used, it was there before so I left it in.


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

https://reviews.llvm.org/D132739

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


[PATCH] D132236: [analyzer] Fix liveness of LazyCompoundVals

2022-08-26 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added a comment.

> For FPs I dont know how to automate this process. :/

Given that our initial hypothesis was that there should be zero new false 
positives, it could probably work with a creduce predicate //"this code has a 
warning after the patch but not before the patch"//. The initial hypothesis is 
probably not entirely correct, given that even a slight change in coverage 
could result in false positives, but I doubt that if you pick 4-5 examples, all 
of them would reduce to a situation where it's just a change of coverage. 
Especially given how common you say the problem appears to be. So I think it's 
worth a try.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132236

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


[PATCH] D130513: [Flang] Add -fconvert option to swap endianness for unformatted files

2022-08-26 Thread Peixin Qiao via Phabricator via cfe-commits
peixin added a comment.

  $ cat fconvert_option_main_2.f90 
  !
  ! Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
  ! See https://llvm.org/LICENSE.txt for license information.
  ! SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  !
  ! checking for I/O: testing read with -fconvert=big-endian.
  ! The convert argument of open function has prior claim over fconvert option.
  ! Only main program intentionally compiled with -fconvert=big-endian.
  
  program fconvert_option_main_2
use fconvert_option_openfile
use fconvert_option_readfile
  
integer, parameter :: n = 4
integer :: del_flag = 0 ! 1 for deleting data file after read
real :: arr(n) = [1.0, 2.0, 3.0, 4.0]
character(:), allocatable :: filename
integer :: arglen
  
call get_command_argument(1, length = arglen)
allocate(character(arglen) :: filename)
call get_command_argument(1, value = filename)
  
call open_for_read_LE(10, filename)
call readfile(10, del_flag, arr, n, 0)
  
call open_for_read_native(11, filename)
call readfile(11, del_flag, arr, n, 4)
  
print *, 'PASS'
  end
  $ cat fconvert_option_readfile.f90 
  !
  ! Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
  ! See https://llvm.org/LICENSE.txt for license information.
  ! SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  !
  ! checking for I/O: readfile subroutine
  
  module fconvert_option_readfile
  
  contains
subroutine readfile(fid, del_flag, expect, n, t)
  integer :: n, t
  integer :: fid, del_flag
  real :: expect(n)
  real :: buf(n)
  
  read (fid) buf
  if (del_flag .eq. 0) then
close (fid)
  else
close (fid, status='delete')
  end if
  
  do i = 1, n
if (buf(i) .ne. expect(i)) stop (i+t)
  enddo
end
  end
  $ cat fconvert_option_openfile.f90 
  !
  ! Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
  ! See https://llvm.org/LICENSE.txt for license information.
  ! SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  !
  ! checking for I/O: openfile subroutines
  
  module fconvert_option_openfile
  
  contains
subroutine open_for_read(fid, file_name)
  integer :: fid
  character(:), allocatable :: file_name
  open (fid, file=file_name, form='UNFORMATTED', status='old')
end
subroutine open_for_read_BE(fid, file_name)
  integer :: fid
  character(:), allocatable :: file_name
  open (fid, file=file_name, form='UNFORMATTED', status='old', 
convert="BIG_ENDIAN")
end
subroutine open_for_read_LE(fid, file_name)
  integer :: fid
  character(:), allocatable :: file_name
  open (fid, file=file_name, form='UNFORMATTED', status='old', 
convert="LITTLE_ENDIAN")
end
subroutine open_for_read_native(fid, file_name)
  integer :: fid
  character(:), allocatable :: file_name
  open (fid, file=file_name, form='UNFORMATTED', status='old', 
convert="NATIVE")
end
  
subroutine open_for_write(fid, file_name)
  integer :: fid
  character(:), allocatable :: file_name
  open (fid, file=file_name, form='UNFORMATTED', status='new')
end
subroutine open_for_write_BE(fid, file_name)
  integer :: fid
  character(:), allocatable :: file_name
  open (fid, file=file_name, form='UNFORMATTED', status='new', 
convert="BIG_ENDIAN")
end
subroutine open_for_write_LE(fid, file_name)
  integer :: fid
  character(:), allocatable :: file_name
  open (fid, file=file_name, form='UNFORMATTED', status='new', 
convert="LITTLE_ENDIAN")
end
subroutine open_for_write_native(fid, file_name)
  integer :: fid
  character(:), allocatable :: file_name
  open (fid, file=file_name, form='UNFORMATTED', status='new', 
convert="NATIVE")
end
  end
  $ cat fconvert_option_writefile.f90 
  !
  ! Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
  ! See https://llvm.org/LICENSE.txt for license information.
  ! SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  !
  ! checking for I/O: writefile subroutine
  
  module fconvert_option_writefile
  
  contains
subroutine writefile(fid, buf, n)
  integer :: n
  real :: buf(n)
  integer :: fid
  
  write (fid) buf
  close (fid)
end
  end
  $ cat run.sh 
  #!/bin/bash
  
  echo "-- gfortran --"
  gfortran fconvert_option_readfile.f90 -c
  gfortran fconvert_option_openfile.f90 -c
  gfortran fconvert_option_writefile.f90 -c
  gfortran $1.f90 $2 -c
  gfortran $1.o fconvert_option_readfile.o fconvert_option_openfile.o 
fconvert_option_writefile.o
  ./a.out Inputs/fc_opt_data_$3 && rm *.o *.mod a.out
  
  echo && echo "-- flang-new --"
  flang-new fconvert_option_readfile.f90 -c
  flang-new fconvert_option_openfile.f90 -c
  flang-new fconvert_option_writefile.f90 -c
  flang-new $1.f90 $2 -c
  flang-new -flang-expe

[PATCH] D132779: Enforce module decl-use restrictions and private header restrictions in textual headers

2022-08-26 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith updated this revision to Diff 456077.
rsmith added a comment.

Add release notes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132779

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/LangOptions.def
  clang/include/clang/Driver/Options.td
  clang/include/clang/Lex/Preprocessor.h
  clang/lib/Lex/PPDirectives.cpp
  clang/test/Modules/Inputs/declare-use/module.map
  clang/test/Modules/Inputs/declare-use/textual.h
  clang/test/Modules/declare-use-textual.cpp

Index: clang/test/Modules/declare-use-textual.cpp
===
--- /dev/null
+++ clang/test/Modules/declare-use-textual.cpp
@@ -0,0 +1,6 @@
+// RUN: rm -rf %t
+// RUN: %clang_cc1 -fimplicit-module-maps -fmodules-cache-path=%t -fmodules-decluse -fmodule-name=Textual -I %S/Inputs/declare-use %s -verify
+// RUN: %clang_cc1 -fimplicit-module-maps -fmodules-cache-path=%t -fmodules-decluse -fmodule-name=Textual -I %S/Inputs/declare-use %s -fno-modules-validate-textual-header-includes
+
+// expected-error@textual.h:* {{module Textual does not depend on a module exporting 'a.h'}}
+#include "textual.h"
Index: clang/test/Modules/Inputs/declare-use/textual.h
===
--- /dev/null
+++ clang/test/Modules/Inputs/declare-use/textual.h
@@ -0,0 +1 @@
+#include "a.h"
Index: clang/test/Modules/Inputs/declare-use/module.map
===
--- clang/test/Modules/Inputs/declare-use/module.map
+++ clang/test/Modules/Inputs/declare-use/module.map
@@ -73,3 +73,7 @@
 
 module XS {
 }
+
+module Textual {
+  textual header "textual.h"
+}
Index: clang/lib/Lex/PPDirectives.cpp
===
--- clang/lib/Lex/PPDirectives.cpp
+++ clang/lib/Lex/PPDirectives.cpp
@@ -856,7 +856,8 @@
 Tok.getLocation());
 }
 
-Module *Preprocessor::getModuleForLocation(SourceLocation Loc) {
+Module *Preprocessor::getModuleForLocation(SourceLocation Loc,
+   bool AllowTextual) {
   if (!SourceMgr.isInMainFile(Loc)) {
 // Try to determine the module of the include directive.
 // FIXME: Look into directly passing the FileEntry from LookupFile instead.
@@ -864,7 +865,7 @@
 if (const FileEntry *EntryOfIncl = SourceMgr.getFileEntryForID(IDOfIncl)) {
   // The include comes from an included file.
   return HeaderInfo.getModuleMap()
-  .findModuleForHeader(EntryOfIncl)
+  .findModuleForHeader(EntryOfIncl, AllowTextual)
   .getModule();
 }
   }
@@ -879,7 +880,8 @@
 const FileEntry *
 Preprocessor::getHeaderToIncludeForDiagnostics(SourceLocation IncLoc,
SourceLocation Loc) {
-  Module *IncM = getModuleForLocation(IncLoc);
+  Module *IncM = getModuleForLocation(
+  IncLoc, LangOpts.ModulesValidateTextualHeaderIncludes);
 
   // Walk up through the include stack, looking through textual headers of M
   // until we hit a non-textual header that we can #include. (We assume textual
@@ -953,7 +955,8 @@
   ConstSearchDirIterator CurDirLocal = nullptr;
   ConstSearchDirIterator &CurDir = CurDirArg ? *CurDirArg : CurDirLocal;
 
-  Module *RequestingModule = getModuleForLocation(FilenameLoc);
+  Module *RequestingModule = getModuleForLocation(
+  FilenameLoc, LangOpts.ModulesValidateTextualHeaderIncludes);
   bool RequestingModuleIsModuleInterface = !SourceMgr.isInMainFile(FilenameLoc);
 
   // If the header lookup mechanism may be relative to the current inclusion
Index: clang/include/clang/Lex/Preprocessor.h
===
--- clang/include/clang/Lex/Preprocessor.h
+++ clang/include/clang/Lex/Preprocessor.h
@@ -2546,7 +2546,7 @@
   /// Find the module that owns the source or header file that
   /// \p Loc points to. If the location is in a file that was included
   /// into a module, or is outside any module, returns nullptr.
-  Module *getModuleForLocation(SourceLocation Loc);
+  Module *getModuleForLocation(SourceLocation Loc, bool AllowTextual);
 
   /// We want to produce a diagnostic at location IncLoc concerning an
   /// unreachable effect at location MLoc (eg, where a desired entity was
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -2283,6 +2283,11 @@
   HeaderSearchOpts<"ModulesValidateSystemHeaders">, DefaultFalse,
   PosFlag,
   NegFlag>, Group;
+def fno_modules_validate_textual_header_includes :
+  Flag<["-"], "fno-modules-validate-textual-header-includes">,
+  Group, Flags<[CC1Option, NoXarchOption]>,
+  MarshallingInfoNegativeFlag>,
+  HelpText<"Do not enforce -fmodules-decluse and private header restrictions for textual headers.

[PATCH] D132779: Enforce module decl-use restrictions and private header restrictions in textual headers

2022-08-26 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith created this revision.
rsmith added reviewers: Bigcheese, aaron.ballman.
Herald added a project: All.
rsmith requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Per the documentation, these restrictions were intended to apply to textual 
headers but previously this didn't work because we decided there was no 
requesting module when the `#include` was in a textual header.

  

A `-cc1` flag is provided to restore the old behavior for transitionary 
purposes.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D132779

Files:
  clang/include/clang/Basic/LangOptions.def
  clang/include/clang/Driver/Options.td
  clang/include/clang/Lex/Preprocessor.h
  clang/lib/Lex/PPDirectives.cpp
  clang/test/Modules/Inputs/declare-use/module.map
  clang/test/Modules/Inputs/declare-use/textual.h
  clang/test/Modules/declare-use-textual.cpp

Index: clang/test/Modules/declare-use-textual.cpp
===
--- /dev/null
+++ clang/test/Modules/declare-use-textual.cpp
@@ -0,0 +1,6 @@
+// RUN: rm -rf %t
+// RUN: %clang_cc1 -fimplicit-module-maps -fmodules-cache-path=%t -fmodules-decluse -fmodule-name=Textual -I %S/Inputs/declare-use %s -verify
+// RUN: %clang_cc1 -fimplicit-module-maps -fmodules-cache-path=%t -fmodules-decluse -fmodule-name=Textual -I %S/Inputs/declare-use %s -fno-modules-validate-textual-header-includes
+
+// expected-error@textual.h:* {{module Textual does not depend on a module exporting 'a.h'}}
+#include "textual.h"
Index: clang/test/Modules/Inputs/declare-use/textual.h
===
--- /dev/null
+++ clang/test/Modules/Inputs/declare-use/textual.h
@@ -0,0 +1 @@
+#include "a.h"
Index: clang/test/Modules/Inputs/declare-use/module.map
===
--- clang/test/Modules/Inputs/declare-use/module.map
+++ clang/test/Modules/Inputs/declare-use/module.map
@@ -73,3 +73,7 @@
 
 module XS {
 }
+
+module Textual {
+  textual header "textual.h"
+}
Index: clang/lib/Lex/PPDirectives.cpp
===
--- clang/lib/Lex/PPDirectives.cpp
+++ clang/lib/Lex/PPDirectives.cpp
@@ -856,7 +856,8 @@
 Tok.getLocation());
 }
 
-Module *Preprocessor::getModuleForLocation(SourceLocation Loc) {
+Module *Preprocessor::getModuleForLocation(SourceLocation Loc,
+   bool AllowTextual) {
   if (!SourceMgr.isInMainFile(Loc)) {
 // Try to determine the module of the include directive.
 // FIXME: Look into directly passing the FileEntry from LookupFile instead.
@@ -864,7 +865,7 @@
 if (const FileEntry *EntryOfIncl = SourceMgr.getFileEntryForID(IDOfIncl)) {
   // The include comes from an included file.
   return HeaderInfo.getModuleMap()
-  .findModuleForHeader(EntryOfIncl)
+  .findModuleForHeader(EntryOfIncl, AllowTextual)
   .getModule();
 }
   }
@@ -879,7 +880,8 @@
 const FileEntry *
 Preprocessor::getHeaderToIncludeForDiagnostics(SourceLocation IncLoc,
SourceLocation Loc) {
-  Module *IncM = getModuleForLocation(IncLoc);
+  Module *IncM = getModuleForLocation(
+  IncLoc, LangOpts.ModulesValidateTextualHeaderIncludes);
 
   // Walk up through the include stack, looking through textual headers of M
   // until we hit a non-textual header that we can #include. (We assume textual
@@ -953,7 +955,8 @@
   ConstSearchDirIterator CurDirLocal = nullptr;
   ConstSearchDirIterator &CurDir = CurDirArg ? *CurDirArg : CurDirLocal;
 
-  Module *RequestingModule = getModuleForLocation(FilenameLoc);
+  Module *RequestingModule = getModuleForLocation(
+  FilenameLoc, LangOpts.ModulesValidateTextualHeaderIncludes);
   bool RequestingModuleIsModuleInterface = !SourceMgr.isInMainFile(FilenameLoc);
 
   // If the header lookup mechanism may be relative to the current inclusion
Index: clang/include/clang/Lex/Preprocessor.h
===
--- clang/include/clang/Lex/Preprocessor.h
+++ clang/include/clang/Lex/Preprocessor.h
@@ -2546,7 +2546,7 @@
   /// Find the module that owns the source or header file that
   /// \p Loc points to. If the location is in a file that was included
   /// into a module, or is outside any module, returns nullptr.
-  Module *getModuleForLocation(SourceLocation Loc);
+  Module *getModuleForLocation(SourceLocation Loc, bool AllowTextual);
 
   /// We want to produce a diagnostic at location IncLoc concerning an
   /// unreachable effect at location MLoc (eg, where a desired entity was
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -2283,6 +2283,11 @@
   HeaderSearchOpts<"ModulesValidateSystemHeaders

[clang] 5284cf0 - [Clang][Driver] Temporarily disable failing DriverKit test

2022-08-26 Thread Julian Lettner via cfe-commits

Author: Julian Lettner
Date: 2022-08-26T18:32:51-07:00
New Revision: 5284cf0098c150137983d9e6326fc1ac014428a6

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

LOG: [Clang][Driver] Temporarily disable failing DriverKit test

Added: 


Modified: 
clang/test/Driver/driverkit-path.c

Removed: 




diff  --git a/clang/test/Driver/driverkit-path.c 
b/clang/test/Driver/driverkit-path.c
index 755cb228e7ed6..0aa3e958b2908 100644
--- a/clang/test/Driver/driverkit-path.c
+++ b/clang/test/Driver/driverkit-path.c
@@ -1,4 +1,7 @@
 // REQUIRES: x86-registered-target
+// REQUIRES: darwin
+// FIXME: Breaks on non-macOS:
+//http://45.33.8.238/linux/85125/step_7.txt
 // RUN: %clang %s -target x86_64-apple-driverkit19.0 -mlinker-version=0 \
 // RUN:   -isysroot %S/Inputs/DriverKit19.0.sdk -### 2>&1   \
 // RUN: | FileCheck %s --check-prefix=LD64-OLD



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


[PATCH] D128113: Clang: fix AST representation of expanded template arguments.

2022-08-26 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh added a comment.

In D128113#3751477 , @mizvekov wrote:

> In D128113#3747946 , @alexfh wrote:
>
>> For now we've added a workaround for the most problematic use case and got 
>> us unblocked. Thus there is no need now in introducing additional flags. 
>> However, I'm rather concerned about the cumulative additional overhead our 
>> build infrastructure gets as a result of this patch. Measuring this would 
>> unfortunately be a project of its own, which I'm not ready to commit to. If 
>> reverting this and discussing with Richard Smith is an option for you, I'd 
>> suggest doing this now and if you end up not finding a good alternative, we 
>> would probably need to find a way to estimate the impact of this patch. WDYT?
>
> Thanks, and sorry for the long time to respond to this.
>
> I have been thinking about this problem, and I have an idea for a solution 
> which is better on the performance side, but more complex change.
>
> We would need to implement some pattern matching during AST traversal, and 
> keep track of the pack index there. When extracting a component of the larger 
> type, such as when deducing non-pack arguments from a pack, we would wrap it 
> over with a new sugar type node which encodes the current pack indexes.
>
> I reflected a bit on this, and yeah I think we should try to design something 
> which does not potentially hinder large packs so much.
>
> I am not sure how this is going to play out in practice, and it's possible we 
> may need to come back to this solution again, but I think it's prudent to 
> revert it for now if we are not sure, as this is an API change, however 
> obscure for most users.

I appreciate your effort on designing an alternative solution. Hopefully, it 
works out well.

> As an aside, it would be really helpful if you could track how the 
> compilation of your codebase performs as clang evolves, regardless if we keep 
> this change or not :)
> Maybe you can reuse something from http://llvm-compile-time-tracker.com/

Good point about tracking compile time. We do have compiler performance tests 
running in a controlled environment with a number of measures in place to 
reduce errors in results, but they are limited to a rather small sample of 
build targets. Tracking compiler performance (times, memory used) for all of 
our code and using this as a regression test for compiler performance is 
impractical due to the size of the code base, rate of changes, and the design 
of the build system (high level of parallelism, aggressive caching, shared 
build cluster consisting of machines with different performance 
characteristics).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128113

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


[PATCH] D132592: [Clang] Implement function attribute nouwtable

2022-08-26 Thread Yuanfang Chen via Phabricator via cfe-commits
ychen added a comment.

In D132592#3751561 , @aaron.ballman 
wrote:

> In D132592#3749567 , @ychen wrote:
>
>> Thanks for taking a look!
>>
>> In D132592#3749261 , 
>> @aaron.ballman wrote:
>>
>>> Do we have any evidence that users need this level of control or will 
>>> understand how to properly use the attribute? The command line option makes 
>>> sense to me because it's an all-or-nothing flag, but I'm not certain I 
>>> understand the need for per-function control.
>>
>> https://github.com/llvm/llvm-project/blob/064a08cd955019da9130f1109bfa534e79b8ec7c/llvm/include/llvm/IR/Function.h#L639-L641,
>>  per-function unwind table entry depends on both nounwind and uwtable. We 
>> have nothrow attribute for nounwind but not nouwtable for uwtable. With 
>> this, a user could use function attributes to control unwind table entry 
>> generation which could only be achieved by inline assembly or writing 
>> assembly files directly. I'd consider this a companion of nothrow. So making 
>> them both per-function attribute seems natural?
>>
>>> Also, if a user gets this wrong (applies the attribute where they 
>>> shouldn't), what is the failure mode (does it introduce any exploitable 
>>> behavior)?
>>
>> The flag may only suppress unwind table emission instead of causing more, 
>> the lack of unwind table may only stop control flow rather than giving it 
>> more freedom. So I think this is safe from a security perspective. Using it 
>> wrong may cause unnecessary crashes just like any other memory bugs, but not 
>> a malicious binary.
>
> Thank you for the explanations, that helped. :-)
>
> You're missing all of the semantic tests (that the attr takes no arguments, 
> only applies to function-like things, etc). Also, the subject you picked is 
> `FunctionLike` so you should have some test coverage showing how this works 
> when calling through a function pointer with the attribute (or you should 
> pick a more appropriate subject if that one is wrong).

Yes, `Function` is more proper than `FunctionLike`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132592

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


[PATCH] D132592: [Clang] Implement function attribute nouwtable

2022-08-26 Thread Yuanfang Chen via Phabricator via cfe-commits
ychen updated this revision to Diff 456069.
ychen added a comment.

- change from `FunctionLike` to `Function`
- add a Sema test
- update doc


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132592

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/test/CodeGen/attr-nouwtable.c
  clang/test/Misc/pragma-attribute-supported-attributes-list.test
  clang/test/Sema/attr-nouwtable.c


Index: clang/test/Sema/attr-nouwtable.c
===
--- /dev/null
+++ clang/test/Sema/attr-nouwtable.c
@@ -0,0 +1,6 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+void *t1() __attribute__((nouwtable(1))); // expected-error {{'nouwtable' 
attribute takes no arguments}}
+
+typedef void (*F)(void);
+__attribute__((nouwtable)) F f; // expected-warning {{'nouwtable' attribute 
only applies to functions}}
Index: clang/test/Misc/pragma-attribute-supported-attributes-list.test
===
--- clang/test/Misc/pragma-attribute-supported-attributes-list.test
+++ clang/test/Misc/pragma-attribute-supported-attributes-list.test
@@ -114,6 +114,7 @@
 // CHECK-NEXT: NoStackProtector (SubjectMatchRule_function)
 // CHECK-NEXT: NoThreadSafetyAnalysis (SubjectMatchRule_function)
 // CHECK-NEXT: NoThrow (SubjectMatchRule_hasType_functionType)
+// CHECK-NEXT: NoUwtable (SubjectMatchRule_function)
 // CHECK-NEXT: NotTailCalled (SubjectMatchRule_function)
 // CHECK-NEXT: OSConsumed (SubjectMatchRule_variable_is_parameter)
 // CHECK-NEXT: OSReturnsNotRetained (SubjectMatchRule_function, 
SubjectMatchRule_objc_method, SubjectMatchRule_objc_property, 
SubjectMatchRule_variable_is_parameter)
Index: clang/test/CodeGen/attr-nouwtable.c
===
--- /dev/null
+++ clang/test/CodeGen/attr-nouwtable.c
@@ -0,0 +1,14 @@
+// RUN: %clang_cc1 -funwind-tables=2 -S -emit-llvm %s -o - | FileCheck %s
+
+void t1(void) {}
+
+void t2(void) __attribute__((nouwtable));
+void t2(void) {}
+
+// CHECK: @t1{{.*}}[[ATTR1:#[0-9]+]]
+// CHECK: @t2{{.*}}[[ATTR2:#[0-9]+]]
+
+// CHECK: attributes [[ATTR1]] = {{{.*}}uwtable{{.*}}}
+// CHECK: attributes [[ATTR2]] = {
+// CHECK-NOT: uwtable
+// CHECK: }
Index: clang/lib/CodeGen/CodeGenModule.cpp
===
--- clang/lib/CodeGen/CodeGenModule.cpp
+++ clang/lib/CodeGen/CodeGenModule.cpp
@@ -1942,7 +1942,7 @@
llvm::Function *F) {
   llvm::AttrBuilder B(F->getContext());
 
-  if (CodeGenOpts.UnwindTables)
+  if ((!D || !D->hasAttr()) && CodeGenOpts.UnwindTables)
 B.addUWTableAttr(llvm::UWTableKind(CodeGenOpts.UnwindTables));
 
   if (CodeGenOpts.StackClashProtector)
Index: clang/include/clang/Basic/AttrDocs.td
===
--- clang/include/clang/Basic/AttrDocs.td
+++ clang/include/clang/Basic/AttrDocs.td
@@ -4537,6 +4537,16 @@
 }];
 }
 
+def NoUwtableDocs : Documentation {
+  let Category = DocCatFunction;
+  let Content = [{
+Clang supports the ``nouwtable`` attribute which skips emitting
+the unwind table entry for the specified function. This attribute is useful for
+selectively suppressing the unwind table entry on some functions when building
+with the ``-funwind-tables`` compiler option.
+}];
+}
+
 def InternalLinkageDocs : Documentation {
   let Category = DocCatFunction;
   let Content = [{
Index: clang/include/clang/Basic/Attr.td
===
--- clang/include/clang/Basic/Attr.td
+++ clang/include/clang/Basic/Attr.td
@@ -2086,6 +2086,13 @@
   let Documentation = [NoThrowDocs];
 }
 
+def NoUwtable : InheritableAttr {
+  let Spellings = [Clang<"nouwtable">];
+  let Subjects = SubjectList<[Function]>;
+  let Documentation = [NoUwtableDocs];
+  let SimpleHandler = 1;
+}
+
 def NvWeak : IgnoredAttr {
   // No Declspec spelling of this attribute; the CUDA headers use
   // __attribute__((nv_weak)) unconditionally. Does not receive an [[]]


Index: clang/test/Sema/attr-nouwtable.c
===
--- /dev/null
+++ clang/test/Sema/attr-nouwtable.c
@@ -0,0 +1,6 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+void *t1() __attribute__((nouwtable(1))); // expected-error {{'nouwtable' attribute takes no arguments}}
+
+typedef void (*F)(void);
+__attribute__((nouwtable)) F f; // expected-warning {{'nouwtable' attribute only applies to functions}}
Index: clang/test/Misc/pragma-attribute-supported-attributes-list.test
===
--- clang/test/Misc/pragma-attribute-supported-attributes-list.test
+++ clang/test/Misc/pragma-attribute-supported-attributes-list.test
@@ -114,6 +1

[PATCH] D132425: [clang] Do not instrument relative vtables under hwasan

2022-08-26 Thread Mitch Phillips via Phabricator via cfe-commits
hctim added a comment.

In D132425#3753065 , @leonardchan 
wrote:

> We have a generic long term solution for hwasan+RV which I think might also 
> be applicable for MTE+RV. For hwasan, since it's mainly the IR pass that 
> converts usages of the vtable (within the vtable itself) to use tagged 
> aliases, the ideal solution is to just have hwasan ignore these specific 
> references in the vtable such that offset calculation can continue to use the 
> untagged address allowing the relocation arithmetic to not overflow. Now for 
> llvm, I'm assuming it's an instrumentation pass like memtagsanitizer that 
> will ensure all references to globals go through the GOT by replacing all 
> global references with the appropriate IR that gets lowered to this GOT 
> reference. If this is the case, then I *think* a similar solution can be done 
> here where particular references to the vtable continue to use the original 
> vtable address and avoid instrumentation.

HWASan and MTE have a nice invariant that helps - functions aren't tagged 
(phew). IIUC, For HWASan, it seems like you could just use an `_NC` relocation 
and truncate off the tag bits when materializing a function pointer from the 
relative vtable. For MTE, taking the address of the vtable would be indirect 
(as it has to be grabbed from the GOT), and applying the offset would result in 
a tagged function pointer. Because code pages aren't mapped as `PROT_MTE`, 
seems like this would succeed (maybe unwinders would have to be taught to 
truncate any tag bits, but that seems about it).

Either way, I don't think we should worry about it right this instant, and any 
problems would be easily detected during experimentation.

Didn't actually realise this was submitted. Appreciate the follow-up patch for 
non-relative-vtables + hwasan :).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132425

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


[PATCH] D132739: [clang][Interp] Implement IntegralToBoolean casts

2022-08-26 Thread Shafik Yaghmour via Phabricator via cfe-commits
shafik added inline comments.



Comment at: clang/lib/AST/Interp/Boolean.h:90
+  template  static Boolean from(T Value) {
+if constexpr (std::is_integral::value)
+  return Boolean(Value != 0);

This should work for `floating_point` as well.



Comment at: clang/lib/AST/Interp/Boolean.h:91
+if constexpr (std::is_integral::value)
+  return Boolean(Value != 0);
+return Boolean(static_cast(Value) != 0);

Why the `!= 0` shouldn't these all implicitly convert to `bool` with 
appropriate values?


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

https://reviews.llvm.org/D132739

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


[PATCH] D132425: [clang] Do not instrument relative vtables under hwasan

2022-08-26 Thread Leonard Chan via Phabricator via cfe-commits
leonardchan added a comment.

In D132425#3752468 , @hctim wrote:

> Glad to see that refactoring the sanitizer metadata made someone's life 
> easier ;) (now allowing for disabling hwasanificiation of globals)
>
> Patch looks reasonable to me. Can you please add the negative test (that 
> vtables under the vanilla ABI still have hwasan)?

Yup. Will add a followup patch.

> I wans't fully aware of the relative vtables ABI, and it may have some 
> implications about MTE globals tagging (draft abi 
> ).
>  Because logical tags are synthesized at runtime into a synthetic GOT entry - 
> dynamic relocations I believe would be forced (removing any benefit of the 
> relative vtables ABI), so for now it seems like MTE globals and relative 
> vtables are mutually exclusive. Another option would be to disable MTE 
> globals for relative vtables as well. No action needed on your part, just 
> putting some wordso n paper that this might need some consideration at a 
> later date if Fuchsia wants to support MTE globals.

Thanks for bringing this up. For relative vtables, the important bit is that 
the vtable is populated with statically known offsets between the vtable and 
its virtual functions. The particular linker error this patch resolves occurs 
because the hwasan pass happens to replace references to the vtable (within the 
vtable) with the alias, so the tag causes an overflow when resolving the 
relocation.

Now if I'm understanding the draft correctly, the way MTE will work with 
globals is that all references to globals *must* go through the GOT because the 
dynamic linker will place the tagged address there, so the potential conflict 
with relative vtables is that we wouldn't know the full tagged address of the 
vtable at link time, hence the dynamic relocation. If so, simply disabling MTE 
on relative vtables would also be a short term solution.

We have a generic long term solution for hwasan+RV which I think might also be 
applicable for MTE+RV. For hwasan, since it's mainly the IR pass that converts 
usages of the vtable (within the vtable itself) to use tagged aliases, the 
ideal solution is to just have hwasan ignore these specific references in the 
vtable such that offset calculation can continue to use the untagged address 
allowing the relocation arithmetic to not overflow. Now for llvm, I'm assuming 
it's an instrumentation pass like memtagsanitizer that will ensure all 
references to globals go through the GOT by replacing all global references 
with the appropriate IR that gets lowered to this GOT reference. If this is the 
case, then I *think* a similar solution can be done here where particular 
references to the vtable continue to use the original vtable address and avoid 
instrumentation.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132425

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


[PATCH] D132756: [clang][dataflow] Refactor `TypeErasedDataflowAnalysisTest` - replace usage of the deprecated overload of `checkDataflow`.

2022-08-26 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr2 accepted this revision.
gribozavr2 added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/unittests/Analysis/FlowSensitive/TestingSupport.h:68
+const Environment &getEnvironmentAtAnnotation(
+llvm::StringMap> &AnnotationStates,
+llvm::StringRef Annotation) {





Comment at: 
clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp:132
 struct FunctionCallLattice {
-  llvm::SmallSet CalledFunctions;
+  typedef llvm::SmallSet FunctionSet;
+  FunctionSet CalledFunctions;




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132756

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


[PATCH] D132186: Clang: Add a new flag Wmisnoinline for printing hot noinline functions

2022-08-26 Thread Paul Kirth via Phabricator via cfe-commits
paulkirth added a comment.

In D132186#3752403 , @modimo wrote:

> Same. The instances I've seen is an older codebase where compiler 
> optimizations were not as powerful and/or purposefully written by engineers 
> that didn't trust the compiler to do the right thing.

Thanks for pointing that out. I had failed to consider those scenarios. I do 
recall having discussions w/ hardware/embedded engineers a long time ago 
regarding their mistrust of the compiler, so I should have thought about these 
types of situations.

> Currently a new ORE (`-pass-remarks=misnoinline`) is getting generated, which 
> misnoexcept also does. Agreed a warning is more familiar and friendlier for 
> users so I lean towards that approach. For additional tooling, I think the 
> first step will be to trial this on more real programs to see what cases are 
> interesting. @iamarchit123 just finished his internship with us so I'll be 
> evaluating these changes on HHVM to see if they can swing the performance 
> needle.

@iamarchit123, thanks for your contribution, and I hope your summer went well!  
You may want to see if you can present your work at the dev meeting in 
November.  Even a lighting talk is a great item for a resume. There's even a 
student travel grant to help out w/ costs. 
https://discourse.llvm.org/t/llvm-foundation-student-travel-grants-available-sept-8-deadline/64794.
 Also, universities often have their own travel grants for students presenting 
at a conference, so I would encourage you to see if you're eligible for one of 
those from your own university too.

@modimo Keep us posted w/ your findings from HHVM, it will be interesting to 
see what kind of improvements can be gained.




Comment at: llvm/docs/MisNoInline.rst:2
+===
+Misnoexpect
+===





Comment at: llvm/docs/MisNoInline.rst:9-39
+When developers use noinline attribute with a function, i.e., through use of
+``__attribute__((noinline))``, they are trying to communicate that the
+function should not be inlined by the compiler. These can be due to various
+number of reasons to mark a function noinline. If a function is small,
+not critical to the performance of your code and would be called less often,
+especially in cases of error handling, it makes sense to noinline a function.
+These annotations, however, can be incorrect for a variety of reasons:

This is almost a verbatim copy of the MisExpect.rst. If these diagnostics are 
so similar, and use the exact same methodology, then maybe we should unify them 
as something like `Profile-based Mis-annotation Analysis`? We can describe the 
basic approach and then in subsections describe how individual diagnostics 
work/differ. What do you think?



Comment at: llvm/include/llvm/Analysis/InlineCost.h:174
   const char *Message = nullptr;
+  bool IsNoInline = false;
   InlineResult(const char *Message = nullptr) : Message(Message) {}

Do you need this variable? you store it here in the InlineCost, but the only 
place its used is in `canEmitNoInlineWarning`. Seems easier to just check for 
`Attribute::NoInline` on the `Callee` variable directly in 
`canEmitNoInlineWarning`, and avoid plumbing all this data around.



Comment at: llvm/lib/Analysis/InlineAdvisor.cpp:69-71
+cl::desc("Use this option to turn on/off "
+ "warnings about usage of noinline function attribute "
+ "which may hurt performance."));

the verbage here makes `noinline` sound like its always bad/wrong. Maybe "... 
noinlne function attribute on hot functions, which may degrade performance"?



Comment at: llvm/lib/Analysis/InlineAdvisor.cpp:148-150
+  Function &Callee = *CB->getCalledFunction();
+  LLVMContext &Ctx = Callee.getContext();
+  const char *reason = IC.getReason();

nit: Maybe sink these until they're needed?



Comment at: llvm/lib/Analysis/InlineAdvisor.cpp:163
+return false;
+  if (!IC.isNoInline())
+return false;

why not check for `NoInline` on either `CB` or `Callee` directly?



Comment at: llvm/lib/Analysis/InlineAdvisor.cpp:166-169
+  if (MisNoInlinePercent)
+Percent_Threshold = MisNoInlinePercent;
+  else
+Percent_Threshold = Ctx.getDiagnosticsMisNoInlinePercentileThreshold();

Seems like a helper function would make this a little cleaner/ergonomic.



Comment at: llvm/lib/Analysis/InlineAdvisor.cpp:233-242
+if (LLVM_UNLIKELY(canEmitNoInlineWarning(&CB, IC, FAM))) {
+  Function &Callee = *CB.getCalledFunction();
+  auto &CalleeTTI = FAM.getResult(Callee);
+  auto TempIC = llvm::isInlineViableFromCostAnalysis(
+  CB, &Callee, Params, CalleeTTI, GetAssumptionCache, GetTLI, GetBFI,
+  PSI);
+

Can we separate this out into i

[clang] dc32ed8 - [Clang][Driver] Refine/refactor DriverKit support

2022-08-26 Thread Julian Lettner via cfe-commits

Author: Julian Lettner
Date: 2022-08-26T16:06:24-07:00
New Revision: dc32ed8a8e226db3677abb19eda62cfe80572aed

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

LOG: [Clang][Driver] Refine/refactor DriverKit support

Add special Framework header search path for DriverKit.

Added: 

clang/test/Driver/Inputs/DriverKit19.0.sdk/System/DriverKit/System/Library/Frameworks/.keep
clang/test/Driver/Inputs/DriverKit19.0.sdk/System/DriverKit/usr/lib/.keep

clang/test/Driver/Inputs/DriverKit19.0.sdk/System/DriverKit/usr/local/include/.keep
clang/test/Driver/driverkit-path.c

Modified: 
clang/include/clang/Driver/ToolChain.h
clang/lib/Driver/ToolChains/Darwin.cpp
clang/lib/Driver/ToolChains/Darwin.h
clang/lib/Lex/InitHeaderSearch.cpp

Removed: 




diff  --git a/clang/include/clang/Driver/ToolChain.h 
b/clang/include/clang/Driver/ToolChain.h
index f444cf5cbb109..59d8dafc079f0 100644
--- a/clang/include/clang/Driver/ToolChain.h
+++ b/clang/include/clang/Driver/ToolChain.h
@@ -258,6 +258,10 @@ class ToolChain {
 return EffectiveTriple;
   }
 
+  bool hasEffectiveTriple() const {
+return !EffectiveTriple.getTriple().empty();
+  }
+
   path_list &getLibraryPaths() { return LibraryPaths; }
   const path_list &getLibraryPaths() const { return LibraryPaths; }
 

diff  --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index 4482a55a05019..b060a6af6145b 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -522,6 +522,8 @@ static void renderRemarksOptions(const ArgList &Args, 
ArgStringList &CmdArgs,
   }
 }
 
+static void AppendPlatformPrefix(SmallString<128> &Path, const llvm::Triple 
&T);
+
 void darwin::Linker::ConstructJob(Compilation &C, const JobAction &JA,
   const InputInfo &Output,
   const InputInfoList &Inputs,
@@ -719,22 +721,31 @@ void darwin::Linker::ConstructJob(Compilation &C, const 
JobAction &JA,
 }
   }
 
-  // DriverKit's framework doesn't have the same layout as other frameworks.
-  // Add missing search paths if necessary.
-  if (getToolChain().getTriple().getOS() == llvm::Triple::DriverKit) {
-if (const Arg *Root = Args.getLastArg(options::OPT_isysroot)) {
+  // Add non-standard, platform-specific search paths, e.g., for DriverKit:
+  //  -L/System/DriverKit/usr/lib
+  //  -F/System/DriverKit/System/Library/Framework
+  {
+bool NonStandardSearchPath = false;
+const auto &Triple = getToolChain().getTriple();
+if (Triple.isDriverKit()) {
   // ld64 fixed the implicit -F and -L paths in ld64-605.1+.
-  if (Version.getMajor() < 605 ||
-  (Version.getMajor() == 605 && Version.getMinor().value_or(0) < 1)) {
-
-SmallString<128> L(Root->getValue());
-llvm::sys::path::append(L, "System", "DriverKit", "usr", "lib");
-CmdArgs.push_back(Args.MakeArgString(std::string("-L") + L));
+  NonStandardSearchPath =
+  Version.getMajor() < 605 ||
+  (Version.getMajor() == 605 && Version.getMinor().value_or(0) < 1);
+}
 
-SmallString<128> F(Root->getValue());
-llvm::sys::path::append(F, "System", "DriverKit");
-llvm::sys::path::append(F, "System", "Library", "Frameworks");
-CmdArgs.push_back(Args.MakeArgString(std::string("-F") + F));
+if (NonStandardSearchPath) {
+  if (auto *Sysroot = Args.getLastArg(options::OPT_isysroot)) {
+auto AddSearchPath = [&](StringRef Flag, StringRef SearchPath) {
+  SmallString<128> P(Sysroot->getValue());
+  AppendPlatformPrefix(P, Triple);
+  llvm::sys::path::append(P, SearchPath);
+  if (getToolChain().getVFS().exists(P)) {
+CmdArgs.push_back(Args.MakeArgString(Flag + P));
+  }
+};
+AddSearchPath("-L", "/usr/lib");
+AddSearchPath("-F", "/System/Library/Frameworks");
   }
 }
   }
@@ -2265,21 +2276,37 @@ void Darwin::AddDeploymentTarget(DerivedArgList &Args) 
const {
   }
 }
 
-// Returns the effective header sysroot path to use. This comes either from
-// -isysroot or --sysroot.
-llvm::StringRef DarwinClang::GetHeaderSysroot(const llvm::opt::ArgList 
&DriverArgs) const {
-  if(DriverArgs.hasArg(options::OPT_isysroot))
-return DriverArgs.getLastArgValue(options::OPT_isysroot);
-  if (!getDriver().SysRoot.empty())
-return getDriver().SysRoot;
-  return "/";
+// For certain platforms/environments almost all resources (e.g., headers) are
+// located in sub-directories, e.g., for DriverKit they live in
+// /System/DriverKit/usr/include (instead of /usr/include).
+static void AppendPlatformPrefix(SmallString<128> &Path,
+ const llvm::Triple &T) 

[PATCH] D131614: [clang][dataflow] Extend transfer functions for other `CFGElement`s

2022-08-26 Thread weiyi via Phabricator via cfe-commits
wyt updated this revision to Diff 456049.
wyt added a comment.

Mark override for virtual transfer function.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131614

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
  
clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
  clang/include/clang/Analysis/FlowSensitive/NoopAnalysis.h
  clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h
  clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
  clang/unittests/Analysis/FlowSensitive/ChromiumCheckModelTest.cpp
  clang/unittests/Analysis/FlowSensitive/MatchSwitchTest.cpp
  clang/unittests/Analysis/FlowSensitive/MultiVarConstantPropagationTest.cpp
  clang/unittests/Analysis/FlowSensitive/SingleVarConstantPropagationTest.cpp
  clang/unittests/Analysis/FlowSensitive/TestingSupport.h
  clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
@@ -111,7 +111,8 @@
 
   static NonConvergingLattice initialElement() { return {0}; }
 
-  void transfer(const Stmt *S, NonConvergingLattice &E, Environment &Env) {
+  void transfer(const Stmt *S, NonConvergingLattice &E,
+Environment &Env) override {
 ++E.State;
   }
 };
@@ -161,7 +162,8 @@
 
   static FunctionCallLattice initialElement() { return {}; }
 
-  void transfer(const Stmt *S, FunctionCallLattice &E, Environment &Env) {
+  void transfer(const Stmt *S, FunctionCallLattice &E,
+Environment &Env) override {
 if (auto *C = dyn_cast(S)) {
   if (auto *F = dyn_cast(C->getCalleeDecl())) {
 E.CalledFunctions.insert(F->getNameInfo().getAsString());
@@ -305,7 +307,7 @@
 
   static NoopLattice initialElement() { return {}; }
 
-  void transfer(const Stmt *S, NoopLattice &, Environment &Env) {
+  void transfer(const Stmt *S, NoopLattice &, Environment &Env) override {
 auto SpecialBoolRecordDecl = recordDecl(hasName("SpecialBool"));
 auto HasSpecialBoolType = hasType(SpecialBoolRecordDecl);
 
@@ -457,7 +459,7 @@
 
   static NoopLattice initialElement() { return {}; }
 
-  void transfer(const Stmt *S, NoopLattice &, Environment &Env) {
+  void transfer(const Stmt *S, NoopLattice &, Environment &Env) override {
 auto OptionalIntRecordDecl = recordDecl(hasName("OptionalInt"));
 auto HasOptionalIntType = hasType(OptionalIntRecordDecl);
 
Index: clang/unittests/Analysis/FlowSensitive/TestingSupport.h
===
--- clang/unittests/Analysis/FlowSensitive/TestingSupport.h
+++ clang/unittests/Analysis/FlowSensitive/TestingSupport.h
@@ -71,14 +71,25 @@
   std::vector> &BlockStates;
 };
 
+// FIXME: Rename to `checkDataflow` after usages of the overload that applies to
+// `CFGStmt` have been replaced.
+//
+/// Runs dataflow analysis (specified from `MakeAnalysis`) and the
+/// `PostVisitCFG` function (if provided) on the body of the function that
+/// matches `TargetFuncMatcher` in code snippet `Code`. `VerifyResults` checks
+/// that the results from the analysis are correct.
+///
+/// Requirements:
+///
+///  `AnalysisT` contains a type `Lattice`.
 template 
-llvm::Error checkDataflow(
+llvm::Error checkDataflowOnCFG(
 llvm::StringRef Code,
 ast_matchers::internal::Matcher TargetFuncMatcher,
 std::function MakeAnalysis,
-std::function
-PostVisitStmt,
+PostVisitCFG,
 std::function VerifyResults, ArrayRef Args,
 const tooling::FileContentMappings &VirtualMappedFiles = {}) {
   llvm::Annotations AnnotatedCode(Code);
@@ -112,13 +123,14 @@
   Environment Env(DACtx, *F);
   auto Analysis = MakeAnalysis(Context, Env);
 
-  std::function
-  PostVisitStmtClosure = nullptr;
-  if (PostVisitStmt != nullptr) {
-PostVisitStmtClosure = [&PostVisitStmt, &Context](
-   const CFGStmt &Stmt,
-   const TypeErasedDataflowAnalysisState &State) {
-  PostVisitStmt(Context, Stmt, State);
+  std::function
+  PostVisitCFGClosure = nullptr;
+  if (PostVisitCFG) {
+PostVisitCFGClosure = [&PostVisitCFG, &Context](
+  const CFGElement &Element,
+  const TypeErasedDataflowAnalysisState &State) {
+  PostVisitCFG(Context, Element, State);
 };
   }
 
@@ -130,7 +142,7 @@
 
   llvm::Expected>>
   MaybeBlockStates = runTypeErasedDataflowAnalysis(*CFCtx, Analysis, Env,
-   PostVisitStmtClosure);
+   PostVisitCFGClosure);
   if (!MaybeBlockSta

[PATCH] D132763: [clang][dataflow] Use `StringMap` for storing analysis states at annotated points instead of `vector>`.

2022-08-26 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr2 accepted this revision.
gribozavr2 added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/unittests/Analysis/FlowSensitive/TestingSupport.cpp:124
+  }
+  Result[Stmt] = Annotation;
+





Comment at: clang/unittests/Analysis/FlowSensitive/TestingSupport.h:262
 std::function>>,
+llvm::StringMap> &,
 AnalysisOutputs &)>





Comment at: clang/unittests/Analysis/FlowSensitive/TestingSupport.h:300
 llvm::any_cast(&State.Lattice.Value);
-AnnotationStates.emplace_back(It->second, StateT{*Lattice, State.Env});
+AnnotationStates.insert({It->second, StateT{*Lattice, State.Env}});
   };

Could you add an assert that insert reported that it indeed inserted an element 
(didn't overwrite)?



Comment at: clang/unittests/Analysis/FlowSensitive/TestingSupport.h:356-357
+AnnotationStatesAsVector;
+for (auto It = AnnotationStates.begin(); It != AnnotationStates.end();
+ It++) {
+  AnnotationStatesAsVector.push_back(

Would a range-based for loop work?

`for (const auto &P : AnnotationStates)`



Comment at: clang/unittests/Analysis/FlowSensitive/TestingSupport.h:358-361
+  AnnotationStatesAsVector.push_back(
+  std::pair>(
+  It->first(), std::move(It->second)));

Would make_pair work? It allows to omit explicit template arguments.



Comment at: clang/unittests/Analysis/FlowSensitive/TestingSupport.h:363-365
+std::sort(AnnotationStatesAsVector.begin(),
+  AnnotationStatesAsVector.end(),
+  [](auto a, auto b) { return a.first < b.first; });

Please use llvm::sort. You also don't need to specify the comparator, the 
default comparator for strings is exactly the same.




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132763

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


[PATCH] D132421: [HLSL] Support PCH for cc1 mode

2022-08-26 Thread Xiang Li via Phabricator via cfe-commits
python3kgae updated this revision to Diff 456046.
python3kgae added a comment.

Fix build error


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132421

Files:
  clang/include/clang/Sema/HLSLExternalSemaSource.h
  clang/lib/Frontend/FrontendAction.cpp
  clang/lib/Sema/HLSLExternalSemaSource.cpp
  clang/test/AST/HLSL/Inputs/pch.hlsl
  clang/test/AST/HLSL/pch.hlsl

Index: clang/test/AST/HLSL/pch.hlsl
===
--- /dev/null
+++ clang/test/AST/HLSL/pch.hlsl
@@ -0,0 +1,17 @@
+// RUN: %clang_cc1 -triple dxil-pc-shadermodel6.3-library -x hlsl \
+// RUN:  -finclude-default-header -emit-pch -o %t %S/Inputs/pch.hlsl
+// RUN: %clang_cc1 -triple dxil-pc-shadermodel6.3-library -x hlsl \
+// RUN:  -finclude-default-header -include-pch %t -fsyntax-only -ast-dump-all %s \
+// RUN: | FileCheck  %s
+
+// Make sure PCH works by using function declared in PCH header and declare a RWBuffer in current file.
+// CHECK:FunctionDecl 0x[[FOO:[0-9a-f]+]] <{{.*}}:2:1, line:4:1> line:2:8 imported used foo 'float2 (float2, float2)'
+// CHECK:VarDecl 0x{{[0-9a-f]+}} <{{.*}}:10:1, col:23> col:23 Buffer 'hlsl::RWBuffer':'hlsl::RWBuffer<>'
+hlsl::RWBuffer Buffer;
+
+float2 bar(float2 a, float2 b) {
+// CHECK:CallExpr 0x{{[0-9a-f]+}}  'float2':'float __attribute__((ext_vector_type(2)))'
+// CHECK-NEXT:ImplicitCastExpr 0x{{[0-9a-f]+}}  'float2 (*)(float2, float2)' 
+// CHECK-NEXT:`-DeclRefExpr 0x{{[0-9a-f]+}}  'float2 (float2, float2)' lvalue Function 0x[[FOO]] 'foo' 'float2 (float2, float2)'
+  return foo(a, b);
+}
Index: clang/test/AST/HLSL/Inputs/pch.hlsl
===
--- /dev/null
+++ clang/test/AST/HLSL/Inputs/pch.hlsl
@@ -0,0 +1,4 @@
+
+float2 foo(float2 a, float2 b) {
+  return a + b;
+}
Index: clang/lib/Sema/HLSLExternalSemaSource.cpp
===
--- clang/lib/Sema/HLSLExternalSemaSource.cpp
+++ clang/lib/Sema/HLSLExternalSemaSource.cpp
@@ -250,9 +250,51 @@
 
 HLSLExternalSemaSource::~HLSLExternalSemaSource() {}
 
+static NamedDecl *findDecl(ASTContext &AST, Sema &S, StringRef Name,
+  Sema::LookupNameKind Kind) {
+  IdentifierInfo &II = AST.Idents.get(Name, tok::TokenKind::identifier);
+  DeclarationNameInfo NameInfo{DeclarationName{&II}, SourceLocation()};
+  LookupResult R(S, NameInfo, Kind);
+  S.LookupName(R, S.getCurScope());
+  NamedDecl *D = nullptr;
+  if (!R.isAmbiguous() && !R.empty())
+D = R.getRepresentativeDecl();
+  return D;
+}
+
 void HLSLExternalSemaSource::InitializeSema(Sema &S) {
   SemaPtr = &S;
   ASTContext &AST = SemaPtr->getASTContext();
+
+  if (ExternalSema) {
+NamespaceDecl *ExternlHLSL = llvm::dyn_cast_if_present(
+findDecl(AST, S, "hlsl", Sema::LookupNameKind::LookupNamespaceName));
+// Try to initailize from ExternalSema.
+if (ExternlHLSL) {
+  auto *Resource = llvm::dyn_cast_if_present(
+  findDecl(AST, S, "Resource", Sema::LookupNameKind::LookupOrdinaryName));
+
+  auto *RWBuffer = llvm::dyn_cast_if_present(
+  findDecl(AST, S, "RWBuffer", Sema::LookupNameKind::LookupAnyName));
+  
+  // Find all things from ExternalSema, use them and return.
+  if (Resource && RWBuffer) {
+HLSLNamespace = ExternlHLSL;
+ResourceDecl = Resource;
+CXXRecordDecl *Decl = RWBuffer->getTemplatedDecl();
+if (!Decl->hasDefinition()) {
+  // Mark ExternalLexicalStorage so complete type will be called for
+  // ExternalAST path.
+  Decl->setHasExternalLexicalStorage();
+  Completions.insert(std::make_pair(
+  Decl, std::bind(&HLSLExternalSemaSource::completeBufferType, this,
+  std::placeholders::_1)));
+}
+return;
+  }
+}
+  }
+
   IdentifierInfo &HLSL = AST.Idents.get("hlsl", tok::TokenKind::identifier);
   HLSLNamespace =
   NamespaceDecl::Create(AST, AST.getTranslationUnitDecl(), false,
Index: clang/lib/Frontend/FrontendAction.cpp
===
--- clang/lib/Frontend/FrontendAction.cpp
+++ clang/lib/Frontend/FrontendAction.cpp
@@ -1018,9 +1018,16 @@
 
   // Setup HLSL External Sema Source
   if (CI.getLangOpts().HLSL && CI.hasASTContext()) {
-IntrusiveRefCntPtr HLSLSema(
-new HLSLExternalSemaSource());
-CI.getASTContext().setExternalSource(HLSLSema);
+if (auto *SemaSource = dyn_cast_if_present(
+CI.getASTContext().getExternalSource())) {
+  IntrusiveRefCntPtr HLSLSema(
+  new ChainedHLSLExternalSemaSource(SemaSource));
+  CI.getASTContext().setExternalSource(HLSLSema);
+} else {
+  IntrusiveRefCntPtr HLSLSema(
+  new HLSLExternalSemaSource());
+  CI.getASTContext().setExternalSource(HLSLSema);
+}
   }
 
   FailureCleanup.release();
Index: cl

[PATCH] D132147: [clang][dataflow] Refactor `TestingSupport.h`

2022-08-26 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr2 added inline comments.



Comment at: clang/unittests/Analysis/FlowSensitive/TestingSupport.h:117
+llvm::DenseMap
+getAnnotationLinesAndContent(AnalysisOutputs &AO);
+

(if possible)



Comment at: clang/unittests/Analysis/FlowSensitive/TestingSupport.h:125
+std::pair>>>
+getAnnotationStates(AnalysisOutputs &AO) {
+  using StateT = DataflowAnalysisState;

(if possible)



Comment at: clang/unittests/Analysis/FlowSensitive/TestingSupport.h:179
+checkDataflow(AnalysisInputs AI,
+  std::function VerifyResults) {
+  // Build AST context from code.





Comment at: clang/unittests/Analysis/FlowSensitive/TestingSupport.h:258-259
+checkDataflow(AnalysisInputs AI,
+  std::function &,
+ AnalysisOutputs &)>
+  VerifyResults) {





Comment at: clang/unittests/Analysis/FlowSensitive/TestingSupport.h:293
+std::string, DataflowAnalysisState>>,
+AnalysisOutputs &)>
+VerifyResults) {




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132147

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


[clang] fb9c1b8 - Revert "[clang][dataflow] Extend transfer functions for other `CFGElement`s"

2022-08-26 Thread Wei Yi Tee via cfe-commits

Author: Wei Yi Tee
Date: 2022-08-26T22:41:20Z
New Revision: fb9c1b8938fdc37705aa2e71688c4a061cfb2cd5

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

LOG: Revert "[clang][dataflow] Extend transfer functions for other 
`CFGElement`s"

This reverts commit 4b815eb4fde0202434c6395973578349767b3f15.

Added: 


Modified: 
clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h
clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
clang/unittests/Analysis/FlowSensitive/TestingSupport.h

Removed: 




diff  --git a/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
index 4849841d2d8fb..4d1f5248f2115 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
@@ -93,29 +93,10 @@ class DataflowAnalysis : public TypeErasedDataflowAnalysis {
 return L1 == L2;
   }
 
-  /// Deprecated. Use the `transfer` function overload applied on `CFGElement`.
-  ///
-  /// Transfer function for statements in the code being analysed.
-  virtual void transfer(const Stmt *Stmt, Lattice &L, Environment &Env) {}
-
-  /// Transfer function for elements in the control flow graph built from the
-  /// code being analysed.
-  virtual void transfer(const CFGElement *Element, Lattice &L,
-Environment &Env) {}
-
-  // FIXME: Use CRTP pattern and remove virtual transfer functions after users
-  // have been updated to implement transfer.
-  // (e.g. static_cast(this)->transfer(Element, L, Env))
-  void transferTypeErased(const CFGElement *Element, TypeErasedLattice &E,
+  void transferTypeErased(const Stmt *Stmt, TypeErasedLattice &E,
   Environment &Env) final {
 Lattice &L = llvm::any_cast(E.Value);
-transfer(Element, L, Env);
-
-// FIXME: Remove after users have been updated to implement the `transfer`
-// overload applied on `CFGElement`.
-if (auto Stmt = Element->getAs()) {
-  transfer(Stmt->getStmt(), L, Env);
-}
+static_cast(this)->transfer(Stmt, L, Env);
   }
 
 private:
@@ -131,41 +112,37 @@ template  struct DataflowAnalysisState 
{
   Environment Env;
 };
 
-// FIXME: Rename to `runDataflowAnalysis` after usages of the overload that
-// applies to `CFGStmt` have been replaced.
-//
 /// Performs dataflow analysis and returns a mapping from basic block IDs to
 /// dataflow analysis states that model the respective basic blocks. The
 /// returned vector, if any, will have the same size as the number of CFG
 /// blocks, with indices corresponding to basic block IDs. Returns an error if
 /// the dataflow analysis cannot be performed successfully. Otherwise, calls
-/// `PostVisitCFG` on each CFG element with the final analysis results at that
+/// `PostVisitStmt` on each statement with the final analysis results at that
 /// program point.
 template 
 llvm::Expected>>>
-runDataflowAnalysisOnCFG(
+runDataflowAnalysis(
 const ControlFlowContext &CFCtx, AnalysisT &Analysis,
 const Environment &InitEnv,
-std::function &)>
-PostVisitCFG = nullptr) {
-  std::function
-  PostVisitCFGClosure = nullptr;
-  if (PostVisitCFG) {
-PostVisitCFGClosure = [&PostVisitCFG](
-  const CFGElement &Element,
-  const TypeErasedDataflowAnalysisState &State) {
+std::function &)>
+PostVisitStmt = nullptr) {
+  std::function
+  PostVisitStmtClosure = nullptr;
+  if (PostVisitStmt != nullptr) {
+PostVisitStmtClosure = [&PostVisitStmt](
+   const CFGStmt &Stmt,
+   const TypeErasedDataflowAnalysisState &State) {
   auto *Lattice =
   llvm::any_cast(&State.Lattice.Value);
-  PostVisitCFG(Element, DataflowAnalysisState{
-*Lattice, State.Env});
+  PostVisitStmt(Stmt, DataflowAnalysisState{
+  *Lattice, State.Env});
 };
   }
 
   auto TypeErasedBlockStates = runTypeErasedDataflowAnalysis(
-  CFCtx, Analysis, InitEnv, PostVisitCFGClosure);
+  CFCtx, Analysis, InitEnv, PostVisitStmtClosure);
   if (!TypeErasedBlockStates)
 return TypeErasedBlockStates.takeError();
 
@@ -186,41 +163,6 @@ runDataflowAnalysisOnCFG(
   return BlockStates;
 }
 
-/// Deprecated. Use `runDataflowAnalysisOnCFG` instead.
-///
-/// Performs dataflow analysis and returns a mapping from basic block IDs to
-/// dataflow analysis states that model the respective basic blocks. The
-/// returned vector, if any, will have the same size as the number of CFG
-/// blocks, with indices correspon

[PATCH] D131614: [clang][dataflow] Extend transfer functions for other `CFGElement`s

2022-08-26 Thread weiyi via Phabricator via cfe-commits
wyt added a comment.

@thakis 
Thanks for pointing that out, will revert and recommit - since it also ran into 
some build failures.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131614

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


[PATCH] D131614: [clang][dataflow] Extend transfer functions for other `CFGElement`s

2022-08-26 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

I don't know how you commited this, but the commit message is missing all the 
(great!) details that are here on the review. See here: 
https://github.com/llvm/llvm-project/commit/4b815eb4fde0202434c6 or here: 
https://reviews.llvm.org/rG4b815eb4fde0202434c63

Please update your commit workflow so that the description on phab makes it 
into the commit going forward :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131614

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


[clang] e877b42 - [clang] Better warning-fix follow-up to D131632

2022-08-26 Thread Nico Weber via cfe-commits

Author: Nico Weber
Date: 2022-08-26T18:29:20-04:00
New Revision: e877b42e2c70813352c1963ea33e992f481d5cba

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

LOG: [clang] Better warning-fix follow-up to D131632

Not all host compilers understand gnu:: attributes. Just remove the
variable until it's used.

Added: 


Modified: 
clang/lib/Frontend/SARIFDiagnostic.cpp

Removed: 




diff  --git a/clang/lib/Frontend/SARIFDiagnostic.cpp 
b/clang/lib/Frontend/SARIFDiagnostic.cpp
index f0f32a179825..416e9132afaf 100644
--- a/clang/lib/Frontend/SARIFDiagnostic.cpp
+++ b/clang/lib/Frontend/SARIFDiagnostic.cpp
@@ -71,8 +71,7 @@ SarifResult SARIFDiagnostic::addLocationToResult(
 FileID FID = Loc.getFileID();
 if (FID.isValid()) {
   if (const FileEntry *FE = Loc.getFileEntry()) {
-[[gnu::unused]] llvm::StringRef Filename =
-emitFilename(FE->getName(), Loc.getManager());
+emitFilename(FE->getName(), Loc.getManager());
 // FIXME(llvm-project/issues/57366): File-only locations
   }
 }



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


[PATCH] D132745: [clang] Fix ambiguous use of `report_fatal_error`.

2022-08-26 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr2 accepted this revision.
gribozavr2 added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/lib/Basic/SanitizerSpecialCaseList.cpp:36
 return SSCL;
-  llvm::report_fatal_error(Error);
+  llvm::report_fatal_error(llvm::StringRef(Error));
 }

Please omit 'llvm::' on StringRef if it works like that (it should).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132745

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


[PATCH] D131614: [clang][dataflow] Extend transfer functions for other `CFGElement`s

2022-08-26 Thread weiyi via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG4b815eb4fde0: [clang][dataflow] Extend transfer functions 
for other `CFGElement`s (authored by wyt).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131614

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
  clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h
  clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
  clang/unittests/Analysis/FlowSensitive/TestingSupport.h

Index: clang/unittests/Analysis/FlowSensitive/TestingSupport.h
===
--- clang/unittests/Analysis/FlowSensitive/TestingSupport.h
+++ clang/unittests/Analysis/FlowSensitive/TestingSupport.h
@@ -71,14 +71,25 @@
   std::vector> &BlockStates;
 };
 
+// FIXME: Rename to `checkDataflow` after usages of the overload that applies to
+// `CFGStmt` have been replaced.
+//
+/// Runs dataflow analysis (specified from `MakeAnalysis`) and the
+/// `PostVisitCFG` function (if provided) on the body of the function that
+/// matches `TargetFuncMatcher` in code snippet `Code`. `VerifyResults` checks
+/// that the results from the analysis are correct.
+///
+/// Requirements:
+///
+///  `AnalysisT` contains a type `Lattice`.
 template 
-llvm::Error checkDataflow(
+llvm::Error checkDataflowOnCFG(
 llvm::StringRef Code,
 ast_matchers::internal::Matcher TargetFuncMatcher,
 std::function MakeAnalysis,
-std::function
-PostVisitStmt,
+PostVisitCFG,
 std::function VerifyResults, ArrayRef Args,
 const tooling::FileContentMappings &VirtualMappedFiles = {}) {
   llvm::Annotations AnnotatedCode(Code);
@@ -112,13 +123,14 @@
   Environment Env(DACtx, *F);
   auto Analysis = MakeAnalysis(Context, Env);
 
-  std::function
-  PostVisitStmtClosure = nullptr;
-  if (PostVisitStmt != nullptr) {
-PostVisitStmtClosure = [&PostVisitStmt, &Context](
-   const CFGStmt &Stmt,
-   const TypeErasedDataflowAnalysisState &State) {
-  PostVisitStmt(Context, Stmt, State);
+  std::function
+  PostVisitCFGClosure = nullptr;
+  if (PostVisitCFG) {
+PostVisitCFGClosure = [&PostVisitCFG, &Context](
+  const CFGElement &Element,
+  const TypeErasedDataflowAnalysisState &State) {
+  PostVisitCFG(Context, Element, State);
 };
   }
 
@@ -130,7 +142,7 @@
 
   llvm::Expected>>
   MaybeBlockStates = runTypeErasedDataflowAnalysis(*CFCtx, Analysis, Env,
-   PostVisitStmtClosure);
+   PostVisitCFGClosure);
   if (!MaybeBlockStates)
 return MaybeBlockStates.takeError();
   auto &BlockStates = *MaybeBlockStates;
@@ -141,6 +153,32 @@
   return llvm::Error::success();
 }
 
+template 
+llvm::Error checkDataflow(
+llvm::StringRef Code,
+ast_matchers::internal::Matcher TargetFuncMatcher,
+std::function MakeAnalysis,
+std::function
+PostVisitStmt,
+std::function VerifyResults, ArrayRef Args,
+const tooling::FileContentMappings &VirtualMappedFiles = {}) {
+  std::function
+  PostVisitCFG = nullptr;
+  if (PostVisitStmt) {
+PostVisitCFG =
+[&PostVisitStmt](ASTContext &Context, const CFGElement &Element,
+ const TypeErasedDataflowAnalysisState &State) {
+  if (auto Stmt = Element.getAs()) {
+PostVisitStmt(Context, *Stmt, State);
+  }
+};
+  }
+  return checkDataflowOnCFG(Code, TargetFuncMatcher, MakeAnalysis, PostVisitCFG,
+VerifyResults, Args, VirtualMappedFiles);
+}
+
 // Runs dataflow on the body of the function that matches `TargetFuncMatcher` in
 // code snippet `Code`. Requires: `AnalysisT` contains a type `Lattice`.
 template 
@@ -157,9 +195,9 @@
 const tooling::FileContentMappings &VirtualMappedFiles = {}) {
   using StateT = DataflowAnalysisState;
 
-  return checkDataflow(
+  return checkDataflowOnCFG(
   Code, std::move(TargetFuncMatcher), std::move(MakeAnalysis),
-  /*PostVisitStmt=*/nullptr,
+  /*PostVisitCFG=*/nullptr,
   [&VerifyResults](AnalysisData AnalysisData) {
 if (AnalysisData.BlockStates.empty()) {
   VerifyResults({}, AnalysisData.ASTCtx);
@@ -180,9 +218,13 @@
   AnalysisData.CFCtx, AnalysisData.BlockStates, *Block,
   AnalysisData.Env, AnalysisData.Analysis,
   [&Results,
-   &Annotations](const clang::CFGStmt &Stmt,
+   &Annotations](const clang::CFGElement &Element,
  const TypeErasedDataflowAnalysisState &State) {
-auto It = Annotations.find(Stmt.getStmt());
+// FIXME: Extend testing annotations to non statement constructs
+ 

[clang] 4b815eb - [clang][dataflow] Extend transfer functions for other `CFGElement`s

2022-08-26 Thread Wei Yi Tee via cfe-commits

Author: Wei Yi Tee
Date: 2022-08-26T22:21:29Z
New Revision: 4b815eb4fde0202434c6395973578349767b3f15

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

LOG: [clang][dataflow] Extend transfer functions for other `CFGElement`s

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

Added: 


Modified: 
clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h
clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
clang/unittests/Analysis/FlowSensitive/TestingSupport.h

Removed: 




diff  --git a/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
index 4d1f5248f2115..4849841d2d8fb 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
@@ -93,10 +93,29 @@ class DataflowAnalysis : public TypeErasedDataflowAnalysis {
 return L1 == L2;
   }
 
-  void transferTypeErased(const Stmt *Stmt, TypeErasedLattice &E,
+  /// Deprecated. Use the `transfer` function overload applied on `CFGElement`.
+  ///
+  /// Transfer function for statements in the code being analysed.
+  virtual void transfer(const Stmt *Stmt, Lattice &L, Environment &Env) {}
+
+  /// Transfer function for elements in the control flow graph built from the
+  /// code being analysed.
+  virtual void transfer(const CFGElement *Element, Lattice &L,
+Environment &Env) {}
+
+  // FIXME: Use CRTP pattern and remove virtual transfer functions after users
+  // have been updated to implement transfer.
+  // (e.g. static_cast(this)->transfer(Element, L, Env))
+  void transferTypeErased(const CFGElement *Element, TypeErasedLattice &E,
   Environment &Env) final {
 Lattice &L = llvm::any_cast(E.Value);
-static_cast(this)->transfer(Stmt, L, Env);
+transfer(Element, L, Env);
+
+// FIXME: Remove after users have been updated to implement the `transfer`
+// overload applied on `CFGElement`.
+if (auto Stmt = Element->getAs()) {
+  transfer(Stmt->getStmt(), L, Env);
+}
   }
 
 private:
@@ -112,37 +131,41 @@ template  struct DataflowAnalysisState 
{
   Environment Env;
 };
 
+// FIXME: Rename to `runDataflowAnalysis` after usages of the overload that
+// applies to `CFGStmt` have been replaced.
+//
 /// Performs dataflow analysis and returns a mapping from basic block IDs to
 /// dataflow analysis states that model the respective basic blocks. The
 /// returned vector, if any, will have the same size as the number of CFG
 /// blocks, with indices corresponding to basic block IDs. Returns an error if
 /// the dataflow analysis cannot be performed successfully. Otherwise, calls
-/// `PostVisitStmt` on each statement with the final analysis results at that
+/// `PostVisitCFG` on each CFG element with the final analysis results at that
 /// program point.
 template 
 llvm::Expected>>>
-runDataflowAnalysis(
+runDataflowAnalysisOnCFG(
 const ControlFlowContext &CFCtx, AnalysisT &Analysis,
 const Environment &InitEnv,
-std::function &)>
-PostVisitStmt = nullptr) {
-  std::function
-  PostVisitStmtClosure = nullptr;
-  if (PostVisitStmt != nullptr) {
-PostVisitStmtClosure = [&PostVisitStmt](
-   const CFGStmt &Stmt,
-   const TypeErasedDataflowAnalysisState &State) {
+std::function &)>
+PostVisitCFG = nullptr) {
+  std::function
+  PostVisitCFGClosure = nullptr;
+  if (PostVisitCFG) {
+PostVisitCFGClosure = [&PostVisitCFG](
+  const CFGElement &Element,
+  const TypeErasedDataflowAnalysisState &State) {
   auto *Lattice =
   llvm::any_cast(&State.Lattice.Value);
-  PostVisitStmt(Stmt, DataflowAnalysisState{
-  *Lattice, State.Env});
+  PostVisitCFG(Element, DataflowAnalysisState{
+*Lattice, State.Env});
 };
   }
 
   auto TypeErasedBlockStates = runTypeErasedDataflowAnalysis(
-  CFCtx, Analysis, InitEnv, PostVisitStmtClosure);
+  CFCtx, Analysis, InitEnv, PostVisitCFGClosure);
   if (!TypeErasedBlockStates)
 return TypeErasedBlockStates.takeError();
 
@@ -163,6 +186,41 @@ runDataflowAnalysis(
   return BlockStates;
 }
 
+/// Deprecated. Use `runDataflowAnalysisOnCFG` instead.
+///
+/// Performs dataflow analysis and returns a mapping from basic block IDs to
+/// dataflow analysis states that model the respective basic blocks. The
+/// returned vector, if any, will have the same size as the number of CFG
+/// blocks, with indices corresponding to basic block I

[clang] 396f40a - [clang] Add __is_target_variant_{os, environment} builtins

2022-08-26 Thread Nico Weber via cfe-commits

Author: Nico Weber
Date: 2022-08-26T18:20:06-04:00
New Revision: 396f40a79fc98184fb40967db788896263b3b2fa

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

LOG: [clang] Add __is_target_variant_{os,environment} builtins

Xcode 13's clang has them. For the included testcase, Xcode's clang
behaves like the implementation in this patch.

Availability.h in the macOS 12.0 SDK (part of Xcode 13, and the current
stable version of the macOS SDK) does something like:

   #if defined(__has_builtin)
 ...
 #if __has_builtin(__is_target_os)
  #if __has_builtin(__is_target_environment)
   #if __has_builtin(__is_target_variant_os)
#if __has_builtin(__is_target_variant_environment)
 #if (... && ((__is_target_os(ios) && __is_target_environment(macabi)) 
|| (__is_target_variant_os(ios) && __is_target_variant_environment(macabi
   #define __OSX_AVAILABLE_STARTING(_osx, _ios) ...
   #define __OSX_AVAILABLE_BUT_DEPRECATED(_osxIntro, _osxDep, 
_iosIntro, _iosDep) ...
   #define __OSX_AVAILABLE_BUT_DEPRECATED_MSG(_osxIntro, _osxDep, 
_iosIntro, _iosDep, _msg) ...

So if __has_builtin(__is_target_variant_os) or
__has_builtin(__is_target_variant_environment) are false, these defines are not
defined.

Most of the time, this doesn't matter. But open-source clang currently fails
to commpile a file containing only `#include ` when
building for catalyst by adding a `-target arm64-apple-ios13.1-macabi` triple,
due to those __OSX_AVAILABLE macros not being set correctly.

If a potential future SDK version were to include cssmtype.h transitively
from a common header such as ``, then it would become
close to impossible to build Catalyst binaries with open-source clang.

To fix this for normal catalyst builds, it's only necessary that
__has_builtin() evaluates to true for these two built-ins -- the implementation
of them doesn't matter. But as a courtesy, a correct (at least on the test
cases I tried) implementation is provided. (This should also help people who
try to build zippered code, where having the correct implementation does
matter.)

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

Added: 
clang/test/Preprocessor/is_target_variant.c

Modified: 
clang/include/clang/Lex/Preprocessor.h
clang/lib/Lex/PPMacroExpansion.cpp
clang/test/Preprocessor/is_target_unknown.c

Removed: 




diff  --git a/clang/include/clang/Lex/Preprocessor.h 
b/clang/include/clang/Lex/Preprocessor.h
index 470299b133a4a..c00600c68a346 100644
--- a/clang/include/clang/Lex/Preprocessor.h
+++ b/clang/include/clang/Lex/Preprocessor.h
@@ -178,6 +178,8 @@ class Preprocessor {
   IdentifierInfo *Ident__is_target_vendor; // __is_target_vendor
   IdentifierInfo *Ident__is_target_os; // __is_target_os
   IdentifierInfo *Ident__is_target_environment;// __is_target_environment
+  IdentifierInfo *Ident__is_target_variant_os;
+  IdentifierInfo *Ident__is_target_variant_environment;
   IdentifierInfo *Ident__FLT_EVAL_METHOD__;// __FLT_EVAL_METHOD
 
   // Weak, only valid (and set) while InMacroArgs is true.

diff  --git a/clang/lib/Lex/PPMacroExpansion.cpp 
b/clang/lib/Lex/PPMacroExpansion.cpp
index 78ab8bae2f610..6053f3b5d123b 100644
--- a/clang/lib/Lex/PPMacroExpansion.cpp
+++ b/clang/lib/Lex/PPMacroExpansion.cpp
@@ -387,6 +387,10 @@ void Preprocessor::RegisterBuiltinMacros() {
   Ident__is_target_os = RegisterBuiltinMacro(*this, "__is_target_os");
   Ident__is_target_environment =
   RegisterBuiltinMacro(*this, "__is_target_environment");
+  Ident__is_target_variant_os =
+  RegisterBuiltinMacro(*this, "__is_target_variant_os");
+  Ident__is_target_variant_environment =
+  RegisterBuiltinMacro(*this, "__is_target_variant_environment");
 
   // Modules.
   Ident__building_module  = RegisterBuiltinMacro(*this, "__building_module");
@@ -1431,6 +1435,39 @@ static bool isTargetEnvironment(const TargetInfo &TI,
   return TI.getTriple().getEnvironment() == Env.getEnvironment();
 }
 
+/// Implements the __is_target_variant_os builtin macro.
+static bool isTargetVariantOS(const TargetInfo &TI, const IdentifierInfo *II) {
+  if (TI.getTriple().isOSDarwin()) {
+const llvm::Triple *VariantTriple = TI.getDarwinTargetVariantTriple();
+if (!VariantTriple)
+  return false;
+
+std::string OSName =
+(llvm::Twine("unknown-unknown-") + II->getName().lower()).str();
+llvm::Triple OS(OSName);
+if (OS.getOS() == llvm::Triple::Darwin) {
+  // Darwin matches macos, ios, etc.
+  return VariantTriple->isOSDarwin();
+}
+return VariantTriple->getOS() == OS.getOS();
+  }
+  return false;
+}
+
+/// Implements the __is_target_variant_environment builtin macro.
+static bool isTargetVariantEnvironment(const Targe

[PATCH] D132754: [clang] Add __is_target_variant_{os,environment} builtins

2022-08-26 Thread Nico Weber via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG396f40a79fc9: [clang] Add 
__is_target_variant_{os,environment} builtins (authored by thakis).
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132754

Files:
  clang/include/clang/Lex/Preprocessor.h
  clang/lib/Lex/PPMacroExpansion.cpp
  clang/test/Preprocessor/is_target_unknown.c
  clang/test/Preprocessor/is_target_variant.c

Index: clang/test/Preprocessor/is_target_variant.c
===
--- /dev/null
+++ clang/test/Preprocessor/is_target_variant.c
@@ -0,0 +1,72 @@
+// RUN: %clang_cc1 -fsyntax-only -triple arm64-apple-macos -DMAC -verify %s
+// RUN: %clang_cc1 -fsyntax-only -triple arm64-apple-ios13.1 -DIOS -verify %s
+// RUN: %clang_cc1 -fsyntax-only -triple arm64-apple-ios13.1-macabi -DCATALYST -verify %s
+// RUN: %clang_cc1 -fsyntax-only -triple arm64-apple-macos12 -darwin-target-variant-triple arm64-apple-ios-macabi -DZIPPERED -verify %s
+// expected-no-diagnostics
+
+#if !__has_builtin(__is_target_variant_os) || !__has_builtin(__is_target_variant_environment)
+  #error "has builtin doesn't work"
+#endif
+
+#ifdef ZIPPERED
+
+  // Target variant is a darwin.
+  #if !__is_target_variant_os(darwin)
+#error "mismatching variant os"
+  #endif
+
+  // Target variant is not macOS...
+  #if __is_target_variant_os(macos)
+#error "mismatching variant os"
+  #endif
+
+  // ...but iOS.
+  #if !__is_target_variant_os(ios)
+#error "mismatching variant os"
+  #endif
+
+  // Zippered builds also set the target variant environment to macabi.
+  // At the moment, only zippered builds set __is_target_variant_os(ios),
+  // so checking __is_target_variant_environment() is currently redundant
+  // with checking the former.
+  #if !__is_target_variant_environment(macabi)
+#error "mismatching variant environment"
+  #endif
+
+#else
+
+  // In non-zippered builds, even for catalyst, no target variant is set.
+  // So these are all false.
+
+  #if __is_target_variant_os(darwin)
+#error "mismatching variant os"
+  #endif
+
+  #if __is_target_variant_os(macos)
+#error "mismatching variant os"
+  #endif
+
+  #if __is_target_variant_os(ios)
+#error "mismatching variant os"
+  #endif
+
+  #if __is_target_variant_environment(macabi)
+#error "mismatching variant environment"
+  #endif
+
+#endif
+
+// The target environment in zippered builds is _not_ macabi.
+// The target environment is macabi only in catalyst builds.
+#ifdef CATALYST
+  #if !__is_target_environment(macabi)
+#error "mismatching environment"
+  #endif
+  #if !__is_target_os(ios)
+#error "mismatching os"
+  #endif
+#else
+  #if __is_target_environment(macabi)
+#error "mismatching environment"
+  #endif
+#endif
Index: clang/test/Preprocessor/is_target_unknown.c
===
--- clang/test/Preprocessor/is_target_unknown.c
+++ clang/test/Preprocessor/is_target_unknown.c
@@ -20,3 +20,13 @@
 #if !__is_target_environment(unknown)
   #error "mismatching environment"
 #endif
+
+// Unknown variant OS is not allowed.
+#if __is_target_variant_os(unknown)
+  #error "mismatching OS"
+#endif
+
+// Unknown variant environment is not allowed.
+#if __is_target_variant_environment(unknown)
+  #error "mismatching environment"
+#endif
Index: clang/lib/Lex/PPMacroExpansion.cpp
===
--- clang/lib/Lex/PPMacroExpansion.cpp
+++ clang/lib/Lex/PPMacroExpansion.cpp
@@ -387,6 +387,10 @@
   Ident__is_target_os = RegisterBuiltinMacro(*this, "__is_target_os");
   Ident__is_target_environment =
   RegisterBuiltinMacro(*this, "__is_target_environment");
+  Ident__is_target_variant_os =
+  RegisterBuiltinMacro(*this, "__is_target_variant_os");
+  Ident__is_target_variant_environment =
+  RegisterBuiltinMacro(*this, "__is_target_variant_environment");
 
   // Modules.
   Ident__building_module  = RegisterBuiltinMacro(*this, "__building_module");
@@ -1431,6 +1435,39 @@
   return TI.getTriple().getEnvironment() == Env.getEnvironment();
 }
 
+/// Implements the __is_target_variant_os builtin macro.
+static bool isTargetVariantOS(const TargetInfo &TI, const IdentifierInfo *II) {
+  if (TI.getTriple().isOSDarwin()) {
+const llvm::Triple *VariantTriple = TI.getDarwinTargetVariantTriple();
+if (!VariantTriple)
+  return false;
+
+std::string OSName =
+(llvm::Twine("unknown-unknown-") + II->getName().lower()).str();
+llvm::Triple OS(OSName);
+if (OS.getOS() == llvm::Triple::Darwin) {
+  // Darwin matches macos, ios, etc.
+  return VariantTriple->isOSDarwin();
+}
+return VariantTriple->getOS() == OS.getOS();
+  }
+  return false;
+}
+
+/// Implements the __is_target_varian

[PATCH] D132711: [HLSL] add sqrt library function

2022-08-26 Thread Greg Roth via Phabricator via cfe-commits
pow2clk added a comment.

A very minor suggestion. This looks pretty straightforward.




Comment at: clang/test/CodeGenHLSL/builtins/sqrt.hlsl:6
+// RUN:   dxil-pc-shadermodel6.3-library %s -emit-llvm -disable-llvm-passes \
+// RUN:   -o - | FileCheck %s --check-prefix=NO_HALF
+

The -fnative-half-type suggests that you're readying this for when 16-bit types 
are available. That's fine, but in the spirit of starting as early as possible 
as we tend to do with these, you might want to target shadermodel6.2 instead 
since that's where they were introduced and sqrt is as old as HLSL 1.0 AFAIK.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132711

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


[PATCH] D128830: [Pipelines] Introduce DAE after ArgumentPromotion

2022-08-26 Thread Arthur Eubanks via Phabricator via cfe-commits
aeubanks added a comment.

sent out https://reviews.llvm.org/D132764 to fix the CGSCC crash


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128830

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


[PATCH] D132147: [clang][dataflow] Refactor `TestingSupport.h`

2022-08-26 Thread weiyi via Phabricator via cfe-commits
wyt updated this revision to Diff 456032.
wyt added a comment.

Fix typo and indentation.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132147

Files:
  clang/unittests/Analysis/FlowSensitive/TestingSupport.cpp
  clang/unittests/Analysis/FlowSensitive/TestingSupport.h
  clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp
@@ -1240,43 +1240,45 @@
 /*IgnoreSmartPointerDereference=*/true};
 std::vector Diagnostics;
 llvm::Error Error = checkDataflow(
-SourceCode, FuncMatcher,
-[Options](ASTContext &Ctx, Environment &) {
-  return UncheckedOptionalAccessModel(Ctx, Options);
+/*AI:AnalysisInputs=*/{
+.Code = SourceCode,
+.TargetFuncMatcher = FuncMatcher,
+.MakeAnalysis =
+[Options](ASTContext &Ctx, Environment &) {
+  return UncheckedOptionalAccessModel(Ctx, Options);
+},
+.PostVisitCFG =
+[&Diagnostics,
+ Diagnoser = UncheckedOptionalAccessDiagnoser(Options)](
+ASTContext &Ctx, const CFGElement &Elt,
+const TypeErasedDataflowAnalysisState &State) mutable {
+  auto Stmt = Elt.getAs();
+  if (!Stmt) {
+return;
+  }
+  auto StmtDiagnostics =
+  Diagnoser.diagnose(Ctx, Stmt->getStmt(), State.Env);
+  llvm::move(StmtDiagnostics, std::back_inserter(Diagnostics));
+},
+.ASTBuildArgs = {"-fsyntax-only", "-std=c++17",
+ "-Wno-undefined-inline"},
+.ASTBuildVirtualMappedFiles = FileContents,
 },
-[&Diagnostics, Diagnoser = UncheckedOptionalAccessDiagnoser(Options)](
-ASTContext &Ctx, const CFGStmt &Stmt,
-const TypeErasedDataflowAnalysisState &State) mutable {
-  auto StmtDiagnostics =
-  Diagnoser.diagnose(Ctx, Stmt.getStmt(), State.Env);
-  llvm::move(StmtDiagnostics, std::back_inserter(Diagnostics));
-},
-[&Diagnostics](AnalysisData AnalysisData) {
-  auto &SrcMgr = AnalysisData.ASTCtx.getSourceManager();
-
+/*VerifyResults=*/[&Diagnostics](llvm::DenseMap
+ &Annotations,
+ AnalysisOutputs &AO) {
   llvm::DenseSet AnnotationLines;
-  for (const auto &Pair : AnalysisData.Annotations) {
-auto *Stmt = Pair.getFirst();
-AnnotationLines.insert(
-SrcMgr.getPresumedLineNumber(Stmt->getBeginLoc()));
-// We add both the begin and end locations, so that if the
-// statement spans multiple lines then the test will fail.
-//
-// FIXME: Going forward, we should change this to instead just
-// get the single line number from the annotation itself, rather
-// than looking at the statement it's attached to.
-AnnotationLines.insert(
-SrcMgr.getPresumedLineNumber(Stmt->getEndLoc()));
+  for (const auto &[Line, _] : Annotations) {
+AnnotationLines.insert(Line);
   }
-
+  auto &SrcMgr = AO.ASTCtx.getSourceManager();
   llvm::DenseSet DiagnosticLines;
   for (SourceLocation &Loc : Diagnostics) {
 DiagnosticLines.insert(SrcMgr.getPresumedLineNumber(Loc));
   }
 
   EXPECT_THAT(DiagnosticLines, ContainerEq(AnnotationLines));
-},
-{"-fsyntax-only", "-std=c++17", "-Wno-undefined-inline"}, FileContents);
+});
 if (Error)
   FAIL() << llvm::toString(std::move(Error));
   }
Index: clang/unittests/Analysis/FlowSensitive/TestingSupport.h
===
--- clang/unittests/Analysis/FlowSensitive/TestingSupport.h
+++ clang/unittests/Analysis/FlowSensitive/TestingSupport.h
@@ -56,47 +56,134 @@
 
 namespace test {
 
-// Returns assertions based on annotations that are present after statements in
-// `AnnotatedCode`.
-llvm::Expected>
-buildStatementToAnnotationMapping(const FunctionDecl *Func,
-  llvm::Annotations AnnotatedCode);
-
-struct AnalysisData {
+/// Contains data structures required and produced by a dataflow analysis run.
+struct AnalysisOutputs {
+  /// Input code that is analyzed. Points within the code may be marked with
+  /// annotations to facilitate testing.
+  ///
+  /// Example:
+  /// void targe

[PATCH] D132763: [clang][dataflow] Use `StringMap` for storing analysis states at annotated points instead of `vector>`.

2022-08-26 Thread weiyi via Phabricator via cfe-commits
wyt created this revision.
Herald added subscribers: martong, mgrang, xazax.hun.
Herald added a project: All.
wyt requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Depends On D132377 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D132763

Files:
  clang/unittests/Analysis/FlowSensitive/TestingSupport.cpp
  clang/unittests/Analysis/FlowSensitive/TestingSupport.h
  clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
  clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
@@ -426,12 +426,12 @@
std::pair>>
Results,
ASTContext &ASTCtx) {
-ASSERT_THAT(Results, ElementsAre(Pair("p4", _), Pair("p3", _),
- Pair("p2", _), Pair("p1", _)));
-const Environment &Env1 = Results[3].second.Env;
-const Environment &Env2 = Results[2].second.Env;
-const Environment &Env3 = Results[1].second.Env;
-const Environment &Env4 = Results[0].second.Env;
+ASSERT_THAT(Results, ElementsAre(Pair("p1", _), Pair("p2", _),
+ Pair("p3", _), Pair("p4", _)));
+const Environment &Env1 = Results[0].second.Env;
+const Environment &Env2 = Results[1].second.Env;
+const Environment &Env3 = Results[2].second.Env;
+const Environment &Env4 = Results[3].second.Env;
 
 const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
 ASSERT_THAT(FooDecl, NotNull());
@@ -579,10 +579,10 @@
  Results,
  ASTContext &ASTCtx) {
 ASSERT_THAT(Results,
-ElementsAre(Pair("p3", _), Pair("p2", _), Pair("p1", _)));
-const Environment &Env1 = Results[2].second.Env;
+ElementsAre(Pair("p1", _), Pair("p2", _), Pair("p3", _)));
+const Environment &Env1 = Results[0].second.Env;
 const Environment &Env2 = Results[1].second.Env;
-const Environment &Env3 = Results[0].second.Env;
+const Environment &Env3 = Results[2].second.Env;
 
 const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
 ASSERT_THAT(FooDecl, NotNull());
@@ -622,12 +622,12 @@
  std::pair>>
  Results,
  ASTContext &ASTCtx) {
-ASSERT_THAT(Results, ElementsAre(Pair("p4", _), Pair("p3", _),
- Pair("p2", _), Pair("p1", _)));
-const Environment &Env1 = Results[3].second.Env;
-const Environment &Env2 = Results[2].second.Env;
-const Environment &Env3 = Results[1].second.Env;
-const Environment &Env4 = Results[0].second.Env;
+ASSERT_THAT(Results, ElementsAre(Pair("p1", _), Pair("p2", _),
+ Pair("p3", _), Pair("p4", _)));
+const Environment &Env1 = Results[0].second.Env;
+const Environment &Env2 = Results[1].second.Env;
+const Environment &Env3 = Results[2].second.Env;
+const Environment &Env4 = Results[3].second.Env;
 
 const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
 ASSERT_THAT(FooDecl, NotNull());
@@ -751,14 +751,14 @@
 const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
 ASSERT_THAT(FooDecl, NotNull());
 
-ASSERT_THAT(Results, ElementsAre(Pair("p2", _), Pair("p1", _)));
+ASSERT_THAT(Results, ElementsAre(Pair("p1", _), Pair("p2", _)));
 
-const Environment &Env1 = Results[1].second.Env;
+const Environment &Env1 = Results[0].second.Env;
 auto *FooVal1 =
 cast(Env1.getValue(*FooDecl, SkipPast::None));
 EXPECT_TRUE(Env1.flowConditionImplies(*FooVal1));
 
-const Environment &Env2 = Results[0].second.Env;
+const Environment &Env2 = Results[1].second.Env;
 auto *FooVal2 =
 cast(Env2.getValue(*FooDecl, SkipPast::None));
 EXPECT_FALSE(Env2.flowConditionImplies(*FooVal2));
@@ -785,14 +785,14 @@
 const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
 ASSERT_THAT(FooDecl, NotNull());
 
-ASSERT_THAT(Results, ElementsAre(Pair("p2", _), Pair("p1", _)));
+ASSERT_THAT(Results, ElementsAre(Pair("p1", _), Pair("p2", _)));
 
-const Environment &Env1 = Results[1].second.Env;
+con

[PATCH] D132377: [clang][dataflow] Add `SetupTest` parameter for `AnalysisInputs`.

2022-08-26 Thread weiyi via Phabricator via cfe-commits
wyt updated this revision to Diff 456030.
wyt added a comment.

Propagate change from parent patch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132377

Files:
  clang/unittests/Analysis/FlowSensitive/TestingSupport.cpp
  clang/unittests/Analysis/FlowSensitive/TestingSupport.h

Index: clang/unittests/Analysis/FlowSensitive/TestingSupport.h
===
--- clang/unittests/Analysis/FlowSensitive/TestingSupport.h
+++ clang/unittests/Analysis/FlowSensitive/TestingSupport.h
@@ -94,6 +94,11 @@
   /// takes as argument the AST generated from the code being analyzed and the
   /// initial state from which the analysis starts with.
   std::function MakeAnalysis;
+  /// Optional. If provided, this function is executed immediately before
+  /// running the dataflow analysis to allow for additional setup. All fields in
+  /// the `AnalysisOutputs` argument will be initialized except for the
+  /// `BlockStates` field which is only computed later during the analysis.
+  std::function SetupTest = nullptr;
   /// Optional. If provided, this function is applied on each CFG element after
   /// the analysis has been run.
   std::function
-getAnnotationLinesAndContent(AnalysisOutputs &AO);
-
-// FIXME: Return a string map instead of a vector of pairs.
-//
-/// Returns the analysis states at each annotated statement in `AO.Code`.
-template 
-llvm::Expected>>>
-getAnnotationStates(AnalysisOutputs &AO) {
-  using StateT = DataflowAnalysisState;
-  // FIXME: Extend to annotations on non-statement constructs.
-  // Get annotated statements.
-  llvm::Expected>
-  MaybeStmtToAnnotations =
-  buildStatementToAnnotationMapping(AO.Target, AO.Code);
-  if (!MaybeStmtToAnnotations)
-return MaybeStmtToAnnotations.takeError();
-  auto &StmtToAnnotations = *MaybeStmtToAnnotations;
-
-  // Compute a map from statement annotations to the state computed
-  // for the program point immediately after the annotated statement.
-  std::vector> Results;
-  for (const CFGBlock *Block : AO.CFCtx.getCFG()) {
-// Skip blocks that were not evaluated.
-if (!AO.BlockStates[Block->getBlockID()])
-  continue;
-
-transferBlock(
-AO.CFCtx, AO.BlockStates, *Block, AO.InitEnv, AO.Analysis,
-[&Results,
- &StmtToAnnotations](const clang::CFGElement &Element,
- const TypeErasedDataflowAnalysisState &State) {
-  auto Stmt = Element.getAs();
-  if (!Stmt)
-return;
-  auto It = StmtToAnnotations.find(Stmt->getStmt());
-  if (It == StmtToAnnotations.end())
-return;
-  auto *Lattice =
-  llvm::any_cast(&State.Lattice.Value);
-  Results.emplace_back(It->second, StateT{*Lattice, State.Env});
-});
-  }
-
-  return Results;
-}
+buildLineToAnnotationMapping(SourceManager &SM,
+ llvm::Annotations AnnotatedCode);
 
 /// Runs dataflow specified from `AI.MakeAnalysis` and `AI.PostVisitCFG` on the
 /// body of the function that matches `AI.TargetFuncMatcher` in `AI.Code`.
@@ -176,7 +137,7 @@
 template 
 llvm::Error
 checkDataflow(AnalysisInputs AI,
-  std::function VerifyResults) {
+  std::function VerifyResults) {
   // Build AST context from code.
   llvm::Annotations AnnotatedCode(AI.Code);
   auto Unit = tooling::buildASTFromCodeWithArgs(
@@ -210,7 +171,7 @@
 return MaybeCFCtx.takeError();
   auto &CFCtx = *MaybeCFCtx;
 
-  // Initialize states and run dataflow analysis.
+  // Initialize states for running dataflow analysis.
   DataflowAnalysisContext DACtx(std::make_unique());
   Environment InitEnv(DACtx, *Target);
   auto Analysis = AI.MakeAnalysis(Context, InitEnv);
@@ -225,19 +186,28 @@
 };
   }
 
-  // If successful, the run returns a mapping from block IDs to the
-  // post-analysis states for the CFG blocks that have been evaluated.
+  // Additional test setup.
+  AnalysisOutputs AO{AnnotatedCode, Context, Target, CFCtx,
+ Analysis,  InitEnv, {}};
+  if (AI.SetupTest) {
+auto Error = AI.SetupTest(AO);
+if (Error) {
+  return Error;
+}
+  }
+
+  // If successful, the dataflow analysis returns a mapping from block IDs to
+  // the post-analysis states for the CFG blocks that have been evaluated.
   llvm::Expected>>
   MaybeBlockStates = runTypeErasedDataflowAnalysis(CFCtx, Analysis, InitEnv,
PostVisitCFGClosure);
   if (!MaybeBlockStates)
 return MaybeBlockStates.takeError();
-  auto &BlockStates = *MaybeBlockStates;
+  AO.BlockStates = *MaybeBlockStates;
 
   // Verify dataflow analysis outputs.
-  AnalysisOutputs AO{AnnotatedCode, Context, Target, CFCtx,
- Analysis,  InitEnv, BlockStates};
-  return VerifyResults(AO);
+  VerifyResults(AO);
+  return llvm::Err

[PATCH] D132147: [clang][dataflow] Refactor `TestingSupport.h`

2022-08-26 Thread weiyi via Phabricator via cfe-commits
wyt updated this revision to Diff 456029.
wyt marked 4 inline comments as done.
wyt added a comment.

Address comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132147

Files:
  clang/unittests/Analysis/FlowSensitive/TestingSupport.cpp
  clang/unittests/Analysis/FlowSensitive/TestingSupport.h
  clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp
@@ -1240,43 +1240,45 @@
 /*IgnoreSmartPointerDereference=*/true};
 std::vector Diagnostics;
 llvm::Error Error = checkDataflow(
-SourceCode, FuncMatcher,
-[Options](ASTContext &Ctx, Environment &) {
-  return UncheckedOptionalAccessModel(Ctx, Options);
+/*AI:AnalysisInputs=*/{
+.Code = SourceCode,
+.TargetFuncMatcher = FuncMatcher,
+.MakeAnalysis =
+[Options](ASTContext &Ctx, Environment &) {
+  return UncheckedOptionalAccessModel(Ctx, Options);
+},
+.PostVisitCFG =
+[&Diagnostics,
+ Diagnoser = UncheckedOptionalAccessDiagnoser(Options)](
+ASTContext &Ctx, const CFGElement &Elt,
+const TypeErasedDataflowAnalysisState &State) mutable {
+  auto Stmt = Elt.getAs();
+  if (!Stmt) {
+return;
+  }
+  auto StmtDiagnostics =
+  Diagnoser.diagnose(Ctx, Stmt->getStmt(), State.Env);
+  llvm::move(StmtDiagnostics, std::back_inserter(Diagnostics));
+},
+.ASTBuildArgs = {"-fsyntax-only", "-std=c++17",
+ "-Wno-undefined-inline"},
+.ASTBuildVirtualMappedFiles = FileContents,
 },
-[&Diagnostics, Diagnoser = UncheckedOptionalAccessDiagnoser(Options)](
-ASTContext &Ctx, const CFGStmt &Stmt,
-const TypeErasedDataflowAnalysisState &State) mutable {
-  auto StmtDiagnostics =
-  Diagnoser.diagnose(Ctx, Stmt.getStmt(), State.Env);
-  llvm::move(StmtDiagnostics, std::back_inserter(Diagnostics));
-},
-[&Diagnostics](AnalysisData AnalysisData) {
-  auto &SrcMgr = AnalysisData.ASTCtx.getSourceManager();
-
+/*VerifyResults=*/[&Diagnostics](llvm::DenseMap
+ &Annotations,
+ AnalysisOutputs &AO) {
   llvm::DenseSet AnnotationLines;
-  for (const auto &Pair : AnalysisData.Annotations) {
-auto *Stmt = Pair.getFirst();
-AnnotationLines.insert(
-SrcMgr.getPresumedLineNumber(Stmt->getBeginLoc()));
-// We add both the begin and end locations, so that if the
-// statement spans multiple lines then the test will fail.
-//
-// FIXME: Going forward, we should change this to instead just
-// get the single line number from the annotation itself, rather
-// than looking at the statement it's attached to.
-AnnotationLines.insert(
-SrcMgr.getPresumedLineNumber(Stmt->getEndLoc()));
+  for (const auto &[Line, _] : Annotations) {
+AnnotationLines.insert(Line);
   }
-
+  auto &SrcMgr = AO.ASTCtx.getSourceManager();
   llvm::DenseSet DiagnosticLines;
   for (SourceLocation &Loc : Diagnostics) {
 DiagnosticLines.insert(SrcMgr.getPresumedLineNumber(Loc));
   }
 
   EXPECT_THAT(DiagnosticLines, ContainerEq(AnnotationLines));
-},
-{"-fsyntax-only", "-std=c++17", "-Wno-undefined-inline"}, FileContents);
+});
 if (Error)
   FAIL() << llvm::toString(std::move(Error));
   }
Index: clang/unittests/Analysis/FlowSensitive/TestingSupport.h
===
--- clang/unittests/Analysis/FlowSensitive/TestingSupport.h
+++ clang/unittests/Analysis/FlowSensitive/TestingSupport.h
@@ -56,47 +56,134 @@
 
 namespace test {
 
-// Returns assertions based on annotations that are present after statements in
-// `AnnotatedCode`.
-llvm::Expected>
-buildStatementToAnnotationMapping(const FunctionDecl *Func,
-  llvm::Annotations AnnotatedCode);
-
-struct AnalysisData {
+/// Contains data structures required and produced by a dataflow analysis run.
+struct AnalysisOutputs {
+  /// Input code that is analyzed. Points within the code may be marked with
+  /// annotations to facilitate testing.
+  ///
+  

[PATCH] D132762: [clang-format] Allow `throw` to be a keyword in front of casts

2022-08-26 Thread Emilia Dreamer via Phabricator via cfe-commits
rymiel created this revision.
rymiel added reviewers: HazardyKnusperkeks, owenpan, MyDeveloperDay, curdeius.
Herald added a project: All.
rymiel requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This makes `throw` more similar to `return`. However, unlike `return`,
it has to more strict as to not remove spaces after usages of `throw` as
a (deprecated) exception specifier.

Fixes https://github.com/llvm/llvm-project/issues/57391


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D132762

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


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -10958,6 +10958,7 @@
   verifyFormat("my_int a = (my_int)2.0f;");
   verifyFormat("my_int a = (my_int)sizeof(int);");
   verifyFormat("return (my_int)aaa;");
+  verifyFormat("throw (my_int)aaa;");
   verifyFormat("#define x ((int)-1)");
   verifyFormat("#define LENGTH(x, y) (x) - (y) + 1");
   verifyFormat("#define p(q) ((int *)&q)");
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -2153,7 +2153,7 @@
   // before the parentheses, this is unlikely to be a cast.
   if (LeftOfParens->Tok.getIdentifierInfo() &&
   !LeftOfParens->isOneOf(Keywords.kw_in, tok::kw_return, tok::kw_case,
- tok::kw_delete)) {
+ tok::kw_delete, tok::kw_throw)) {
 return false;
   }
 
@@ -3312,6 +3312,10 @@
   !Right.isOneOf(tok::semi, tok::r_paren, tok::hashhash)) {
 return true;
   }
+  if (Left.is(tok::kw_throw) && Right.is(tok::l_paren) && Right.MatchingParen 
&&
+  Right.MatchingParen->is(TT_CastRParen)) {
+return true;
+  }
   if (Style.isJson() && Left.is(tok::string_literal) && Right.is(tok::colon))
 return false;
   if (Left.is(Keywords.kw_assert) && Style.Language == FormatStyle::LK_Java)


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -10958,6 +10958,7 @@
   verifyFormat("my_int a = (my_int)2.0f;");
   verifyFormat("my_int a = (my_int)sizeof(int);");
   verifyFormat("return (my_int)aaa;");
+  verifyFormat("throw (my_int)aaa;");
   verifyFormat("#define x ((int)-1)");
   verifyFormat("#define LENGTH(x, y) (x) - (y) + 1");
   verifyFormat("#define p(q) ((int *)&q)");
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -2153,7 +2153,7 @@
   // before the parentheses, this is unlikely to be a cast.
   if (LeftOfParens->Tok.getIdentifierInfo() &&
   !LeftOfParens->isOneOf(Keywords.kw_in, tok::kw_return, tok::kw_case,
- tok::kw_delete)) {
+ tok::kw_delete, tok::kw_throw)) {
 return false;
   }
 
@@ -3312,6 +3312,10 @@
   !Right.isOneOf(tok::semi, tok::r_paren, tok::hashhash)) {
 return true;
   }
+  if (Left.is(tok::kw_throw) && Right.is(tok::l_paren) && Right.MatchingParen &&
+  Right.MatchingParen->is(TT_CastRParen)) {
+return true;
+  }
   if (Style.isJson() && Left.is(tok::string_literal) && Right.is(tok::colon))
 return false;
   if (Left.is(Keywords.kw_assert) && Style.Language == FormatStyle::LK_Java)
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D128830: [Pipelines] Introduce DAE after ArgumentPromotion

2022-08-26 Thread Arthur Eubanks via Phabricator via cfe-commits
aeubanks added a comment.

reduced:

  define void @a() {
  entry:
%call = call float @strtof(ptr noundef null, ptr noundef null)
ret void
  }
  
  define internal float @strtof(ptr noundef %0, ptr noundef %1) nounwind {
  entry:
ret float 0.0
  }

`./build/rel/bin/opt -passes='inline,argpromotion' -disable-output /tmp/b.ll`

likely something to do with how the CGSCC pass manager handles lib function 
(see `isKnownLibFunction` in LazyCallGraph.cpp)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128830

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


[clang] 0e5813b - [clang][NFC] silences warnings

2022-08-26 Thread Christopher Di Bella via cfe-commits

Author: Abraham Corea Diaz
Date: 2022-08-26T21:09:39Z
New Revision: 0e5813b88e50576940070003e093d696390a6959

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

LOG: [clang][NFC] silences warnings

* removes unused data member `OS` from `SARIFDiagnostic`
* flags `Filename` variable as currently unused

This is a follow-up to D131632.

Added: 


Modified: 
clang/include/clang/Frontend/SARIFDiagnostic.h
clang/lib/Frontend/SARIFDiagnostic.cpp

Removed: 




diff  --git a/clang/include/clang/Frontend/SARIFDiagnostic.h 
b/clang/include/clang/Frontend/SARIFDiagnostic.h
index bd0f1df9aa58..ec1d0b8e6a7c 100644
--- a/clang/include/clang/Frontend/SARIFDiagnostic.h
+++ b/clang/include/clang/Frontend/SARIFDiagnostic.h
@@ -55,8 +55,6 @@ class SARIFDiagnostic : public DiagnosticRenderer {
   StringRef ModuleName) override;
 
 private:
-  raw_ostream &OS;
-
   // Shared between SARIFDiagnosticPrinter and this renderer.
   SarifDocumentWriter *Writer;
 

diff  --git a/clang/lib/Frontend/SARIFDiagnostic.cpp 
b/clang/lib/Frontend/SARIFDiagnostic.cpp
index 2bcbd5cf34f2..f0f32a179825 100644
--- a/clang/lib/Frontend/SARIFDiagnostic.cpp
+++ b/clang/lib/Frontend/SARIFDiagnostic.cpp
@@ -33,7 +33,7 @@ namespace clang {
 SARIFDiagnostic::SARIFDiagnostic(raw_ostream &OS, const LangOptions &LangOpts,
  DiagnosticOptions *DiagOpts,
  SarifDocumentWriter *Writer)
-: DiagnosticRenderer(LangOpts, DiagOpts), OS(OS), Writer(Writer) {}
+: DiagnosticRenderer(LangOpts, DiagOpts), Writer(Writer) {}
 
 // FIXME(llvm-project/issues/57323): Refactor Diagnostic classes.
 void SARIFDiagnostic::emitDiagnosticMessage(
@@ -71,7 +71,8 @@ SarifResult SARIFDiagnostic::addLocationToResult(
 FileID FID = Loc.getFileID();
 if (FID.isValid()) {
   if (const FileEntry *FE = Loc.getFileEntry()) {
-emitFilename(FE->getName(), Loc.getManager());
+[[gnu::unused]] llvm::StringRef Filename =
+emitFilename(FE->getName(), Loc.getManager());
 // FIXME(llvm-project/issues/57366): File-only locations
   }
 }



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


[clang] 937aaea - [CUDA] Fix arguments after removing unused private variable

2022-08-26 Thread Joseph Huber via cfe-commits

Author: Joseph Huber
Date: 2022-08-26T15:28:34-05:00
New Revision: 937aaead87f055caa4d91d7ba637d442a94a24a6

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

LOG: [CUDA] Fix arguments after removing unused private variable

Summary:
A previous patch removed the use of the `OK` private variable in CUDA
which resulted in usused variable warnings. this was fixed in
f886f7e8ef7aa4f54298db792a656373af90440c but did not change the
constructor to accurately represent its removal. This patch removes it
from the interface entirely.

Added: 


Modified: 
clang/lib/Driver/Driver.cpp
clang/lib/Driver/ToolChains/Cuda.cpp
clang/lib/Driver/ToolChains/Cuda.h

Removed: 




diff  --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index bca88e96da6f..d23a8931a8a8 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -757,7 +757,7 @@ void Driver::CreateOffloadingDeviceToolChains(Compilation 
&C,
 auto &CudaTC = ToolChains[CudaTriple->str() + "/" + HostTriple.str()];
 if (!CudaTC) {
   CudaTC = std::make_unique(
-  *this, *CudaTriple, *HostTC, C.getInputArgs(), OFK);
+  *this, *CudaTriple, *HostTC, C.getInputArgs());
 }
 C.addOffloadDeviceToolChain(CudaTC.get(), OFK);
   } else if (IsHIP) {
@@ -874,7 +874,7 @@ void Driver::CreateOffloadingDeviceToolChains(Compilation 
&C,
   if (!DeviceTC) {
 if (TT.isNVPTX())
   DeviceTC = std::make_unique(
-  *this, TT, *HostTC, C.getInputArgs(), Action::OFK_OpenMP);
+  *this, TT, *HostTC, C.getInputArgs());
 else if (TT.isAMDGCN())
   DeviceTC = std::make_unique(
   *this, TT, *HostTC, C.getInputArgs());

diff  --git a/clang/lib/Driver/ToolChains/Cuda.cpp 
b/clang/lib/Driver/ToolChains/Cuda.cpp
index 4d9a473419d3..84a12bd4a144 100644
--- a/clang/lib/Driver/ToolChains/Cuda.cpp
+++ b/clang/lib/Driver/ToolChains/Cuda.cpp
@@ -596,8 +596,7 @@ void NVPTX::getNVPTXTargetFeatures(const Driver &D, const 
llvm::Triple &Triple,
 /// together object files from the assembler into a single blob.
 
 CudaToolChain::CudaToolChain(const Driver &D, const llvm::Triple &Triple,
- const ToolChain &HostTC, const ArgList &Args,
- const Action::OffloadKind OK)
+ const ToolChain &HostTC, const ArgList &Args)
 : ToolChain(D, Triple, Args), HostTC(HostTC),
   CudaInstallation(D, HostTC.getTriple(), Args) {
   if (CudaInstallation.isValid()) {

diff  --git a/clang/lib/Driver/ToolChains/Cuda.h 
b/clang/lib/Driver/ToolChains/Cuda.h
index a51dcc2d5a20..c073a9abceb9 100644
--- a/clang/lib/Driver/ToolChains/Cuda.h
+++ b/clang/lib/Driver/ToolChains/Cuda.h
@@ -123,8 +123,7 @@ namespace toolchains {
 class LLVM_LIBRARY_VISIBILITY CudaToolChain : public ToolChain {
 public:
   CudaToolChain(const Driver &D, const llvm::Triple &Triple,
-const ToolChain &HostTC, const llvm::opt::ArgList &Args,
-const Action::OffloadKind OK);
+const ToolChain &HostTC, const llvm::opt::ArgList &Args);
 
   const llvm::Triple *getAuxTriple() const override {
 return &HostTC.getTriple();



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


[PATCH] D129280: [analyzer] PlacementNewChecker, properly handle array overhead (cookie)

2022-08-26 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added inline comments.



Comment at: clang/lib/StaticAnalyzer/Checkers/CheckPlacementNew.cpp:157
 "Storage provided to placement new is only {0} bytes, "
-"whereas the allocated array type requires more space for "
-"internal needs",
-SizeOfPlaceCI->getValue(), SizeOfTargetCI->getValue()));
+"whereas the allocated array type might require more space for "
+"allocation overhead",

NoQ wrote:
> isuckatcs wrote:
> > martong wrote:
> > > NoQ wrote:
> > > > "might" is not very convincing, it may cause a reaction like "I've no 
> > > > idea what it's talking about and the compiler itself isn't sure, must 
> > > > be false positive". Can we do anything to point the user in the right 
> > > > direction? Say, if this is implementation-defined, are we looking at a 
> > > > portability issue?
> > > Okay, I see your point. Let's dissect the corresponding sections of the 
> > > standard:
> > > ```
> > > new(2, f) T[5] results in a call of operator new[](sizeof(T) * 5 + y, 2, 
> > > f).
> > > 
> > > Here, ... and y are non-negative unspecified values representing array 
> > > allocation overhead;
> > > ```
> > > The array overhead is an **unspecified value**. What does it mean 
> > > exactly? My understanding is that this means it is implementation defined 
> > > and the implementation is not required to document or guarantee anything. 
> > > I came to this conclusion based on this [[ 
> > > https://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior
> > >  | stackoverflow question ]]. 
> > > 
> > > My interpretation could be wrong, but that does not matter. I think, we 
> > > should just simply display the user what the standard says, and let them 
> > > digest themselves the meaning of "unspecified". I am updating the patch 
> > > like so.
> > I also looked into this overhead question. In this [[ 
> > https://stackoverflow.com/a/8721932 | stackoverflow answer]] someone links 
> > the same defect report that you did, and claims that since it's a defect 
> > report, it has been applied retroactively. 
> > 
> > Apparently [[ https://en.cppreference.com/w/cpp/language/new | cppreference 
> > ]] says the same. If you check the defect reports section on the bottom of 
> > the page you can see:
> > ```
> > The following behavior-changing defect reports were applied retroactively 
> > to previously published C++ standards.
> > 
> > ...
> > DR | Applied to | Behavior as published | Correct behavior
> > CWG 2382 | C++98 | non-allocating placement array new could require 
> > allocation overhead | such allocation overhead disallowed
> > ```
> > 
> > So in my understanding you don't need to worry about this overhead at all. 
> > I hope this helps.
> Ok it sounds like we shouldn't emit any warnings at all here, unless we're 
> somehow able to get a signal that the user is compiling their code with a 
> pre-2019 compiler that hasn't been updated to reflect this defect report. One 
> way we could get that signal is by putting the checker into the `portability` 
> package which is off-by-default. Then we can explain the situation in the 
> warning message:
> 
> > "Storage provided to placement new is only {0} bytes, which is sufficient 
> > to hold the array data but placement new may require additional unspecified 
> > array allocation overhead on compilers that don't implement CWG 2382"
> 
> Then if the users enable `portability` but aren't interested in this warning, 
> at least they know how to enable and disable checkers, so they can disable 
> this specific check.
Personally, I think we should definitely not branch on the standard version.
This was never a thing anyway, AFAIK.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129280

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


[PATCH] D128745: [c++] implements DR692, DR1395 and tentatively DR1432, about partial ordering of variadic template partial specialization or function template

2022-08-26 Thread Yuanfang Chen via Phabricator via cfe-commits
ychen added a comment.

In D128745#3752593 , @ychen wrote:

> In D128745#3752148 , @ychen wrote:
>
>> In D128745#3751471 , @joanahalili 
>> wrote:
>>
>>> We have some compilation failures on our end because of function template 
>>> parameter deduction when passing the function template to a function 
>>> pointer.
>>>
>>>   typedef void (*f)(const int&);
>>>   
>>>   template 
>>>   void F(T value) {}
>>>   
>>>   template 
>>>   void F(const T& value){}
>>>   
>>>   void q(f);
>>>   
>>>   void w() {
>>>   q(&F);
>>>   }
>>>
>>> https://gcc.godbolt.org/z/faoq74q7G
>>> Is this an intended outcome for this patch?
>>
>> Thanks for the report. No that's not the intent. This should only affect 
>> partial ordering but not which candidate is viable (error message `candidate 
>> function not viable ...`). I'll take a look.
>
> This new behavior is correct. It is due to the change on line 1758 in 
> `SemaTemplateDeduction.cpp`. Basically, both the taking address of and 
> regular function call to the overloaded function set using the same partial 
> ordering rule (Relevant wording https://eel.is/c++draft/over.over#5). GCC is 
> inconsistent in this regard (https://gcc.godbolt.org/z/WrKsaKrdz). MSVC 
> agrees with this new/correct behavior.

TBH, the Clang diagnosis could be better here. It kinda misleading about what 
is happening. MSVC's diagnosis is more clear 
(https://gcc.godbolt.org/z/WrKsaKrdz).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128745

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


[PATCH] D128745: [c++] implements DR692, DR1395 and tentatively DR1432, about partial ordering of variadic template partial specialization or function template

2022-08-26 Thread Yuanfang Chen via Phabricator via cfe-commits
ychen added a comment.

In D128745#3752148 , @ychen wrote:

> In D128745#3751471 , @joanahalili 
> wrote:
>
>> We have some compilation failures on our end because of function template 
>> parameter deduction when passing the function template to a function pointer.
>>
>>   typedef void (*f)(const int&);
>>   
>>   template 
>>   void F(T value) {}
>>   
>>   template 
>>   void F(const T& value){}
>>   
>>   void q(f);
>>   
>>   void w() {
>>   q(&F);
>>   }
>>
>> https://gcc.godbolt.org/z/faoq74q7G
>> Is this an intended outcome for this patch?
>
> Thanks for the report. No that's not the intent. This should only affect 
> partial ordering but not which candidate is viable (error message `candidate 
> function not viable ...`). I'll take a look.

This new behavior is correct. It is due to the change on line 1758 in 
`SemaTemplateDeduction.cpp`. Basically, both the taking address of and regular 
function call to the overloaded function set using the same partial ordering 
rule (Relevant wording https://eel.is/c++draft/over.over#5). GCC was 
inconsistent in this regard (https://gcc.godbolt.org/z/WrKsaKrdz). MSVC agrees 
with this new/correct behavior.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128745

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


[PATCH] D132739: [clang][Interp] Implement IntegralToBoolean casts

2022-08-26 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.

LGTM!


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

https://reviews.llvm.org/D132739

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


[clang-tools-extra] 9343ec8 - [clang-tidy] Adding the missing handling of "noreturn" attributes for Obj-C nodes in `InfiniteLoopChecker`

2022-08-26 Thread via cfe-commits

Author: ziqingluo-90
Date: 2022-08-26T12:44:59-07:00
New Revision: 9343ec861a2e47f05b3b4339f45f6e755b1c5f96

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

LOG: [clang-tidy] Adding the missing handling of "noreturn" attributes for 
Obj-C nodes in `InfiniteLoopChecker`

With this commit, the `InfiniteLoopChecker` now recognizes message
expressions to "noreturn" methods as well as calls to "noreturn"
blocks.

Reviewed by NoQ, njames93
Differential Revision: https://reviews.llvm.org/D128314

Added: 

clang-tools-extra/test/clang-tidy/checkers/bugprone/infinite-loop-noreturn.mm

Modified: 
clang-tools-extra/clang-tidy/bugprone/InfiniteLoopCheck.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/bugprone/InfiniteLoopCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/InfiniteLoopCheck.cpp
index 8815de220882e..e2401ff7ec0c0 100644
--- a/clang-tools-extra/clang-tidy/bugprone/InfiniteLoopCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/InfiniteLoopCheck.cpp
@@ -16,15 +16,35 @@ using namespace clang::ast_matchers;
 using clang::tidy::utils::hasPtrOrReferenceInFunc;
 
 namespace clang {
+namespace ast_matchers {
+/// matches a Decl if it has a  "no return" attribute of any kind
+AST_MATCHER(Decl, declHasNoReturnAttr) {
+  return Node.hasAttr() || Node.hasAttr() ||
+ Node.hasAttr();
+}
+
+/// matches a FunctionType if the type includes the GNU no return attribute
+AST_MATCHER(FunctionType, typeHasNoReturnAttr) {
+  return Node.getNoReturnAttr();
+}
+} // namespace ast_matchers
 namespace tidy {
 namespace bugprone {
 
 static internal::Matcher
 loopEndingStmt(internal::Matcher Internal) {
-  // FIXME: Cover noreturn ObjC methods (and blocks?).
+  internal::Matcher isNoReturnFunType =
+  ignoringParens(functionType(typeHasNoReturnAttr()));
+  internal::Matcher isNoReturnDecl =
+  anyOf(declHasNoReturnAttr(), functionDecl(hasType(isNoReturnFunType)),
+varDecl(hasType(blockPointerType(pointee(isNoReturnFunType);
+
   return stmt(anyOf(
   mapAnyOf(breakStmt, returnStmt, gotoStmt, cxxThrowExpr).with(Internal),
-  callExpr(Internal, callee(functionDecl(isNoReturn());
+  callExpr(Internal,
+   callee(mapAnyOf(functionDecl, /* block callee */ varDecl)
+  .with(isNoReturnDecl))),
+  objcMessageExpr(Internal, callee(isNoReturnDecl;
 }
 
 /// Return whether `Var` was changed in `LoopStmt`.

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/infinite-loop-noreturn.mm 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/infinite-loop-noreturn.mm
new file mode 100644
index 0..142332d8c
--- /dev/null
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/infinite-loop-noreturn.mm
@@ -0,0 +1,62 @@
+// RUN: %check_clang_tidy %s bugprone-infinite-loop %t -- -- -fblocks 
-fexceptions
+// RUN: %check_clang_tidy %s bugprone-infinite-loop %t -- -- -fblocks 
-fobjc-arc -fexceptions
+
+@interface I
++ (void)foo;
++ (void)bar;
++ (void)baz __attribute__((noreturn));
++ (instancetype)alloc;
+- (instancetype)init;
+@end
+
+_Noreturn void term();
+
+void plainCFunction() {
+  int i = 0;
+  int j = 0;
+  int a[10];
+
+  while (i < 10) {
+// no warning, function term has C noreturn attribute
+term();
+  }
+  while (i < 10) {
+// no warning, class method baz has noreturn attribute
+[I baz];
+  }
+  while (i + j < 10) {
+// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: this loop is infinite; none of 
its condition variables (i, j) are updated in the loop body 
[bugprone-infinite-loop]
+[I foo];
+  }
+  while (i + j < 10) {
+[I foo];
+[I baz]; // no warning, class method baz has noreturn attribute
+  }
+
+  void (^block)() = ^{
+  };
+  void __attribute__((noreturn)) (^block_nr)(void) = ^void 
__attribute__((noreturn)) (void) { throw "err"; };
+
+  while (i < 10) {
+// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: this loop is infinite; none of 
its condition variables (i) are updated in the loop body 
[bugprone-infinite-loop]
+block();
+  }
+  while (i < 10) {
+// no warning, the block has "noreturn" arribute
+block_nr();
+  }
+}
+
+@implementation I
++ (void)bar {
+}
+
++ (void)foo {
+  static int i = 0;
+
+  while (i < 10) {
+// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: this loop is infinite; none of 
its condition variables (i) are updated in the loop body 
[bugprone-infinite-loop]
+[I bar];
+  }
+}
+@end



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


[PATCH] D128314: [Clang-tidy] Fixing a bug in clang-tidy infinite-loop checker

2022-08-26 Thread Ziqing Luo via Phabricator via cfe-commits
This revision was not accepted when it landed; it landed in state "Needs 
Review".
This revision was automatically updated to reflect the committed changes.
Closed by commit rG9343ec861a2e: [clang-tidy] Adding the missing handling of 
"noreturn" attributes for Obj-C… (authored by ziqingluo-90).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128314

Files:
  clang-tools-extra/clang-tidy/bugprone/InfiniteLoopCheck.cpp
  clang-tools-extra/test/clang-tidy/checkers/bugprone/infinite-loop-noreturn.mm

Index: clang-tools-extra/test/clang-tidy/checkers/bugprone/infinite-loop-noreturn.mm
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone/infinite-loop-noreturn.mm
@@ -0,0 +1,62 @@
+// RUN: %check_clang_tidy %s bugprone-infinite-loop %t -- -- -fblocks -fexceptions
+// RUN: %check_clang_tidy %s bugprone-infinite-loop %t -- -- -fblocks -fobjc-arc -fexceptions
+
+@interface I
++ (void)foo;
++ (void)bar;
++ (void)baz __attribute__((noreturn));
++ (instancetype)alloc;
+- (instancetype)init;
+@end
+
+_Noreturn void term();
+
+void plainCFunction() {
+  int i = 0;
+  int j = 0;
+  int a[10];
+
+  while (i < 10) {
+// no warning, function term has C noreturn attribute
+term();
+  }
+  while (i < 10) {
+// no warning, class method baz has noreturn attribute
+[I baz];
+  }
+  while (i + j < 10) {
+// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: this loop is infinite; none of its condition variables (i, j) are updated in the loop body [bugprone-infinite-loop]
+[I foo];
+  }
+  while (i + j < 10) {
+[I foo];
+[I baz]; // no warning, class method baz has noreturn attribute
+  }
+
+  void (^block)() = ^{
+  };
+  void __attribute__((noreturn)) (^block_nr)(void) = ^void __attribute__((noreturn)) (void) { throw "err"; };
+
+  while (i < 10) {
+// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: this loop is infinite; none of its condition variables (i) are updated in the loop body [bugprone-infinite-loop]
+block();
+  }
+  while (i < 10) {
+// no warning, the block has "noreturn" arribute
+block_nr();
+  }
+}
+
+@implementation I
++ (void)bar {
+}
+
++ (void)foo {
+  static int i = 0;
+
+  while (i < 10) {
+// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: this loop is infinite; none of its condition variables (i) are updated in the loop body [bugprone-infinite-loop]
+[I bar];
+  }
+}
+@end
Index: clang-tools-extra/clang-tidy/bugprone/InfiniteLoopCheck.cpp
===
--- clang-tools-extra/clang-tidy/bugprone/InfiniteLoopCheck.cpp
+++ clang-tools-extra/clang-tidy/bugprone/InfiniteLoopCheck.cpp
@@ -16,15 +16,35 @@
 using clang::tidy::utils::hasPtrOrReferenceInFunc;
 
 namespace clang {
+namespace ast_matchers {
+/// matches a Decl if it has a  "no return" attribute of any kind
+AST_MATCHER(Decl, declHasNoReturnAttr) {
+  return Node.hasAttr() || Node.hasAttr() ||
+ Node.hasAttr();
+}
+
+/// matches a FunctionType if the type includes the GNU no return attribute
+AST_MATCHER(FunctionType, typeHasNoReturnAttr) {
+  return Node.getNoReturnAttr();
+}
+} // namespace ast_matchers
 namespace tidy {
 namespace bugprone {
 
 static internal::Matcher
 loopEndingStmt(internal::Matcher Internal) {
-  // FIXME: Cover noreturn ObjC methods (and blocks?).
+  internal::Matcher isNoReturnFunType =
+  ignoringParens(functionType(typeHasNoReturnAttr()));
+  internal::Matcher isNoReturnDecl =
+  anyOf(declHasNoReturnAttr(), functionDecl(hasType(isNoReturnFunType)),
+varDecl(hasType(blockPointerType(pointee(isNoReturnFunType);
+
   return stmt(anyOf(
   mapAnyOf(breakStmt, returnStmt, gotoStmt, cxxThrowExpr).with(Internal),
-  callExpr(Internal, callee(functionDecl(isNoReturn());
+  callExpr(Internal,
+   callee(mapAnyOf(functionDecl, /* block callee */ varDecl)
+  .with(isNoReturnDecl))),
+  objcMessageExpr(Internal, callee(isNoReturnDecl;
 }
 
 /// Return whether `Var` was changed in `LoopStmt`.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D132754: [clang] Add __is_target_variant_{os,environment} builtins

2022-08-26 Thread Hans Wennborg via Phabricator via cfe-commits
hans accepted this revision.
hans added a comment.
This revision is now accepted and ready to land.

lgtm


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

https://reviews.llvm.org/D132754

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


[clang] f886f7e - Remove unused private variable.

2022-08-26 Thread Sterling Augustine via cfe-commits

Author: Sterling Augustine
Date: 2022-08-26T12:43:05-07:00
New Revision: f886f7e8ef7aa4f54298db792a656373af90440c

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

LOG: Remove unused private variable.

Added: 


Modified: 
clang/lib/Driver/ToolChains/Cuda.cpp
clang/lib/Driver/ToolChains/Cuda.h

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Cuda.cpp 
b/clang/lib/Driver/ToolChains/Cuda.cpp
index 16c82de54aa3..4d9a473419d3 100644
--- a/clang/lib/Driver/ToolChains/Cuda.cpp
+++ b/clang/lib/Driver/ToolChains/Cuda.cpp
@@ -599,7 +599,7 @@ CudaToolChain::CudaToolChain(const Driver &D, const 
llvm::Triple &Triple,
  const ToolChain &HostTC, const ArgList &Args,
  const Action::OffloadKind OK)
 : ToolChain(D, Triple, Args), HostTC(HostTC),
-  CudaInstallation(D, HostTC.getTriple(), Args), OK(OK) {
+  CudaInstallation(D, HostTC.getTriple(), Args) {
   if (CudaInstallation.isValid()) {
 CudaInstallation.WarnIfUnsupportedVersion();
 getProgramPaths().push_back(std::string(CudaInstallation.getBinPath()));

diff  --git a/clang/lib/Driver/ToolChains/Cuda.h 
b/clang/lib/Driver/ToolChains/Cuda.h
index 997fdfbc44df..a51dcc2d5a20 100644
--- a/clang/lib/Driver/ToolChains/Cuda.h
+++ b/clang/lib/Driver/ToolChains/Cuda.h
@@ -188,9 +188,6 @@ class LLVM_LIBRARY_VISIBILITY CudaToolChain : public 
ToolChain {
 protected:
   Tool *buildAssembler() const override;  // ptxas
   Tool *buildLinker() const override; // fatbinary (ok, not really a 
linker)
-
-private:
-  const Action::OffloadKind OK;
 };
 
 } // end namespace toolchains



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


[clang] 5eab94f - Eliminate unused-variable warning.

2022-08-26 Thread Sterling Augustine via cfe-commits

Author: Sterling Augustine
Date: 2022-08-26T12:40:55-07:00
New Revision: 5eab94f7eb20c2f5d3123e7401892a1a6a133e38

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

LOG: Eliminate unused-variable warning.

Added: 


Modified: 
clang/lib/Frontend/SARIFDiagnostic.cpp

Removed: 




diff  --git a/clang/lib/Frontend/SARIFDiagnostic.cpp 
b/clang/lib/Frontend/SARIFDiagnostic.cpp
index d19426c91a3d..2bcbd5cf34f2 100644
--- a/clang/lib/Frontend/SARIFDiagnostic.cpp
+++ b/clang/lib/Frontend/SARIFDiagnostic.cpp
@@ -71,8 +71,7 @@ SarifResult SARIFDiagnostic::addLocationToResult(
 FileID FID = Loc.getFileID();
 if (FID.isValid()) {
   if (const FileEntry *FE = Loc.getFileEntry()) {
-llvm::StringRef Filename =
-emitFilename(FE->getName(), Loc.getManager());
+emitFilename(FE->getName(), Loc.getManager());
 // FIXME(llvm-project/issues/57366): File-only locations
   }
 }



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


[PATCH] D132398: Allow constant static members to be used with 'this'

2022-08-26 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: clang/lib/AST/ExprConstant.cpp:8458
+  Info.AccessingStaticConstantDataMember);
+  if(Info.InConstantContext)
+Info.AccessingStaticConstantDataMember = true;

When not in a constant-context, what should we be doing here? Why doesn't that 
set the variable?



Comment at: clang/lib/AST/ExprConstant.cpp:8460
+Info.AccessingStaticConstantDataMember = true;
   VisitIgnoredBaseExpression(E->getBase());
   return Success(MD);

Will this visit end up looking into OTHER things here?  I guess I'm concerned 
about something like:

`this->get_some_other_type().static_func()` and us skipping the `this->` for 
THAT, despite it not being a static call in that context.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132398

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


[PATCH] D132136: [clang] Perform implicit lvalue-to-rvalue cast with new interpreter

2022-08-26 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D132136#3751702 , @erichkeane 
wrote:

> Would be great if we had a better test here... is there anything we can do to 
> validate this is happening other than checking for that one note?

+1 to this request, but the changes themselves LGTM otherwise


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

https://reviews.llvm.org/D132136

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


[PATCH] D131632: [clang] Enable output of SARIF diagnostics

2022-08-26 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

This adds warnings:

  [498/568] CXX obj/clang/lib/Frontend/Frontend.SARIFDiagnostic.o
  ../../clang/lib/Frontend/SARIFDiagnostic.cpp:74:25: warning: unused variable 
'Filename' [-Wunused-variable]
  llvm::StringRef Filename =
  ^
  In file included from ../../clang/lib/Frontend/SARIFDiagnostic.cpp:9:
  ../../clang/include/clang/Frontend/SARIFDiagnostic.h:58:16: warning: private 
field 'OS' is not used [-Wunused-private-field]
raw_ostream &OS;
 ^


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131632

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


[PATCH] D132398: Allow constant static members to be used with 'this'

2022-08-26 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added reviewers: aaron.ballman, clang-language-wg.
aaron.ballman added a comment.

Thanks for this! Can you add some more details to the patch description so it's 
more clear from there why the patch is necessary? Also, can you add a release 
note for the fix?

I'm pretty sure the changes here are correct, but I want to take another run at 
the standards wording to be sure.




Comment at: clang/lib/AST/ExprConstant.cpp:931
 
+/// TODO: add doc.
+bool AccessingStaticConstantDataMember = false;

Add the docs?



Comment at: clang/lib/AST/ExprConstant.cpp:8741-8743
+  if (Info.AccessingStaticConstantDataMember) {
+return Success(E);
+  }





Comment at: clang/test/SemaCXX/cxx2a-consteval.cpp:925
+}
\ No newline at end of file


You should add a new line back to the end of the file.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132398

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


[PATCH] D132756: [clang][dataflow] Refactor `TypeErasedDataflowAnalysisTest` - replace usage of the deprecated overload of `checkDataflow`.

2022-08-26 Thread weiyi via Phabricator via cfe-commits
wyt created this revision.
Herald added subscribers: martong, xazax.hun.
Herald added a project: All.
wyt requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D132756

Files:
  clang/unittests/Analysis/FlowSensitive/TestingSupport.h
  clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
@@ -24,8 +24,10 @@
 #include "llvm/ADT/Optional.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallSet.h"
+#include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Error.h"
+#include "llvm/Testing/ADT/StringMapEntryMatcher.h"
 #include "llvm/Testing/Support/Error.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
@@ -42,12 +44,10 @@
 using namespace dataflow;
 using namespace test;
 using namespace ast_matchers;
-using ::testing::_;
-using ::testing::ElementsAre;
+using llvm::IsStringMapEntry;
+using ::testing::DescribeMatcher;
 using ::testing::IsEmpty;
-using ::testing::IsNull;
 using ::testing::NotNull;
-using ::testing::Pair;
 using ::testing::Test;
 using ::testing::UnorderedElementsAre;
 
@@ -129,7 +129,8 @@
 }
 
 struct FunctionCallLattice {
-  llvm::SmallSet CalledFunctions;
+  typedef llvm::SmallSet FunctionSet;
+  FunctionSet CalledFunctions;
 
   bool operator==(const FunctionCallLattice &Other) const {
 return CalledFunctions == Other.CalledFunctions;
@@ -195,16 +196,22 @@
 
 ASSERT_THAT_ERROR(
 test::checkDataflow(
-Code, "target",
-[](ASTContext &C, Environment &) {
-  return FunctionCallAnalysis(C);
+/*AI:AnalysisInputs=*/
+{
+.Code = Code,
+.TargetFuncMatcher = ast_matchers::hasName("target"),
+.MakeAnalysis =
+[](ASTContext &C, Environment &) {
+  return FunctionCallAnalysis(C);
+},
+.ASTBuildArgs = {"-fsyntax-only", "-std=c++17"},
+.ASTBuildVirtualMappedFiles = FilesContents,
 },
+/*VerifyResults=*/
 [&Expectations](
-llvm::ArrayRef>>
-Results,
-ASTContext &) { EXPECT_THAT(Results, Expectations); },
-{"-fsyntax-only", "-std=c++17"}, FilesContents),
+llvm::StringMap>
+&Results,
+AnalysisOutputs &) { EXPECT_THAT(Results, Expectations); }),
 llvm::Succeeded());
   }
 };
@@ -212,12 +219,16 @@
 MATCHER_P(HoldsFunctionCallLattice, m,
   ((negation ? "doesn't hold" : "holds") +
llvm::StringRef(" a lattice element that ") +
-   ::testing::DescribeMatcher(m, negation))
+   DescribeMatcher(m))
   .str()) {
   return ExplainMatchResult(m, arg.Lattice, result_listener);
 }
 
-MATCHER_P(HasCalledFunctions, m, "") {
+MATCHER_P(HasCalledFunctions, m,
+  ((negation ? "doesn't hold" : "holds") +
+   llvm::StringRef(" a set of called functions that ") +
+   DescribeMatcher(m))
+  .str()) {
   return ExplainMatchResult(m, arg.CalledFunctions, result_listener);
 }
 
@@ -231,9 +242,9 @@
   // [[p]]
 }
   )";
-  runDataflow(Code, UnorderedElementsAre(
-Pair("p", HoldsFunctionCallLattice(HasCalledFunctions(
-  UnorderedElementsAre("foo", "bar"));
+  runDataflow(Code, UnorderedElementsAre(IsStringMapEntry(
+"p", HoldsFunctionCallLattice(HasCalledFunctions(
+ UnorderedElementsAre("foo", "bar"));
 }
 
 TEST_F(NoreturnDestructorTest, ConditionalOperatorLeftBranchReturns) {
@@ -246,9 +257,9 @@
   // [[p]]
 }
   )";
-  runDataflow(Code, UnorderedElementsAre(
-Pair("p", HoldsFunctionCallLattice(HasCalledFunctions(
-  UnorderedElementsAre("foo"));
+  runDataflow(Code, UnorderedElementsAre(IsStringMapEntry(
+"p", HoldsFunctionCallLattice(HasCalledFunctions(
+ UnorderedElementsAre("foo"));
 }
 
 TEST_F(NoreturnDestructorTest, ConditionalOperatorRightBranchReturns) {
@@ -261,9 +272,9 @@
   // [[p]]
 }
   )";
-  runDataflow(Code, UnorderedElementsAre(
-Pair("p", HoldsFunctionCallLattice(HasCalledFunctions(
-  UnorderedElementsAre("foo"));
+  runDataflow(Code, UnorderedElementsAre(IsStringMapEntry(
+"p", HoldsFunctionCallLattice(HasCalledFunctions(
+  

[PATCH] D132754: [clang] Add __is_target_variant_{os,environment} builtins

2022-08-26 Thread Nico Weber via Phabricator via cfe-commits
thakis added inline comments.



Comment at: clang/lib/Lex/PPMacroExpansion.cpp:1713
   // FIXME: This is inconsistent; we usually suggest detecting
   // builtin macros via #ifdef. Don't add more cases here.
   .Case("__is_target_arch", true)

(I saw this comment, but system headers force our hand.)


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

https://reviews.llvm.org/D132754

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


[PATCH] D130513: [Flang] Add -fconvert option to swap endianness for unformatted files

2022-08-26 Thread Jonathon Penix via Phabricator via cfe-commits
jpenix-quic added inline comments.



Comment at: flang/runtime/environment-default-list.h:1
+//===-- Runtime/environment-default-list.h 
===//
+//

klausler wrote:
> If you want this header to be maximally portable C and C++, please observe 
> the usage of other such headers, and use old-school C /*comments*/.
> 
> You could probably just use an 'int' for the item count and avoid some 
> difficulty below, unless you expect a program to use billions of default 
> environment settings.
Done re: using an int!

Just to double check regarding C/C++ portability and looking at other headers, 
one that I was looking at was Decimal/decimal.h and the structs, etc. in that 
file are conditionally added to namespaces depending on whether it is C or C++. 
I was waffling on whether I should be doing that here though (I am not 
currently/was not previously) as keeping the type out of the namespace allows 
me to keep a consistent type/directly pass the pointer from Fortran_main.c to 
main.cpp/enviornment.cpp. But, as a result I'm also polluting the default 
namespace with EnvironmentDefaultList/Item for C++ code. Is how I have it 
currently ok, or would it be better to move the structs into namespaces for C++ 
and just cast to the correct type along the way? (Or, is there another option I 
am missing?)


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

https://reviews.llvm.org/D130513

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


[PATCH] D132754: [clang] Add __is_target_variant_{os,environment} builtins

2022-08-26 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

Another patch to make open-source clang more like Xcode's clang, needed to 
parse system headers.

https://github.com/nico/hack/blob/main/notes/catalyst.md has some background 
information on catalyst triples and zippered code.


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

https://reviews.llvm.org/D132754

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


[PATCH] D132754: [clang] Add __is_target_variant_{os,environment} builtins

2022-08-26 Thread Nico Weber via Phabricator via cfe-commits
thakis created this revision.
thakis added a reviewer: hans.
Herald added a subscriber: kristof.beyls.
Herald added a project: All.
thakis requested review of this revision.

Xcode 13's clang has them. For the included testcase, Xcode's clang
behaves like the implementation in this patch.

Availability.h in the macOS 12.0 SDK (part of Xcode 13, and the current
stable version of the macOS SDK) does something like:

  #if defined(__has_builtin)
...
#if __has_builtin(__is_target_os)
 #if __has_builtin(__is_target_environment)
  #if __has_builtin(__is_target_variant_os)
   #if __has_builtin(__is_target_variant_environment)
#if (... && ((__is_target_os(ios) && __is_target_environment(macabi)) 
|| (__is_target_variant_os(ios) && __is_target_variant_environment(macabi
  #define __OSX_AVAILABLE_STARTING(_osx, _ios) ...
  #define __OSX_AVAILABLE_BUT_DEPRECATED(_osxIntro, _osxDep, _iosIntro, 
_iosDep) ...
  #define __OSX_AVAILABLE_BUT_DEPRECATED_MSG(_osxIntro, _osxDep, 
_iosIntro, _iosDep, _msg) ...

So if __has_builtin(__is_target_variant_os) or
__has_builtin(__is_target_variant_environment) are false, these defines are not
defined.

Most of the time, this doesn't matter. But open-source clang currently fails
to commpile a file containing only `#include ` when
building for catalyst by adding a `-target arm64-apple-ios13.1-macabi` triple,
due to those __OSX_AVAILABLE macros not being set correctly.

If a potential future SDK version were to include cssmtype.h transitively
from a common header such as ``, then it would become
close to impossible to build Catalyst binaries with open-source clang.

To fix this for normal catalyst builds, it's only necessary that
__has_builtin() evaluates to true for these two built-ins -- the implementation
of them doesn't matter. But as a courtesy, a correct (at least on the test
cases I tried) implementation is provided. (This should also help people who
try to build zippered code, where having the correct implementation does
matter.)


https://reviews.llvm.org/D132754

Files:
  clang/include/clang/Lex/Preprocessor.h
  clang/lib/Lex/PPMacroExpansion.cpp
  clang/test/Preprocessor/is_target_unknown.c
  clang/test/Preprocessor/is_target_variant.c

Index: clang/test/Preprocessor/is_target_variant.c
===
--- /dev/null
+++ clang/test/Preprocessor/is_target_variant.c
@@ -0,0 +1,72 @@
+// RUN: %clang_cc1 -fsyntax-only -triple arm64-apple-macos -DMAC -verify %s
+// RUN: %clang_cc1 -fsyntax-only -triple arm64-apple-ios13.1 -DIOS -verify %s
+// RUN: %clang_cc1 -fsyntax-only -triple arm64-apple-ios13.1-macabi -DCATALYST -verify %s
+// RUN: %clang_cc1 -fsyntax-only -triple arm64-apple-macos12 -darwin-target-variant-triple arm64-apple-ios-macabi -DZIPPERED -verify %s
+// expected-no-diagnostics
+
+#if !__has_builtin(__is_target_variant_os) || !__has_builtin(__is_target_variant_environment)
+  #error "has builtin doesn't work"
+#endif
+
+#ifdef ZIPPERED
+
+  // Target variant is a darwin.
+  #if !__is_target_variant_os(darwin)
+#error "mismatching variant os"
+  #endif
+
+  // Target variant is not macOS...
+  #if __is_target_variant_os(macos)
+#error "mismatching variant os"
+  #endif
+
+  // ...but iOS.
+  #if !__is_target_variant_os(ios)
+#error "mismatching variant os"
+  #endif
+
+  // Zippered builds also set the target variant environment to macabi.
+  // At the moment, only zippered builds set __is_target_variant_os(ios),
+  // so checking __is_target_variant_environment() is currently redundant
+  // with checking the former.
+  #if !__is_target_variant_environment(macabi)
+#error "mismatching variant environment"
+  #endif
+
+#else
+
+  // In non-zippered builds, even for catalyst, no target variant is set.
+  // So these are all false.
+
+  #if __is_target_variant_os(darwin)
+#error "mismatching variant os"
+  #endif
+
+  #if __is_target_variant_os(macos)
+#error "mismatching variant os"
+  #endif
+
+  #if __is_target_variant_os(ios)
+#error "mismatching variant os"
+  #endif
+
+  #if __is_target_variant_environment(macabi)
+#error "mismatching variant environment"
+  #endif
+
+#endif
+
+// The target environment in zippered builds is _not_ macabi.
+// The target environment is macabi only in catalyst builds.
+#ifdef CATALYST
+  #if !__is_target_environment(macabi)
+#error "mismatching environment"
+  #endif
+  #if !__is_target_os(ios)
+#error "mismatching os"
+  #endif
+#else
+  #if __is_target_environment(macabi)
+#error "mismatching environment"
+  #endif
+#endif
Index: clang/test/Preprocessor/is_target_unknown.c
===
--- clang/test/Preprocessor/is_target_unknown.c
+++ clang/test/Preprocessor/is_target_unknown.c
@@ -20,3 +20,13 @@
 #if !__is_target_environment(unknown)
   #error "mismatching environment"
 #endif
+
+// Unknown variant OS is not allowed.
+#if __is_

[PATCH] D131009: [analyzer] Fixing a bug raising false positives of stack block object leaking under ARC

2022-08-26 Thread Ziqing Luo via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGa5e354ec4da1: [analyzer] Fixing a bug raising false 
positives of stack block object (authored by ziqingluo-90).

Changed prior to commit:
  https://reviews.llvm.org/D131009?vs=453144&id=455992#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131009

Files:
  clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
  clang/lib/StaticAnalyzer/Core/MemRegion.cpp
  clang/test/Analysis/stack-capture-leak-arc.mm
  clang/test/Analysis/stack-capture-leak-no-arc.mm

Index: clang/test/Analysis/stack-capture-leak-no-arc.mm
===
--- clang/test/Analysis/stack-capture-leak-no-arc.mm
+++ clang/test/Analysis/stack-capture-leak-no-arc.mm
@@ -4,6 +4,7 @@
 typedef void (^dispatch_block_t)(void);
 void dispatch_async(dispatch_queue_t queue, dispatch_block_t block);
 extern dispatch_queue_t queue;
+void f(int);
 
 void test_block_inside_block_async_no_leak() {
   int x = 123;
@@ -35,3 +36,46 @@
   return outer; // expected-warning-re{{Address of stack-allocated block declared on line {{.+}} is captured by a returned block}}
 }
 
+// The block literal defined in this function could leak once being
+// called.
+void output_block(dispatch_block_t * blk) {
+  int x = 0;
+  *blk = ^{ f(x); }; // expected-warning {{Address of stack-allocated block declared on line 43 is still referred to by the stack variable 'blk' upon returning to the caller.  This will be a dangling reference [core.StackAddressEscape]}}
+}
+
+// The block literal captures nothing thus is treated as a constant.
+void output_constant_block(dispatch_block_t * blk) {
+  *blk = ^{ };
+}
+
+// A block can leak if it captures at least one variable and is not
+// under ARC when its' stack frame expires.
+void test_block_leak() {
+  __block dispatch_block_t blk;
+  int x = 0;
+  dispatch_block_t p = ^{
+blk = ^{ // expected-warning {{Address of stack-allocated block declared on line 57 is still referred to by the stack variable 'blk' upon returning to the caller.  This will be a dangling reference [core.StackAddressEscape]}}
+  f(x);
+};
+  };
+
+  p();
+  blk();
+  output_block(&blk);
+  blk();
+}
+
+// A block captures nothing is a constant thus never leaks.
+void test_constant_block_no_leak() {
+  __block dispatch_block_t blk;
+  dispatch_block_t p = ^{
+blk = ^{
+  f(0);
+};
+  };
+  
+  p();
+  blk();
+  output_constant_block(&blk);
+  blk();
+}
Index: clang/test/Analysis/stack-capture-leak-arc.mm
===
--- clang/test/Analysis/stack-capture-leak-arc.mm
+++ clang/test/Analysis/stack-capture-leak-arc.mm
@@ -8,6 +8,7 @@
 typedef long dispatch_time_t;
 void dispatch_after(dispatch_time_t when, dispatch_queue_t queue, dispatch_block_t block);
 void dispatch_barrier_sync(dispatch_queue_t queue, dispatch_block_t block);
+void f(int);
 
 extern dispatch_queue_t queue;
 extern dispatch_once_t *predicate;
@@ -187,3 +188,40 @@
   }
   dispatch_barrier_sync(queue, ^{});
 }
+
+void output_block(dispatch_block_t * blk) {
+  int x = 0;
+  *blk = ^{ f(x); };
+}
+
+// Block objects themselves can never leak under ARC.
+void test_no_block_leak() {
+  __block dispatch_block_t blk;
+  int x = 0;
+  dispatch_block_t p = ^{
+blk = ^{
+  f(x);
+};
+  };
+  p();
+  blk();
+  output_block(&blk);
+  blk();
+}
+
+// Block objects do not leak under ARC but stack variables of
+// non-object kind indirectly referred by a block can leak.
+dispatch_block_t test_block_referencing_variable_leak() {
+  int x = 0;
+  __block int * p = &x;
+  __block int * q = &x;
+  
+  dispatch_async(queue, ^{// expected-warning {{Address of stack memory associated with local variable 'x' is captured by an asynchronously-executed block \
+[alpha.core.StackAddressAsyncEscape]}}
+  ++(*p);
+});
+  return (dispatch_block_t) ^{// expected-warning {{Address of stack memory associated with local variable 'x' is captured by a returned block \
+[core.StackAddressEscape]}}
+++(*q);
+  };
+}
Index: clang/lib/StaticAnalyzer/Core/MemRegion.cpp
===
--- clang/lib/StaticAnalyzer/Core/MemRegion.cpp
+++ clang/lib/StaticAnalyzer/Core/MemRegion.cpp
@@ -1076,14 +1076,18 @@
 sReg = getGlobalsRegion(MemRegion::GlobalImmutableSpaceRegionKind);
   }
   else {
-if (LC) {
+bool IsArcManagedBlock = Ctx.getLangOpts().ObjCAutoRefCount;
+
+// ARC managed blocks can be initialized on stack or directly in heap
+// depending on the implementations.  So we initialize them with
+// UnknownRegion.
+if (!IsArcManagedBlock && LC) {
   // FIXME: Once we implement scope handling, we want the parent region
   // to be the scope.
   const StackFrameContext *STC = LC->getStackFrame();
   assert(STC);
 

[clang] a5e354e - [analyzer] Fixing a bug raising false positives of stack block object

2022-08-26 Thread via cfe-commits

Author: ziqingluo-90
Date: 2022-08-26T12:19:32-07:00
New Revision: a5e354ec4da14cfc02b9847be314524e8deb93c6

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

LOG: [analyzer] Fixing a bug raising false positives of stack block object
leaking in ARC mode

When ARC (automatic reference count) is enabled, (objective-c) block
objects are automatically retained and released thus they do not leak.
Without ARC, they still can leak from an expiring stack frame like
other stack variables.
With this commit, the static analyzer now puts a block object in an
"unknown" region if ARC is enabled because it is up to the
implementation to choose whether to put the object on stack initially
(then move to heap when needed) or in heap directly under ARC.
Therefore, the `StackAddrEscapeChecker` has no need to know
specifically about ARC at all and it will not report errors on objects
in "unknown" regions.

Reviewed By: NoQ (Artem Dergachev)

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

Added: 


Modified: 
clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
clang/lib/StaticAnalyzer/Core/MemRegion.cpp
clang/test/Analysis/stack-capture-leak-arc.mm
clang/test/Analysis/stack-capture-leak-no-arc.mm

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
index e6cea0fbff8cd..c4b7411e94011 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
@@ -61,7 +61,6 @@ class StackAddrEscapeChecker
  ASTContext &Ctx);
   static SmallVector
   getCapturedStackRegions(const BlockDataRegion &B, CheckerContext &C);
-  static bool isArcManagedBlock(const MemRegion *R, CheckerContext &C);
   static bool isNotInCurrentFrame(const MemRegion *R, CheckerContext &C);
 };
 } // namespace
@@ -110,13 +109,6 @@ SourceRange StackAddrEscapeChecker::genName(raw_ostream 
&os, const MemRegion *R,
   return range;
 }
 
-bool StackAddrEscapeChecker::isArcManagedBlock(const MemRegion *R,
-   CheckerContext &C) {
-  assert(R && "MemRegion should not be null");
-  return C.getASTContext().getLangOpts().ObjCAutoRefCount &&
- isa(R);
-}
-
 bool StackAddrEscapeChecker::isNotInCurrentFrame(const MemRegion *R,
  CheckerContext &C) {
   const StackSpaceRegion *S = cast(R->getMemorySpace());
@@ -214,7 +206,7 @@ void 
StackAddrEscapeChecker::checkAsyncExecutedBlockCaptures(
 void StackAddrEscapeChecker::checkReturnedBlockCaptures(
 const BlockDataRegion &B, CheckerContext &C) const {
   for (const MemRegion *Region : getCapturedStackRegions(B, C)) {
-if (isArcManagedBlock(Region, C) || isNotInCurrentFrame(Region, C))
+if (isNotInCurrentFrame(Region, C))
   continue;
 ExplodedNode *N = C.generateNonFatalErrorNode();
 if (!N)
@@ -267,8 +259,7 @@ void StackAddrEscapeChecker::checkPreStmt(const ReturnStmt 
*RS,
   if (const BlockDataRegion *B = dyn_cast(R))
 checkReturnedBlockCaptures(*B, C);
 
-  if (!isa(R->getMemorySpace()) ||
-  isNotInCurrentFrame(R, C) || isArcManagedBlock(R, C))
+  if (!isa(R->getMemorySpace()) || isNotInCurrentFrame(R, C))
 return;
 
   // Returning a record by value is fine. (In this case, the returned
@@ -348,8 +339,7 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
   // Check the globals for the same.
   if (!isa(Region->getMemorySpace()))
 return true;
-  if (VR && VR->hasStackStorage() && !isArcManagedBlock(VR, Ctx) &&
-  !isNotInCurrentFrame(VR, Ctx))
+  if (VR && VR->hasStackStorage() && !isNotInCurrentFrame(VR, Ctx))
 V.emplace_back(Region, VR);
   return true;
 }

diff  --git a/clang/lib/StaticAnalyzer/Core/MemRegion.cpp 
b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp
index bb64cbc4b71c4..482862a23030a 100644
--- a/clang/lib/StaticAnalyzer/Core/MemRegion.cpp
+++ b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp
@@ -1076,14 +1076,18 @@ MemRegionManager::getBlockDataRegion(const 
BlockCodeRegion *BC,
 sReg = getGlobalsRegion(MemRegion::GlobalImmutableSpaceRegionKind);
   }
   else {
-if (LC) {
+bool IsArcManagedBlock = Ctx.getLangOpts().ObjCAutoRefCount;
+
+// ARC managed blocks can be initialized on stack or directly in heap
+// depending on the implementations.  So we initialize them with
+// UnknownRegion.
+if (!IsArcManagedBlock && LC) {
   // FIXME: Once we implement scope handling, we want the parent region
   // to be the scope.
   const StackFrameContext *STC = LC->getStackFrame();
   assert(STC);
   sReg = getStackLocalsRegi

[PATCH] D132425: [clang] Do not instrument relative vtables under hwasan

2022-08-26 Thread Mitch Phillips via Phabricator via cfe-commits
hctim added a comment.

Glad to see that refactoring the sanitizer metadata made someone's life easier 
;) (now allowing for disabling hwasanificiation of globals)

Patch looks reasonable to me. Can you please add the negative test (that 
vtables under the vanilla ABI still have hwasan)?

I wans't fully aware of the relative vtables ABI, and it may have some 
implications about MTE globals tagging (draft abi 
).
 Because logical tags are synthesized at runtime into a synthetic GOT entry - 
dynamic relocations I believe would be forced (removing any benefit of the 
relative vtables ABI), so for now it seems like MTE globals and relative 
vtables are mutually exclusive. Another option would be to disable MTE globals 
for relative vtables as well. No action needed on your part, just putting some 
wordso n paper that this might need some consideration at a later date if 
Fuchsia wants to support MTE globals.




Comment at: 
clang/test/CodeGenCXX/RelativeVTablesABI/relative-vtables-hwasan.cpp:1
+// RUN: %clang_cc1 %s -triple=aarch64-unknown-fuchsia -S -o - -emit-llvm 
-fsanitize=hwaddress | FileCheck %s
+

Can you add a note here that `-triple=aarch64-unknown-fuchsia` has implicit 
relative vtables


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132425

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


[PATCH] D130020: [OpenMP] Deprecate the old driver for OpenMP offloading

2022-08-26 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

ps: Thank you to everyone who's been working on having fewer offload wrapper 
binaries!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130020

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


[PATCH] D130020: [OpenMP] Deprecate the old driver for OpenMP offloading

2022-08-26 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 added a comment.

In D130020#3752458 , @thakis wrote:

> This caused:
>
>   In file included from ../../clang/lib/Driver/ToolChains/Cuda.cpp:9:
>   ../../clang/lib/Driver/ToolChains/Cuda.h:193:29: warning: private field 
> 'OK' is not used [-Wunused-private-field]
> const Action::OffloadKind OK;
>   ^

Thanks for bringing this to my attention, it should be an easy fix.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130020

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


[PATCH] D130020: [OpenMP] Deprecate the old driver for OpenMP offloading

2022-08-26 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

This caused:

  In file included from ../../clang/lib/Driver/ToolChains/Cuda.cpp:9:
  ../../clang/lib/Driver/ToolChains/Cuda.h:193:29: warning: private field 'OK' 
is not used [-Wunused-private-field]
const Action::OffloadKind OK;
  ^


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130020

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


[PATCH] D130513: [Flang] Add -fconvert option to swap endianness for unformatted files

2022-08-26 Thread Jonathon Penix via Phabricator via cfe-commits
jpenix-quic updated this revision to Diff 455975.
jpenix-quic added a comment.

Fixed up/simplified environment-default-list.h for C/C++ compatibility. Also 
cleaned up a declaration and a few autos in the lowering component. Rebased.


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

https://reviews.llvm.org/D130513

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Flang.cpp
  flang/examples/external-hello.cpp
  flang/include/flang/Frontend/FrontendOptions.h
  flang/include/flang/Lower/Bridge.h
  flang/include/flang/Optimizer/Builder/Runtime/EnvironmentDefaults.h
  flang/include/flang/Optimizer/Support/InternalNames.h
  flang/include/flang/Runtime/environment-defaults.h
  flang/include/flang/Runtime/main.h
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/lib/Lower/Bridge.cpp
  flang/lib/Optimizer/Builder/CMakeLists.txt
  flang/lib/Optimizer/Builder/Runtime/EnvironmentDefaults.cpp
  flang/lib/Optimizer/Support/InternalNames.cpp
  flang/runtime/FortranMain/Fortran_main.c
  flang/runtime/environment-default-list.h
  flang/runtime/environment.cpp
  flang/runtime/environment.h
  flang/runtime/main.cpp
  flang/test/Driver/convert.f90
  flang/test/Driver/driver-help-hidden.f90
  flang/test/Driver/driver-help.f90
  flang/test/Driver/emit-mlir.f90
  flang/test/Driver/frontend-forwarding.f90
  flang/test/Lower/convert.f90
  flang/test/Lower/environment-defaults.f90
  flang/test/Runtime/no-cpp-dep.c
  flang/tools/bbc/bbc.cpp
  flang/unittests/Runtime/CommandTest.cpp
  flang/unittests/Runtime/Stop.cpp

Index: flang/unittests/Runtime/Stop.cpp
===
--- flang/unittests/Runtime/Stop.cpp
+++ flang/unittests/Runtime/Stop.cpp
@@ -26,7 +26,8 @@
 
 TEST(TestProgramEnd, StopTestNoStopMessage) {
   putenv(const_cast("NO_STOP_MESSAGE=1"));
-  Fortran::runtime::executionEnvironment.Configure(0, nullptr, nullptr);
+  Fortran::runtime::executionEnvironment.Configure(
+  0, nullptr, nullptr, nullptr);
   EXPECT_EXIT(
   RTNAME(StopStatement)(), testing::ExitedWithCode(EXIT_SUCCESS), "");
 }
@@ -52,7 +53,8 @@
 
 TEST(TestProgramEnd, NoStopMessageTest) {
   putenv(const_cast("NO_STOP_MESSAGE=1"));
-  Fortran::runtime::executionEnvironment.Configure(0, nullptr, nullptr);
+  Fortran::runtime::executionEnvironment.Configure(
+  0, nullptr, nullptr, nullptr);
   static const char *message{"bye bye"};
   EXPECT_EXIT(RTNAME(StopStatementText)(message, std::strlen(message),
   /*isErrorStop=*/false, /*quiet=*/false),
Index: flang/unittests/Runtime/CommandTest.cpp
===
--- flang/unittests/Runtime/CommandTest.cpp
+++ flang/unittests/Runtime/CommandTest.cpp
@@ -49,7 +49,7 @@
 class CommandFixture : public ::testing::Test {
 protected:
   CommandFixture(int argc, const char *argv[]) {
-RTNAME(ProgramStart)(argc, argv, {});
+RTNAME(ProgramStart)(argc, argv, {}, {});
   }
 
   std::string GetPaddedStr(const char *text, std::size_t len) const {
Index: flang/tools/bbc/bbc.cpp
===
--- flang/tools/bbc/bbc.cpp
+++ flang/tools/bbc/bbc.cpp
@@ -222,7 +222,7 @@
   auto burnside = Fortran::lower::LoweringBridge::create(
   ctx, semanticsContext, defKinds, semanticsContext.intrinsics(),
   semanticsContext.targetCharacteristics(), parsing.allCooked(), "",
-  kindMap, loweringOptions);
+  kindMap, loweringOptions, {});
   burnside.lower(parseTree, semanticsContext);
   mlir::ModuleOp mlirModule = burnside.getModule();
   std::error_code ec;
Index: flang/test/Runtime/no-cpp-dep.c
===
--- flang/test/Runtime/no-cpp-dep.c
+++ flang/test/Runtime/no-cpp-dep.c
@@ -16,18 +16,20 @@
 we're testing. We can't include any headers directly since they likely contain
 C++ code that would explode here.
 */
+struct EnvironmentDefaultList;
 struct Descriptor;
 
 double RTNAME(CpuTime)();
 
-void RTNAME(ProgramStart)(int, const char *[], const char *[]);
+void RTNAME(ProgramStart)(
+int, const char *[], const char *[], const struct EnvironmentDefaultList *);
 int32_t RTNAME(ArgumentCount)();
 int32_t RTNAME(GetCommandArgument)(int32_t, const struct Descriptor *,
 const struct Descriptor *, const struct Descriptor *);
 
 int main() {
   double x = RTNAME(CpuTime)();
-  RTNAME(ProgramStart)(0, 0, 0);
+  RTNAME(ProgramStart)(0, 0, 0, 0);
   int32_t c = RTNAME(ArgumentCount)();
   int32_t v = RTNAME(GetCommandArgument)(0, 0, 0, 0);
   return x + c + v;
Index: flang/test/Lower/environment-defaults.f90
===
--- /dev/null
+++ flang/test/Lower/environment-defaults.f90
@@ -0,0 +1,11 @@
+! RUN: bbc -emit-fir -o - %s | FileCheck %s
+
+program test
+  continue
+end
+
+! Test that a null pointer is generated for environment defaults 

[PATCH] D132672: [Docs] [HLSL] Documenting HLSL Entry Functions

2022-08-26 Thread Chris Bieneman via Phabricator via cfe-commits
beanz updated this revision to Diff 455985.
beanz added a comment.

Updating based on feedback.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132672

Files:
  clang/docs/HLSL/EntryFunctions.rst
  clang/docs/HLSL/HLSLDocs.rst


Index: clang/docs/HLSL/HLSLDocs.rst
===
--- clang/docs/HLSL/HLSLDocs.rst
+++ clang/docs/HLSL/HLSLDocs.rst
@@ -12,3 +12,4 @@
:maxdepth: 1
 
ResourceTypes
+   EntryFunctions
Index: clang/docs/HLSL/EntryFunctions.rst
===
--- /dev/null
+++ clang/docs/HLSL/EntryFunctions.rst
@@ -0,0 +1,65 @@
+
+HLSL Entry Functions
+
+
+.. contents::
+   :local:
+
+Usage
+=
+
+In HLSL, entry functions denote the starting point for shader execution. They
+must be known at compile time. For all non-library shaders, the compiler 
assumes
+the default entry function name ``main``, unless the DXC ``/E`` option is
+provided to specify an alternate entry point. For library shaders entry points
+are denoted using the ``[shader(...)]`` attribute.
+
+All scalar parameters to entry functions must have semantic annotations, and 
all
+struct parameters must have semantic annotations on every field in the struct
+declaration. Additionally if the entry function has a return type, a semantic
+annotation must be provided for the return type as well.
+
+HLSL entry functions can be called from other parts of the shader, which has
+implications on code generation.
+
+Implementation Details
+==
+
+In Clang, the DXC ``/E`` option is translated to the cc1 flag ``-hlsl-entry``,
+which in turn applies the ``HLSLShader`` attribute to the function with the
+specified name. This allows code generation for entry functions to always key
+off the presence of the ``HLSLShader`` attribute, regardless of what shader
+profile you are compiling.
+
+In code generation, two functions are generated. One is the user defined
+function, which is code generated as a mangled C++ function with internal
+linkage following normal function code generation.
+
+The actual exported entry function which can be called by the GPU driver is a
+``void(void)`` function that isn't name mangled. In code generation we generate
+the unmangled entry function, instantiations of the parameters with their
+semantic values populated, and a call to the user-defined function. After the
+call instruction the return value (if any) is saved using a target-appropriate
+intrinsic for storing outputs (for DirectX, the ``llvm.dx.store.output``).
+
+.. note::
+
+   HLSL support in Clang is currently focused on compute shaders, which do not
+   support output semantics. Support for output semantics will not be
+   implemented until other shader profiles are supported.
+
+Below is example IR that represents the planned implementation, subject to
+change as the ``llvm.dx.store.output`` and ``llvm.dx.load.input`` intrinsics 
are
+not yet implemented.
+
+.. code-block:: none
+
+   ; Function Attrs: norecurse
+   define void @main() #1 {
+  entry:
+  %0 = call i32 @llvm.dx.load.input.i32(...)
+  %1 = call i32 @"?main@@YAXII@Z"(i32 %0)
+  call @llvm.dx.store.output.i32(%1, ...)
+  ret void
+   }
+


Index: clang/docs/HLSL/HLSLDocs.rst
===
--- clang/docs/HLSL/HLSLDocs.rst
+++ clang/docs/HLSL/HLSLDocs.rst
@@ -12,3 +12,4 @@
:maxdepth: 1
 
ResourceTypes
+   EntryFunctions
Index: clang/docs/HLSL/EntryFunctions.rst
===
--- /dev/null
+++ clang/docs/HLSL/EntryFunctions.rst
@@ -0,0 +1,65 @@
+
+HLSL Entry Functions
+
+
+.. contents::
+   :local:
+
+Usage
+=
+
+In HLSL, entry functions denote the starting point for shader execution. They
+must be known at compile time. For all non-library shaders, the compiler assumes
+the default entry function name ``main``, unless the DXC ``/E`` option is
+provided to specify an alternate entry point. For library shaders entry points
+are denoted using the ``[shader(...)]`` attribute.
+
+All scalar parameters to entry functions must have semantic annotations, and all
+struct parameters must have semantic annotations on every field in the struct
+declaration. Additionally if the entry function has a return type, a semantic
+annotation must be provided for the return type as well.
+
+HLSL entry functions can be called from other parts of the shader, which has
+implications on code generation.
+
+Implementation Details
+==
+
+In Clang, the DXC ``/E`` option is translated to the cc1 flag ``-hlsl-entry``,
+which in turn applies the ``HLSLShader`` attribute to the function with the
+specified name. This allows code generation for entry functions to always key
+off the 

[PATCH] D132749: Expose QualType::getUnqualifiedType in libclang

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

In D132749#3752233 , @diseraluca 
wrote:

> I found a precedence on the old mailing list, from 2018 
> (https://lists.llvm.org/pipermail/cfe-dev/2018-February/056874.html), for a 
> similar request, where it seemed it wouldn't be disruptive to expose it to 
> libclang.

Yup! FWIW, we will add things to libclang as people say they found a need for 
them (we do similar for AST matchers). We mostly just want to avoid trying to 
expose all of the APIs through a C interface, as that causes significant 
maintenance burden given how rapidly our APIs change.

> This is my first contribution to llvm-project, so I apologize if I missed 
> some requirement or pushed a patch that is incorrect. 
> I'm obviously open to spend more time on this patch if there is something 
> that should be modified.

Welcome to the community!

> Originally the patch contained the addition of `clang_getNonReferenceType` 
> too, as that is something else that we would like to have access to.

That seems perfectly reasonable to me as well.

> I avoided including it into this patch because:
>
> - As I understand it, having both in one patch would not comply with the 
> isolated changes requirement in 
> https://www.llvm.org/docs/Contributing.html#how-to-submit-a-patch.
> - I could not find any precedence for requesting that specific interface and 
> am unsure if the correct etiquette requires that a discussion is opened 
> BEFORE pushing this kind of patch.
> - First pushing a smaller patch would allow me to get accustomed to the 
> contributing workflow and understand what I might have done incorrectly, so 
> as to push an higher quality patch.
>
> Any clarification on if a patch that exposes `getNonReferencedType` requires 
> a discussion to be opened before being pushed for acceptance and review is 
> appreciated.

Feel free to put up a new review for that and add me as a reviewer, I'm happy 
to look at it. It should be a separate patch because we like to keep patches 
logically separate in case we need to revert something (no sense in losing all 
the good changes along with the bad by sticking them all in one patch). It's 
also far easier to review a patch without a lot of moving parts to it.

In terms of this patch, it looks good to me, but can you add a release note for 
the improvement? (We have a section for `libclang` that this should go under.) 
Once you post the patch with the release note, I'm happy to land this on your 
behalf (assuming precommit CI doesn't find any surprises I missed). What name 
and email address would you like used for patch attribution?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132749

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


[clang] 82e893c - [clang] Enable output of SARIF diagnostics

2022-08-26 Thread Christopher Di Bella via cfe-commits

Author: Abraham Corea Diaz
Date: 2022-08-26T18:49:29Z
New Revision: 82e893c47c77430ca59f92d7a814a336e3873a35

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

LOG: [clang] Enable output of SARIF diagnostics

Enables Clang to emit diagnostics in SARIF format when
`-fdiagnostics-format=sarif`. Adds a new DiagnosticConsumer named
SARIFDiagnosticPrinter and a new DiagnosticRenderer named SARIFDiagnostic
to constuct and emit a SARIF object containing the run's basic diagnostic info.

Reviewed By: cjdb, denik, aaron.ballman

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

Added: 
clang/include/clang/Frontend/SARIFDiagnostic.h
clang/include/clang/Frontend/SARIFDiagnosticPrinter.h
clang/lib/Frontend/SARIFDiagnostic.cpp
clang/lib/Frontend/SARIFDiagnosticPrinter.cpp
clang/test/Frontend/sarif-diagnostics.cpp

Modified: 
clang/lib/Frontend/CMakeLists.txt
clang/lib/Frontend/CompilerInstance.cpp
clang/lib/Frontend/FrontendAction.cpp

Removed: 




diff  --git a/clang/include/clang/Frontend/SARIFDiagnostic.h 
b/clang/include/clang/Frontend/SARIFDiagnostic.h
new file mode 100644
index 0..bd0f1df9aa58f
--- /dev/null
+++ b/clang/include/clang/Frontend/SARIFDiagnostic.h
@@ -0,0 +1,76 @@
+//===--- SARIFDiagnostic.h - SARIF Diagnostic Formatting -*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// This is a utility class that provides support for constructing a SARIF 
object
+// containing diagnostics.
+//
+//===--===//
+
+#ifndef LLVM_CLANG_FRONTEND_SARIFDIAGNOSTIC_H
+#define LLVM_CLANG_FRONTEND_SARIFDIAGNOSTIC_H
+
+#include "clang/Basic/Sarif.h"
+#include "clang/Frontend/DiagnosticRenderer.h"
+#include "llvm/ADT/StringRef.h"
+
+namespace clang {
+
+class SARIFDiagnostic : public DiagnosticRenderer {
+public:
+  SARIFDiagnostic(raw_ostream &OS, const LangOptions &LangOpts,
+  DiagnosticOptions *DiagOpts, SarifDocumentWriter *Writer);
+
+  ~SARIFDiagnostic() = default;
+
+  SARIFDiagnostic &operator=(const SARIFDiagnostic &&) = delete;
+  SARIFDiagnostic(SARIFDiagnostic &&) = delete;
+  SARIFDiagnostic &operator=(const SARIFDiagnostic &) = delete;
+  SARIFDiagnostic(const SARIFDiagnostic &) = delete;
+
+protected:
+  void emitDiagnosticMessage(FullSourceLoc Loc, PresumedLoc PLoc,
+ DiagnosticsEngine::Level Level, StringRef Message,
+ ArrayRef Ranges,
+ DiagOrStoredDiag D) override;
+
+  void emitDiagnosticLoc(FullSourceLoc Loc, PresumedLoc PLoc,
+ DiagnosticsEngine::Level Level,
+ ArrayRef Ranges) override;
+
+  void emitCodeContext(FullSourceLoc Loc, DiagnosticsEngine::Level Level,
+   SmallVectorImpl &Ranges,
+   ArrayRef Hints) override {}
+
+  void emitIncludeLocation(FullSourceLoc Loc, PresumedLoc PLoc) override;
+
+  void emitImportLocation(FullSourceLoc Loc, PresumedLoc PLoc,
+  StringRef ModuleName) override;
+
+  void emitBuildingModuleLocation(FullSourceLoc Loc, PresumedLoc PLoc,
+  StringRef ModuleName) override;
+
+private:
+  raw_ostream &OS;
+
+  // Shared between SARIFDiagnosticPrinter and this renderer.
+  SarifDocumentWriter *Writer;
+
+  SarifResult addLocationToResult(SarifResult Result, FullSourceLoc Loc,
+  PresumedLoc PLoc,
+  ArrayRef Ranges,
+  const Diagnostic &Diag);
+
+  SarifRule addDiagnosticLevelToRule(SarifRule Rule,
+ DiagnosticsEngine::Level Level);
+
+  llvm::StringRef emitFilename(StringRef Filename, const SourceManager &SM);
+};
+
+} // end namespace clang
+
+#endif

diff  --git a/clang/include/clang/Frontend/SARIFDiagnosticPrinter.h 
b/clang/include/clang/Frontend/SARIFDiagnosticPrinter.h
new file mode 100644
index 0..f2652833b3c18
--- /dev/null
+++ b/clang/include/clang/Frontend/SARIFDiagnosticPrinter.h
@@ -0,0 +1,76 @@
+//===-- SARIFDiagnosticPrinter.h - SARIF Diagnostic Client ---*- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// This 

[PATCH] D131632: [clang] Enable output of SARIF diagnostics

2022-08-26 Thread Christopher Di Bella via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG82e893c47c77: [clang] Enable output of SARIF diagnostics 
(authored by abrahamcd, committed by cjdb).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131632

Files:
  clang/include/clang/Frontend/SARIFDiagnostic.h
  clang/include/clang/Frontend/SARIFDiagnosticPrinter.h
  clang/lib/Frontend/CMakeLists.txt
  clang/lib/Frontend/CompilerInstance.cpp
  clang/lib/Frontend/FrontendAction.cpp
  clang/lib/Frontend/SARIFDiagnostic.cpp
  clang/lib/Frontend/SARIFDiagnosticPrinter.cpp
  clang/test/Frontend/sarif-diagnostics.cpp

Index: clang/test/Frontend/sarif-diagnostics.cpp
===
--- /dev/null
+++ clang/test/Frontend/sarif-diagnostics.cpp
@@ -0,0 +1,28 @@
+// RUN: %clang -fsyntax-only -Wall -Wextra -fdiagnostics-format=sarif %s > %t 2>&1 || true
+// RUN: FileCheck -dump-input=always %s --input-file=%t
+// CHECK: warning: diagnostic formatting in SARIF mode is currently unstable [-Wsarif-format-unstable]
+// CHECK: {"$schema":"https://docs.oasis-open.org/sarif/sarif/v2.1.0/cos02/schemas/sarif-schema-2.1.0.json","runs":[{"artifacts":[{"length":
+// Omit exact length of this file
+// CHECK: ,"location":{"index":0,"uri":"file://
+// Omit filepath to llvm project directory
+// CHECK: clang/test/Frontend/sarif-diagnostics.cpp"},"mimeType":"text/plain","roles":["resultFile"]}],"columnKind":"unicodeCodePoints","results":[{"level":"error","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":1,"startColumn":1,"startLine":12}}}],"message":{"text":"'main' must return 'int'"},"ruleId":"3465","ruleIndex":0},{"level":"error","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":11,"startColumn":11,"startLine":13}}}],"message":{"text":"use of undeclared identifier 'hello'"},"ruleId":"4604","ruleIndex":1},{"level":"error","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":17,"startColumn":17,"startLine":15}}}],"message":{"text":"invalid digit 'a' in decimal constant"},"ruleId":"898","ruleIndex":2},{"level":"warning","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":5,"startColumn":5,"startLine":19}}}],"message":{"text":"misleading indentation; statement is not part of the previous 'if'"},"ruleId":"1806","ruleIndex":3},{"level":"note","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":3,"startColumn":3,"startLine":17}}}],"message":{"text":"previous statement is here"},"ruleId":"1730","ruleIndex":4},{"level":"warning","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":10,"startColumn":10,"startLine":18}}}],"message":{"text":"unused variable 'Yes'"},"ruleId":"6539","ruleIndex":5},{"level":"error","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":12,"startColumn":12,"startLine":21}}}],"message":{"text":"use of undeclared identifier 'hi'"},"ruleId":"4604","ruleIndex":6},{"level":"error","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":1,"startColumn":1,"startLine":23}}}],"message":{"text":"extraneous closing brace ('}')"},"ruleId":"1399","ruleIndex":7},{"level":"error","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":6,"endLine":27,"startColumn":5,"startLine":27}}},{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":10,"endLine":27,"startColumn":9,"startLine":27}}},{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":7,"startColumn":7,"startLine":27}}}],"message":{"text":"invalid operands to binary expression ('t1' and 't1')"},"ruleId":"4539","ruleIndex":8}],"tool":{"driver":{"fullName":"","informationUri":"https://clang.llvm.org/docs/UsersManual.html","language":"en-US","name":"clang","rules":[{"defaultConfiguration":{"enabled":true,"level":"error","rank":50},"fullDescription":{"text":""},"id":"3465","name":""},{"defaultConfiguration":{"enabled":true,"level":"error","rank":50},"fullDescription":{"text":""},"id":"4604","name":""},{"defaultConfiguration":{"enabled":true,"level":"error","rank":50},"fullDescription":{"text":""},"id":"898","name":""},{"defaultConfiguration":{"enabled":true,"level":"warning","rank":-1},"fullDescription":{"text":""},"id":"1806","name":""},{"defaultConfiguration":{"enabled":true,"level":"note","rank":-1},"fullDescription":{"text":""},"id":"1730","name":""},{"defaultConfiguration":{"enabled":true,"level":"warning","rank":-1},"fullDescription":{"text":""},"id":"6539","name":""},{"defaultConfiguration":{"enabled":true,"level":"error","rank":50},"fullDescription":{"text":""},"id":"4604","name":""},{"defaultConfiguration":{"enabled":true,"level":"error","rank":50},

[PATCH] D132186: Clang: Add a new flag Wmisnoinline for printing hot noinline functions

2022-08-26 Thread Di Mo via Phabricator via cfe-commits
modimo added a comment.

Thanks for taking a look!

In D132186#3752150 , @paulkirth wrote:

> In D132186#3751985 , @tejohnson 
> wrote:
>
>> I have seen a few cases where noinline was used for performance, in addition 
>> to other cases like avoiding too much stack growth.
>
> Well, I stand corrected. I'm curious about what these cases are, but in any 
> case if there are cases where its done, then I agree that a diagnostic would 
> be helpful.

Same. The instances I've seen is an older codebase where compiler optimizations 
were not as powerful and/or purposefully written by engineers that didn't trust 
the compiler to do the right thing.

>> It is a little different than misexpect though in that the expect hints are 
>> pretty much only for performance, so it is more useful to be able to issue a 
>> strong warning that can be turned into an error if they are wrong. And also 
>> there was no way to report the misuse of expects earlier, unlike inlining 
>> where we already had the remarks plumbing.
>>
>> I haven't looked through the patch in detail, but is it possible to use your 
>> changes to emit a better missed opt remark from the inliner for these cases 
>> (I assume we will already emit a -Rpass-missed=inline for the noinline 
>> attribute case, just not highlighting that it is hot and would have been 
>> inlined for performance reasons otherwise)? I suppose one main reason for 
>> adding a warning is that the missed inline remarks can be really noisy and 
>> not really useful to the user vs a compiler optimization engineer doing 
>> inliner/compiler tuning, and therefore a warning would make it easier to 
>> turn on more widely as user feedback that can/should be addressed in user 
>> code.
>
> Yeah, I was thinking we could emit a new remark type for this to 
> differentiate, but it seems simpler more user friendly to emit some clar 
> diagnostic directly.
>
> I think we’re starting to accumulate a few of these diagnostics now that are 
> trying to diagnose potential performance deficiencies based on profiling 
> information. Originally we had prototyped a tool for misexpect based on 
> libtooling that ran over the build based on the compile commands DB and 
> reported everything it found.  I wonder if reviving that would be useful in 
> these cases when you want to look for performance issues like this, 
> misexpect, and other cases? Making ORE diagnostic output queryable through a 
> tool may also be a good option, but I'm not too familiar with what already 
> exists in that area.

Currently a new ORE (`-pass-remarks=misnoinline`) is getting generated, which 
misnoexcept also does. Agreed a warning is more familiar and friendlier for 
users so I lean towards that approach. For additional tooling, I think the 
first step will be to trial this on more real programs to see what cases are 
interesting. @iamarchit123 just finished his internship with us so I'll be 
evaluating these changes on HHVM to see if they can swing the performance 
needle.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132186

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


[PATCH] D131632: [clang] Enable output of SARIF diagnostics

2022-08-26 Thread Abraham Corea Diaz via Phabricator via cfe-commits
abrahamcd updated this revision to Diff 455968.
abrahamcd added a comment.

Reset SARIFDiag during EndSourceFile().


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131632

Files:
  clang/include/clang/Frontend/SARIFDiagnostic.h
  clang/include/clang/Frontend/SARIFDiagnosticPrinter.h
  clang/lib/Frontend/CMakeLists.txt
  clang/lib/Frontend/CompilerInstance.cpp
  clang/lib/Frontend/FrontendAction.cpp
  clang/lib/Frontend/SARIFDiagnostic.cpp
  clang/lib/Frontend/SARIFDiagnosticPrinter.cpp
  clang/test/Frontend/sarif-diagnostics.cpp

Index: clang/test/Frontend/sarif-diagnostics.cpp
===
--- /dev/null
+++ clang/test/Frontend/sarif-diagnostics.cpp
@@ -0,0 +1,28 @@
+// RUN: %clang -fsyntax-only -Wall -Wextra -fdiagnostics-format=sarif %s > %t 2>&1 || true
+// RUN: FileCheck -dump-input=always %s --input-file=%t
+// CHECK: warning: diagnostic formatting in SARIF mode is currently unstable [-Wsarif-format-unstable]
+// CHECK: {"$schema":"https://docs.oasis-open.org/sarif/sarif/v2.1.0/cos02/schemas/sarif-schema-2.1.0.json","runs":[{"artifacts":[{"length":
+// Omit exact length of this file
+// CHECK: ,"location":{"index":0,"uri":"file://
+// Omit filepath to llvm project directory
+// CHECK: clang/test/Frontend/sarif-diagnostics.cpp"},"mimeType":"text/plain","roles":["resultFile"]}],"columnKind":"unicodeCodePoints","results":[{"level":"error","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":1,"startColumn":1,"startLine":12}}}],"message":{"text":"'main' must return 'int'"},"ruleId":"3465","ruleIndex":0},{"level":"error","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":11,"startColumn":11,"startLine":13}}}],"message":{"text":"use of undeclared identifier 'hello'"},"ruleId":"4604","ruleIndex":1},{"level":"error","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":17,"startColumn":17,"startLine":15}}}],"message":{"text":"invalid digit 'a' in decimal constant"},"ruleId":"898","ruleIndex":2},{"level":"warning","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":5,"startColumn":5,"startLine":19}}}],"message":{"text":"misleading indentation; statement is not part of the previous 'if'"},"ruleId":"1806","ruleIndex":3},{"level":"note","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":3,"startColumn":3,"startLine":17}}}],"message":{"text":"previous statement is here"},"ruleId":"1730","ruleIndex":4},{"level":"warning","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":10,"startColumn":10,"startLine":18}}}],"message":{"text":"unused variable 'Yes'"},"ruleId":"6539","ruleIndex":5},{"level":"error","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":12,"startColumn":12,"startLine":21}}}],"message":{"text":"use of undeclared identifier 'hi'"},"ruleId":"4604","ruleIndex":6},{"level":"error","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":1,"startColumn":1,"startLine":23}}}],"message":{"text":"extraneous closing brace ('}')"},"ruleId":"1399","ruleIndex":7},{"level":"error","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":6,"endLine":27,"startColumn":5,"startLine":27}}},{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":10,"endLine":27,"startColumn":9,"startLine":27}}},{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":7,"startColumn":7,"startLine":27}}}],"message":{"text":"invalid operands to binary expression ('t1' and 't1')"},"ruleId":"4539","ruleIndex":8}],"tool":{"driver":{"fullName":"","informationUri":"https://clang.llvm.org/docs/UsersManual.html","language":"en-US","name":"clang","rules":[{"defaultConfiguration":{"enabled":true,"level":"error","rank":50},"fullDescription":{"text":""},"id":"3465","name":""},{"defaultConfiguration":{"enabled":true,"level":"error","rank":50},"fullDescription":{"text":""},"id":"4604","name":""},{"defaultConfiguration":{"enabled":true,"level":"error","rank":50},"fullDescription":{"text":""},"id":"898","name":""},{"defaultConfiguration":{"enabled":true,"level":"warning","rank":-1},"fullDescription":{"text":""},"id":"1806","name":""},{"defaultConfiguration":{"enabled":true,"level":"note","rank":-1},"fullDescription":{"text":""},"id":"1730","name":""},{"defaultConfiguration":{"enabled":true,"level":"warning","rank":-1},"fullDescription":{"text":""},"id":"6539","name":""},{"defaultConfiguration":{"enabled":true,"level":"error","rank":50},"fullDescription":{"text":""},"id":"4604","name":""},{"defaultConfiguration":{"enabled":true,"level":"error","rank":50},"fullDescription":{"text":""},"id":"1399","name":""},{"defaultConfiguration":{"enabled":true,"level":"error","rank":50},"fullDescripti

[PATCH] D132691: [clang] Do not instrument the rtti_proxies under hwasan

2022-08-26 Thread Leonard Chan via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGcdb30f7a2635: [clang] Do not instrument the rtti_proxies 
under hwasan (authored by leonardchan).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132691

Files:
  clang/lib/CodeGen/CGVTables.cpp
  clang/lib/CodeGen/CGVTables.h
  clang/test/CodeGenCXX/RelativeVTablesABI/relative-vtables-hwasan.cpp


Index: clang/test/CodeGenCXX/RelativeVTablesABI/relative-vtables-hwasan.cpp
===
--- clang/test/CodeGenCXX/RelativeVTablesABI/relative-vtables-hwasan.cpp
+++ clang/test/CodeGenCXX/RelativeVTablesABI/relative-vtables-hwasan.cpp
@@ -6,6 +6,7 @@
 /// hwasan-instrumented.
 // CHECK-DAG: @_ZTV1A.local = private unnamed_addr constant { [3 x i32] } { [3 
x i32] [i32 0, i32 trunc (i64 sub (i64 ptrtoint (ptr @_ZTI1A.rtti_proxy to 
i64), i64 ptrtoint (ptr getelementptr inbounds ({ [3 x i32] }, ptr 
@_ZTV1A.local, i32 0, i32 0, i32 2) to i64)) to i32), i32 trunc (i64 sub (i64 
ptrtoint (ptr dso_local_equivalent @_ZN1A3fooEv to i64), i64 ptrtoint (ptr 
getelementptr inbounds ({ [3 x i32] }, ptr @_ZTV1A.local, i32 0, i32 0, i32 2) 
to i64)) to i32)] }, no_sanitize_hwaddress, align 4
 // CHECK-DAG: @_ZTV1A = unnamed_addr alias { [3 x i32] }, ptr @_ZTV1A.local
+// CHECK-DAG: @_ZTI1A.rtti_proxy = hidden unnamed_addr constant ptr @_ZTI1A, 
no_sanitize_hwaddress, comdat
 
 class A {
 public:
@@ -21,6 +22,7 @@
 /// If the vtable happens to be hidden, then the alias is not needed. In this
 /// case, the original vtable struct itself should be unsanitized.
 // CHECK-DAG: @_ZTV1B = hidden unnamed_addr constant { [3 x i32] } { [3 x i32] 
[i32 0, i32 trunc (i64 sub (i64 ptrtoint (ptr @_ZTI1B.rtti_proxy to i64), i64 
ptrtoint (ptr getelementptr inbounds ({ [3 x i32] }, ptr @_ZTV1B, i32 0, i32 0, 
i32 2) to i64)) to i32), i32 trunc (i64 sub (i64 ptrtoint (ptr 
dso_local_equivalent @_ZN1B3fooEv to i64), i64 ptrtoint (ptr getelementptr 
inbounds ({ [3 x i32] }, ptr @_ZTV1B, i32 0, i32 0, i32 2) to i64)) to i32)] }, 
no_sanitize_hwaddress, align 4
+// CHECK-DAG: @_ZTI1B.rtti_proxy = hidden unnamed_addr constant ptr @_ZTI1B, 
no_sanitize_hwaddress, comdat
 
 class __attribute__((visibility("hidden"))) B {
 public:
Index: clang/lib/CodeGen/CGVTables.h
===
--- clang/lib/CodeGen/CGVTables.h
+++ clang/lib/CodeGen/CGVTables.h
@@ -155,8 +155,8 @@
   void GenerateRelativeVTableAlias(llvm::GlobalVariable *VTable,
llvm::StringRef AliasNameRef);
 
-  /// Specify a vtable should not be instrumented with hwasan.
-  void RemoveHwasanMetadata(llvm::GlobalValue *VTable);
+  /// Specify a global should not be instrumented with hwasan.
+  void RemoveHwasanMetadata(llvm::GlobalValue *GV) const;
 };
 
 } // end namespace CodeGen
Index: clang/lib/CodeGen/CGVTables.cpp
===
--- clang/lib/CodeGen/CGVTables.cpp
+++ clang/lib/CodeGen/CGVTables.cpp
@@ -664,6 +664,12 @@
 proxy->setVisibility(llvm::GlobalValue::HiddenVisibility);
 proxy->setComdat(module.getOrInsertComdat(rttiProxyName));
   }
+  // Do not instrument the rtti proxies with hwasan to avoid a duplicate
+  // symbol error. Aliases generated by hwasan will retain the same namebut
+  // the addresses they are set to may have different tags from different
+  // compilation units. We don't run into this without hwasan because the
+  // proxies are in comdat groups, but those aren't propagated to the 
alias.
+  RemoveHwasanMetadata(proxy);
 }
 target = proxy;
   }
@@ -938,13 +944,13 @@
 // relocations. A future alternative for this would be finding which usages of
 // the vtable can continue to use the untagged hwasan value without any loss of
 // value in hwasan.
-void CodeGenVTables::RemoveHwasanMetadata(llvm::GlobalValue *VTable) {
+void CodeGenVTables::RemoveHwasanMetadata(llvm::GlobalValue *GV) const {
   if (CGM.getLangOpts().Sanitize.has(SanitizerKind::HWAddress)) {
 llvm::GlobalValue::SanitizerMetadata Meta;
-if (VTable->hasSanitizerMetadata())
-  Meta = VTable->getSanitizerMetadata();
+if (GV->hasSanitizerMetadata())
+  Meta = GV->getSanitizerMetadata();
 Meta.NoHWAddress = true;
-VTable->setSanitizerMetadata(Meta);
+GV->setSanitizerMetadata(Meta);
   }
 }
 


Index: clang/test/CodeGenCXX/RelativeVTablesABI/relative-vtables-hwasan.cpp
===
--- clang/test/CodeGenCXX/RelativeVTablesABI/relative-vtables-hwasan.cpp
+++ clang/test/CodeGenCXX/RelativeVTablesABI/relative-vtables-hwasan.cpp
@@ -6,6 +6,7 @@
 /// hwasan-instrumented.
 // CHECK-DAG: @_ZTV1A.local = private unnamed_addr constant { [3 x i32] } { [3 x i

[clang] cdb30f7 - [clang] Do not instrument the rtti_proxies under hwasan

2022-08-26 Thread Leonard Chan via cfe-commits

Author: Leonard Chan
Date: 2022-08-26T18:22:17Z
New Revision: cdb30f7a26354b000310ebe30a6874f7737675ed

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

LOG: [clang] Do not instrument the rtti_proxies under hwasan

We run into a duplicate symbol error when instrumenting the rtti_proxies
generated as part of the relative vtables ABI with hwasan:

```
ld.lld: error: duplicate symbol: typeinfo for icu_71::UObject
(.rtti_proxy)
>>> defined at brkiter.cpp
>>>
arm64-hwasan-shared/obj/third_party/icu/source/common/libicuuc.brkiter.cpp.o:(typeinfo
for icu_71::UObject (.rtti_proxy))
>>> defined at locavailable.cpp
>>>
arm64-hwasan-shared/obj/third_party/icu/source/common/libicuuc.locavailable.cpp.o:(.data.rel.ro..L_ZTIN6icu_717UObjectE.rtti_proxy.hwasan+0xE00)
```

The issue here is that the hwasan alias carries over the visibility and
linkage of the original proxy, so we have duplicate external symbols
that participate in linking. Similar to D132425 we can just disable
hwasan for the proxies for now.

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

Added: 


Modified: 
clang/lib/CodeGen/CGVTables.cpp
clang/lib/CodeGen/CGVTables.h
clang/test/CodeGenCXX/RelativeVTablesABI/relative-vtables-hwasan.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGVTables.cpp b/clang/lib/CodeGen/CGVTables.cpp
index c8b29aec917c..3f8835d80a9a 100644
--- a/clang/lib/CodeGen/CGVTables.cpp
+++ b/clang/lib/CodeGen/CGVTables.cpp
@@ -664,6 +664,12 @@ void 
CodeGenVTables::addRelativeComponent(ConstantArrayBuilder &builder,
 proxy->setVisibility(llvm::GlobalValue::HiddenVisibility);
 proxy->setComdat(module.getOrInsertComdat(rttiProxyName));
   }
+  // Do not instrument the rtti proxies with hwasan to avoid a duplicate
+  // symbol error. Aliases generated by hwasan will retain the same namebut
+  // the addresses they are set to may have 
diff erent tags from 
diff erent
+  // compilation units. We don't run into this without hwasan because the
+  // proxies are in comdat groups, but those aren't propagated to the 
alias.
+  RemoveHwasanMetadata(proxy);
 }
 target = proxy;
   }
@@ -938,13 +944,13 @@ llvm::GlobalVariable 
*CodeGenVTables::GenerateConstructionVTable(
 // relocations. A future alternative for this would be finding which usages of
 // the vtable can continue to use the untagged hwasan value without any loss of
 // value in hwasan.
-void CodeGenVTables::RemoveHwasanMetadata(llvm::GlobalValue *VTable) {
+void CodeGenVTables::RemoveHwasanMetadata(llvm::GlobalValue *GV) const {
   if (CGM.getLangOpts().Sanitize.has(SanitizerKind::HWAddress)) {
 llvm::GlobalValue::SanitizerMetadata Meta;
-if (VTable->hasSanitizerMetadata())
-  Meta = VTable->getSanitizerMetadata();
+if (GV->hasSanitizerMetadata())
+  Meta = GV->getSanitizerMetadata();
 Meta.NoHWAddress = true;
-VTable->setSanitizerMetadata(Meta);
+GV->setSanitizerMetadata(Meta);
   }
 }
 

diff  --git a/clang/lib/CodeGen/CGVTables.h b/clang/lib/CodeGen/CGVTables.h
index c044ecc9bc8c..eb6b00b7847b 100644
--- a/clang/lib/CodeGen/CGVTables.h
+++ b/clang/lib/CodeGen/CGVTables.h
@@ -155,8 +155,8 @@ class CodeGenVTables {
   void GenerateRelativeVTableAlias(llvm::GlobalVariable *VTable,
llvm::StringRef AliasNameRef);
 
-  /// Specify a vtable should not be instrumented with hwasan.
-  void RemoveHwasanMetadata(llvm::GlobalValue *VTable);
+  /// Specify a global should not be instrumented with hwasan.
+  void RemoveHwasanMetadata(llvm::GlobalValue *GV) const;
 };
 
 } // end namespace CodeGen

diff  --git 
a/clang/test/CodeGenCXX/RelativeVTablesABI/relative-vtables-hwasan.cpp 
b/clang/test/CodeGenCXX/RelativeVTablesABI/relative-vtables-hwasan.cpp
index b414b8d8ea8a..d0777b0f1245 100644
--- a/clang/test/CodeGenCXX/RelativeVTablesABI/relative-vtables-hwasan.cpp
+++ b/clang/test/CodeGenCXX/RelativeVTablesABI/relative-vtables-hwasan.cpp
@@ -6,6 +6,7 @@
 /// hwasan-instrumented.
 // CHECK-DAG: @_ZTV1A.local = private unnamed_addr constant { [3 x i32] } { [3 
x i32] [i32 0, i32 trunc (i64 sub (i64 ptrtoint (ptr @_ZTI1A.rtti_proxy to 
i64), i64 ptrtoint (ptr getelementptr inbounds ({ [3 x i32] }, ptr 
@_ZTV1A.local, i32 0, i32 0, i32 2) to i64)) to i32), i32 trunc (i64 sub (i64 
ptrtoint (ptr dso_local_equivalent @_ZN1A3fooEv to i64), i64 ptrtoint (ptr 
getelementptr inbounds ({ [3 x i32] }, ptr @_ZTV1A.local, i32 0, i32 0, i32 2) 
to i64)) to i32)] }, no_sanitize_hwaddress, align 4
 // CHECK-DAG: @_ZTV1A = unnamed_addr alias { [3 x i32] }, ptr @_ZTV1A.local
+// CHECK-DAG: @_ZTI1A.rtti_proxy = hidden unnamed_addr constant ptr @_ZTI1A, 
no_sanitize_hwaddress, comdat
 
 class A {
 public:
@@ -21,6 +22,7 @@ void A_foo(A *a)

[clang] 93e5cf6 - [clang] Do not instrument relative vtables under hwasan

2022-08-26 Thread Leonard Chan via cfe-commits

Author: Leonard Chan
Date: 2022-08-26T18:21:40Z
New Revision: 93e5cf6b9c08d99cf7cefc0adda346bd7ba56049

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

LOG: [clang] Do not instrument relative vtables under hwasan

Full context in
https://bugs.fuchsia.dev/p/fuchsia/issues/detail?id=107017.

Instrumenting hwasan with globals results in a linker error under the
relative vtables abi:

```
ld.lld: error:
libunwind.cpp:(.rodata..L_ZTVN9libunwind12UnwindCursorINS_17LocalAddressSpaceENS_15Registers_arm64EEE.hwasan+0x8):
relocation R_AARCH64_PLT32 out of range: 6845471433603167792 is not in
[-2147483648, 2147483647]; references
libunwind::AbstractUnwindCursor::~AbstractUnwindCursor()
>>> defined in
libunwind/src/CMakeFiles/unwind_shared.dir/libunwind.cpp.obj
```

This is because the tag is included in the vtable address when
calculating the offset between the vtable and virtual function. A
temporary solution until we can resolve this is to just disable hwasan
instrumentation on relative vtables specifically, which can be done in
the frontend.

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

Added: 
clang/test/CodeGenCXX/RelativeVTablesABI/relative-vtables-hwasan.cpp

Modified: 
clang/lib/CodeGen/CGVTables.cpp
clang/lib/CodeGen/CGVTables.h
clang/lib/CodeGen/ItaniumCXXABI.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGVTables.cpp b/clang/lib/CodeGen/CGVTables.cpp
index cdd40d2a6a2e..c8b29aec917c 100644
--- a/clang/lib/CodeGen/CGVTables.cpp
+++ b/clang/lib/CodeGen/CGVTables.cpp
@@ -921,12 +921,33 @@ llvm::GlobalVariable 
*CodeGenVTables::GenerateConstructionVTable(
 
   CGM.EmitVTableTypeMetadata(RD, VTable, *VTLayout.get());
 
-  if (UsingRelativeLayout && !VTable->isDSOLocal())
-GenerateRelativeVTableAlias(VTable, OutName);
+  if (UsingRelativeLayout) {
+RemoveHwasanMetadata(VTable);
+if (!VTable->isDSOLocal())
+  GenerateRelativeVTableAlias(VTable, OutName);
+  }
 
   return VTable;
 }
 
+// Ensure this vtable is not instrumented by hwasan. That is, a global alias is
+// not generated for it. This is mainly used by the relative-vtables ABI where
+// vtables instead contain 32-bit offsets between the vtable and function
+// pointers. Hwasan is disabled for these vtables for now because the tag in a
+// vtable pointer may fail the overflow check when resolving 32-bit PLT
+// relocations. A future alternative for this would be finding which usages of
+// the vtable can continue to use the untagged hwasan value without any loss of
+// value in hwasan.
+void CodeGenVTables::RemoveHwasanMetadata(llvm::GlobalValue *VTable) {
+  if (CGM.getLangOpts().Sanitize.has(SanitizerKind::HWAddress)) {
+llvm::GlobalValue::SanitizerMetadata Meta;
+if (VTable->hasSanitizerMetadata())
+  Meta = VTable->getSanitizerMetadata();
+Meta.NoHWAddress = true;
+VTable->setSanitizerMetadata(Meta);
+  }
+}
+
 // If the VTable is not dso_local, then we will not be able to indicate that
 // the VTable does not need a relocation and move into rodata. A frequent
 // time this can occur is for classes that should be made public from a DSO

diff  --git a/clang/lib/CodeGen/CGVTables.h b/clang/lib/CodeGen/CGVTables.h
index bdfc075ee305..c044ecc9bc8c 100644
--- a/clang/lib/CodeGen/CGVTables.h
+++ b/clang/lib/CodeGen/CGVTables.h
@@ -154,6 +154,9 @@ class CodeGenVTables {
   /// when a vtable may not be dso_local.
   void GenerateRelativeVTableAlias(llvm::GlobalVariable *VTable,
llvm::StringRef AliasNameRef);
+
+  /// Specify a vtable should not be instrumented with hwasan.
+  void RemoveHwasanMetadata(llvm::GlobalValue *VTable);
 };
 
 } // end namespace CodeGen

diff  --git a/clang/lib/CodeGen/ItaniumCXXABI.cpp 
b/clang/lib/CodeGen/ItaniumCXXABI.cpp
index 2809cbe99c10..cb97af7ab11a 100644
--- a/clang/lib/CodeGen/ItaniumCXXABI.cpp
+++ b/clang/lib/CodeGen/ItaniumCXXABI.cpp
@@ -1769,8 +1769,11 @@ void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables 
&CGVT,
 }
   }
 
-  if (VTContext.isRelativeLayout() && !VTable->isDSOLocal())
-CGVT.GenerateRelativeVTableAlias(VTable, VTable->getName());
+  if (VTContext.isRelativeLayout()) {
+CGVT.RemoveHwasanMetadata(VTable);
+if (!VTable->isDSOLocal())
+  CGVT.GenerateRelativeVTableAlias(VTable, VTable->getName());
+  }
 }
 
 bool ItaniumCXXABI::isVirtualOffsetNeededForVTableField(

diff  --git 
a/clang/test/CodeGenCXX/RelativeVTablesABI/relative-vtables-hwasan.cpp 
b/clang/test/CodeGenCXX/RelativeVTablesABI/relative-vtables-hwasan.cpp
new file mode 100644
index ..b414b8d8ea8a
--- /dev/null
+++ b/clang/test/CodeGenCXX/RelativeVTablesABI/relative-vtables-hwasan.cpp
@@ -0,0 +1,34 @@
+// RUN: %clang_cc1 %s -triple=aarch64-unknown-fuchsia -S -o - -emit-llvm 
-fsanitize

[PATCH] D132425: [clang] Do not instrument relative vtables under hwasan

2022-08-26 Thread Leonard Chan via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG93e5cf6b9c08: [clang] Do not instrument relative vtables 
under hwasan (authored by leonardchan).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132425

Files:
  clang/lib/CodeGen/CGVTables.cpp
  clang/lib/CodeGen/CGVTables.h
  clang/lib/CodeGen/ItaniumCXXABI.cpp
  clang/test/CodeGenCXX/RelativeVTablesABI/relative-vtables-hwasan.cpp

Index: clang/test/CodeGenCXX/RelativeVTablesABI/relative-vtables-hwasan.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/RelativeVTablesABI/relative-vtables-hwasan.cpp
@@ -0,0 +1,34 @@
+// RUN: %clang_cc1 %s -triple=aarch64-unknown-fuchsia -S -o - -emit-llvm -fsanitize=hwaddress | FileCheck %s
+
+/// The usual vtable will have default visibility. In this case, the actual
+/// vtable is hidden and the alias is made public. With hwasan enabled, we want
+/// to ensure the local one self-referenced in the hidden vtable is not
+/// hwasan-instrumented.
+// CHECK-DAG: @_ZTV1A.local = private unnamed_addr constant { [3 x i32] } { [3 x i32] [i32 0, i32 trunc (i64 sub (i64 ptrtoint (ptr @_ZTI1A.rtti_proxy to i64), i64 ptrtoint (ptr getelementptr inbounds ({ [3 x i32] }, ptr @_ZTV1A.local, i32 0, i32 0, i32 2) to i64)) to i32), i32 trunc (i64 sub (i64 ptrtoint (ptr dso_local_equivalent @_ZN1A3fooEv to i64), i64 ptrtoint (ptr getelementptr inbounds ({ [3 x i32] }, ptr @_ZTV1A.local, i32 0, i32 0, i32 2) to i64)) to i32)] }, no_sanitize_hwaddress, align 4
+// CHECK-DAG: @_ZTV1A = unnamed_addr alias { [3 x i32] }, ptr @_ZTV1A.local
+
+class A {
+public:
+  virtual void foo();
+};
+
+void A::foo() {}
+
+void A_foo(A *a) {
+  a->foo();
+}
+
+/// If the vtable happens to be hidden, then the alias is not needed. In this
+/// case, the original vtable struct itself should be unsanitized.
+// CHECK-DAG: @_ZTV1B = hidden unnamed_addr constant { [3 x i32] } { [3 x i32] [i32 0, i32 trunc (i64 sub (i64 ptrtoint (ptr @_ZTI1B.rtti_proxy to i64), i64 ptrtoint (ptr getelementptr inbounds ({ [3 x i32] }, ptr @_ZTV1B, i32 0, i32 0, i32 2) to i64)) to i32), i32 trunc (i64 sub (i64 ptrtoint (ptr dso_local_equivalent @_ZN1B3fooEv to i64), i64 ptrtoint (ptr getelementptr inbounds ({ [3 x i32] }, ptr @_ZTV1B, i32 0, i32 0, i32 2) to i64)) to i32)] }, no_sanitize_hwaddress, align 4
+
+class __attribute__((visibility("hidden"))) B {
+public:
+  virtual void foo();
+};
+
+void B::foo() {}
+
+void B_foo(B *b) {
+  b->foo();
+}
Index: clang/lib/CodeGen/ItaniumCXXABI.cpp
===
--- clang/lib/CodeGen/ItaniumCXXABI.cpp
+++ clang/lib/CodeGen/ItaniumCXXABI.cpp
@@ -1769,8 +1769,11 @@
 }
   }
 
-  if (VTContext.isRelativeLayout() && !VTable->isDSOLocal())
-CGVT.GenerateRelativeVTableAlias(VTable, VTable->getName());
+  if (VTContext.isRelativeLayout()) {
+CGVT.RemoveHwasanMetadata(VTable);
+if (!VTable->isDSOLocal())
+  CGVT.GenerateRelativeVTableAlias(VTable, VTable->getName());
+  }
 }
 
 bool ItaniumCXXABI::isVirtualOffsetNeededForVTableField(
Index: clang/lib/CodeGen/CGVTables.h
===
--- clang/lib/CodeGen/CGVTables.h
+++ clang/lib/CodeGen/CGVTables.h
@@ -154,6 +154,9 @@
   /// when a vtable may not be dso_local.
   void GenerateRelativeVTableAlias(llvm::GlobalVariable *VTable,
llvm::StringRef AliasNameRef);
+
+  /// Specify a vtable should not be instrumented with hwasan.
+  void RemoveHwasanMetadata(llvm::GlobalValue *VTable);
 };
 
 } // end namespace CodeGen
Index: clang/lib/CodeGen/CGVTables.cpp
===
--- clang/lib/CodeGen/CGVTables.cpp
+++ clang/lib/CodeGen/CGVTables.cpp
@@ -921,12 +921,33 @@
 
   CGM.EmitVTableTypeMetadata(RD, VTable, *VTLayout.get());
 
-  if (UsingRelativeLayout && !VTable->isDSOLocal())
-GenerateRelativeVTableAlias(VTable, OutName);
+  if (UsingRelativeLayout) {
+RemoveHwasanMetadata(VTable);
+if (!VTable->isDSOLocal())
+  GenerateRelativeVTableAlias(VTable, OutName);
+  }
 
   return VTable;
 }
 
+// Ensure this vtable is not instrumented by hwasan. That is, a global alias is
+// not generated for it. This is mainly used by the relative-vtables ABI where
+// vtables instead contain 32-bit offsets between the vtable and function
+// pointers. Hwasan is disabled for these vtables for now because the tag in a
+// vtable pointer may fail the overflow check when resolving 32-bit PLT
+// relocations. A future alternative for this would be finding which usages of
+// the vtable can continue to use the untagged hwasan value without any loss of
+// value in hwasan.
+void CodeGenVTables::RemoveHwasanMetadata(llvm::GlobalValue *VTable) {
+  if (CGM.getLangOpts().Sanitize.has(SanitizerKind::HWAddress)) {
+llv

[PATCH] D131632: [clang] Enable output of SARIF diagnostics

2022-08-26 Thread Abraham Corea Diaz via Phabricator via cfe-commits
abrahamcd updated this revision to Diff 455964.
abrahamcd added a comment.

Deleted copy and move for Printer and added asserts.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131632

Files:
  clang/include/clang/Frontend/SARIFDiagnostic.h
  clang/include/clang/Frontend/SARIFDiagnosticPrinter.h
  clang/lib/Frontend/CMakeLists.txt
  clang/lib/Frontend/CompilerInstance.cpp
  clang/lib/Frontend/FrontendAction.cpp
  clang/lib/Frontend/SARIFDiagnostic.cpp
  clang/lib/Frontend/SARIFDiagnosticPrinter.cpp
  clang/test/Frontend/sarif-diagnostics.cpp

Index: clang/test/Frontend/sarif-diagnostics.cpp
===
--- /dev/null
+++ clang/test/Frontend/sarif-diagnostics.cpp
@@ -0,0 +1,28 @@
+// RUN: %clang -fsyntax-only -Wall -Wextra -fdiagnostics-format=sarif %s > %t 2>&1 || true
+// RUN: FileCheck -dump-input=always %s --input-file=%t
+// CHECK: warning: diagnostic formatting in SARIF mode is currently unstable [-Wsarif-format-unstable]
+// CHECK: {"$schema":"https://docs.oasis-open.org/sarif/sarif/v2.1.0/cos02/schemas/sarif-schema-2.1.0.json","runs":[{"artifacts":[{"length":
+// Omit exact length of this file
+// CHECK: ,"location":{"index":0,"uri":"file://
+// Omit filepath to llvm project directory
+// CHECK: clang/test/Frontend/sarif-diagnostics.cpp"},"mimeType":"text/plain","roles":["resultFile"]}],"columnKind":"unicodeCodePoints","results":[{"level":"error","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":1,"startColumn":1,"startLine":12}}}],"message":{"text":"'main' must return 'int'"},"ruleId":"3465","ruleIndex":0},{"level":"error","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":11,"startColumn":11,"startLine":13}}}],"message":{"text":"use of undeclared identifier 'hello'"},"ruleId":"4604","ruleIndex":1},{"level":"error","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":17,"startColumn":17,"startLine":15}}}],"message":{"text":"invalid digit 'a' in decimal constant"},"ruleId":"898","ruleIndex":2},{"level":"warning","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":5,"startColumn":5,"startLine":19}}}],"message":{"text":"misleading indentation; statement is not part of the previous 'if'"},"ruleId":"1806","ruleIndex":3},{"level":"note","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":3,"startColumn":3,"startLine":17}}}],"message":{"text":"previous statement is here"},"ruleId":"1730","ruleIndex":4},{"level":"warning","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":10,"startColumn":10,"startLine":18}}}],"message":{"text":"unused variable 'Yes'"},"ruleId":"6539","ruleIndex":5},{"level":"error","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":12,"startColumn":12,"startLine":21}}}],"message":{"text":"use of undeclared identifier 'hi'"},"ruleId":"4604","ruleIndex":6},{"level":"error","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":1,"startColumn":1,"startLine":23}}}],"message":{"text":"extraneous closing brace ('}')"},"ruleId":"1399","ruleIndex":7},{"level":"error","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":6,"endLine":27,"startColumn":5,"startLine":27}}},{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":10,"endLine":27,"startColumn":9,"startLine":27}}},{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":7,"startColumn":7,"startLine":27}}}],"message":{"text":"invalid operands to binary expression ('t1' and 't1')"},"ruleId":"4539","ruleIndex":8}],"tool":{"driver":{"fullName":"","informationUri":"https://clang.llvm.org/docs/UsersManual.html","language":"en-US","name":"clang","rules":[{"defaultConfiguration":{"enabled":true,"level":"error","rank":50},"fullDescription":{"text":""},"id":"3465","name":""},{"defaultConfiguration":{"enabled":true,"level":"error","rank":50},"fullDescription":{"text":""},"id":"4604","name":""},{"defaultConfiguration":{"enabled":true,"level":"error","rank":50},"fullDescription":{"text":""},"id":"898","name":""},{"defaultConfiguration":{"enabled":true,"level":"warning","rank":-1},"fullDescription":{"text":""},"id":"1806","name":""},{"defaultConfiguration":{"enabled":true,"level":"note","rank":-1},"fullDescription":{"text":""},"id":"1730","name":""},{"defaultConfiguration":{"enabled":true,"level":"warning","rank":-1},"fullDescription":{"text":""},"id":"6539","name":""},{"defaultConfiguration":{"enabled":true,"level":"error","rank":50},"fullDescription":{"text":""},"id":"4604","name":""},{"defaultConfiguration":{"enabled":true,"level":"error","rank":50},"fullDescription":{"text":""},"id":"1399","name":""},{"defaultConfiguration":{"enabled":true,"level":"error","rank":50},"

[PATCH] D132661: [clang] Make guard(nocf) attribute available only for Windows

2022-08-26 Thread Reid Kleckner via Phabricator via cfe-commits
rnk accepted this revision.
rnk added a comment.

+1


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132661

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


[PATCH] D132236: [analyzer] Fix liveness of LazyCompoundVals

2022-08-26 Thread Balázs Benics via Phabricator via cfe-commits
steakhal planned changes to this revision.
steakhal added a comment.

In D132236#3752209 , @NoQ wrote:

>> So, what you are suggesting here is an alternative solution to the one you 
>> already proposed in your last comment?
>
> I was just expanding the initial suggestion but also symbol reaper is too 
> complicated for me to make such suggestions confidently. So I'm just sharing 
> some ideas but you'll probably have to dig deeper to understand whether 
> they're correct.

I see. I very much appreciate any suggestions. Many thanks.

>> Unfortunately, we found many FPs introduced by this change; so this should 
>> be definitely blocked.
>
> Interesting, I didn't expect that. It could be insanely valuable to make 
> tests out of those so that future generations didn't make the same mistake! 
> Symbol reaper seems to be very under-tested for its complexity.

I agree. We were also surprised. I havent spent the time to understand the root 
cause, as only a single path resulted in a 160Mb+ html. So far I can tell that 
it messed up something including lambdas capturing by reference. I find it 
always difficult to catch "what is missing" from the puzzle in such cases. Its 
much easier to catch if something has a wrong binding etc. We'll see how much 
effort it takes to reduce. For FPs I dont know how to automate this process. :/

Lets see when we get back to this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132236

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


[PATCH] D131632: [clang] Enable output of SARIF diagnostics

2022-08-26 Thread Abraham Corea Diaz via Phabricator via cfe-commits
abrahamcd added inline comments.



Comment at: clang/lib/Frontend/SARIFDiagnostic.cpp:58
+
+  if (Loc.isValid())
+Result = addLocationToResult(Result, Loc, PLoc, Ranges, *Diag);

denik wrote:
> abrahamcd wrote:
> > denik wrote:
> > > I think we should add a test case when Loc or/and Source Manager is not 
> > > set.
> > > If Loc is not set SarifDocumentWriter might not create the `locations` 
> > > property which is required by the spec.
> > > If this is the case we need to fix it. But I'm not sure if 
> > > emitDiagnosticMessage() is going to be called when Loc.isInvalid() ).
> > I believe if Loc is invalid, it goes to one of those special cases I 
> > mentioned in this review.
> If it does then "if" is redundant here.
Looked closer and the base Renderer calls this function in both cases when Loc 
is valid and when it is invalid, so the extra check is necessary. In the case 
that Loc is invalid, you're right that results will not have locations. This 
might be something to add to the Writer, I couldn't find a way to add an empty 
locations object.



Comment at: clang/lib/Frontend/SARIFDiagnostic.cpp:191
+#ifdef _WIN32
+  TmpFilename = (*File)->getName();
+  llvm::sys::fs::make_absolute(TmpFilename);

cjdb wrote:
> denik wrote:
> > cjdb wrote:
> > > aaron.ballman wrote:
> > > > Note: this is not a particularly small string when it requires 4k by 
> > > > default.
> > > There's a bug either here or in the function's interface: the function 
> > > returns a `StringRef` to a stack object. Do we really need ownership here?
> > > Note: this is not a particularly small string when it requires 4k by 
> > > default.
> > 
> > This still has to be addressed.
> > There's a bug either here or in the function's interface: the function 
> > returns a StringRef to a stack object. Do we really need ownership here?
> 
> Disregard, I misread `TmpFilename` as `Filename` and thought we were 
> returning a dangling reference. That isn't the case, so there is no bug.
Made it smaller for now, but this should be revisited during refactoring, since 
text diag still uses 4096


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131632

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


[PATCH] D131632: [clang] Enable output of SARIF diagnostics

2022-08-26 Thread Abraham Corea Diaz via Phabricator via cfe-commits
abrahamcd updated this revision to Diff 455955.
abrahamcd marked 10 inline comments as done.
abrahamcd added a comment.

Resolved pending comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131632

Files:
  clang/include/clang/Frontend/SARIFDiagnostic.h
  clang/include/clang/Frontend/SARIFDiagnosticPrinter.h
  clang/lib/Frontend/CMakeLists.txt
  clang/lib/Frontend/CompilerInstance.cpp
  clang/lib/Frontend/FrontendAction.cpp
  clang/lib/Frontend/SARIFDiagnostic.cpp
  clang/lib/Frontend/SARIFDiagnosticPrinter.cpp
  clang/test/Frontend/sarif-diagnostics.cpp

Index: clang/test/Frontend/sarif-diagnostics.cpp
===
--- /dev/null
+++ clang/test/Frontend/sarif-diagnostics.cpp
@@ -0,0 +1,28 @@
+// RUN: %clang -fsyntax-only -Wall -Wextra -fdiagnostics-format=sarif %s > %t 2>&1 || true
+// RUN: FileCheck -dump-input=always %s --input-file=%t
+// CHECK: warning: diagnostic formatting in SARIF mode is currently unstable [-Wsarif-format-unstable]
+// CHECK: {"$schema":"https://docs.oasis-open.org/sarif/sarif/v2.1.0/cos02/schemas/sarif-schema-2.1.0.json","runs":[{"artifacts":[{"length":
+// Omit exact length of this file
+// CHECK: ,"location":{"index":0,"uri":"file://
+// Omit filepath to llvm project directory
+// CHECK: clang/test/Frontend/sarif-diagnostics.cpp"},"mimeType":"text/plain","roles":["resultFile"]}],"columnKind":"unicodeCodePoints","results":[{"level":"error","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":1,"startColumn":1,"startLine":12}}}],"message":{"text":"'main' must return 'int'"},"ruleId":"3465","ruleIndex":0},{"level":"error","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":11,"startColumn":11,"startLine":13}}}],"message":{"text":"use of undeclared identifier 'hello'"},"ruleId":"4604","ruleIndex":1},{"level":"error","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":17,"startColumn":17,"startLine":15}}}],"message":{"text":"invalid digit 'a' in decimal constant"},"ruleId":"898","ruleIndex":2},{"level":"warning","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":5,"startColumn":5,"startLine":19}}}],"message":{"text":"misleading indentation; statement is not part of the previous 'if'"},"ruleId":"1806","ruleIndex":3},{"level":"note","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":3,"startColumn":3,"startLine":17}}}],"message":{"text":"previous statement is here"},"ruleId":"1730","ruleIndex":4},{"level":"warning","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":10,"startColumn":10,"startLine":18}}}],"message":{"text":"unused variable 'Yes'"},"ruleId":"6539","ruleIndex":5},{"level":"error","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":12,"startColumn":12,"startLine":21}}}],"message":{"text":"use of undeclared identifier 'hi'"},"ruleId":"4604","ruleIndex":6},{"level":"error","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":1,"startColumn":1,"startLine":23}}}],"message":{"text":"extraneous closing brace ('}')"},"ruleId":"1399","ruleIndex":7},{"level":"error","locations":[{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":6,"endLine":27,"startColumn":5,"startLine":27}}},{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":10,"endLine":27,"startColumn":9,"startLine":27}}},{"physicalLocation":{"artifactLocation":{"index":0},"region":{"endColumn":7,"startColumn":7,"startLine":27}}}],"message":{"text":"invalid operands to binary expression ('t1' and 't1')"},"ruleId":"4539","ruleIndex":8}],"tool":{"driver":{"fullName":"","informationUri":"https://clang.llvm.org/docs/UsersManual.html","language":"en-US","name":"clang","rules":[{"defaultConfiguration":{"enabled":true,"level":"error","rank":50},"fullDescription":{"text":""},"id":"3465","name":""},{"defaultConfiguration":{"enabled":true,"level":"error","rank":50},"fullDescription":{"text":""},"id":"4604","name":""},{"defaultConfiguration":{"enabled":true,"level":"error","rank":50},"fullDescription":{"text":""},"id":"898","name":""},{"defaultConfiguration":{"enabled":true,"level":"warning","rank":-1},"fullDescription":{"text":""},"id":"1806","name":""},{"defaultConfiguration":{"enabled":true,"level":"note","rank":-1},"fullDescription":{"text":""},"id":"1730","name":""},{"defaultConfiguration":{"enabled":true,"level":"warning","rank":-1},"fullDescription":{"text":""},"id":"6539","name":""},{"defaultConfiguration":{"enabled":true,"level":"error","rank":50},"fullDescription":{"text":""},"id":"4604","name":""},{"defaultConfiguration":{"enabled":true,"level":"error","rank":50},"fullDescription":{"text":""},"id":"1399","name":""},{"defaultConfiguration":{"enabled":true,"level":"

[PATCH] D131799: [HLSL] clang codeGen for HLSLNumThreadsAttr

2022-08-26 Thread Xiang Li via Phabricator via cfe-commits
python3kgae updated this revision to Diff 455954.
python3kgae added a comment.

Fix build error and merge conflict.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131799

Files:
  clang/lib/CodeGen/CGHLSLRuntime.cpp
  clang/test/CodeGenHLSL/entry.hlsl


Index: clang/test/CodeGenHLSL/entry.hlsl
===
--- clang/test/CodeGenHLSL/entry.hlsl
+++ clang/test/CodeGenHLSL/entry.hlsl
@@ -2,9 +2,10 @@
 
 // Make sure not mangle entry.
 // CHECK:define void @foo()
-// Make sure add function attribute.
+// Make sure add function attribute and numthreads attribute.
+// CHECK:"hlsl.numthreads"="16,8,1"
 // CHECK:"hlsl.shader"="compute"
-[numthreads(1,1,1)]
+[numthreads(16,8,1)]
 void foo() {
 
 }
Index: clang/lib/CodeGen/CGHLSLRuntime.cpp
===
--- clang/lib/CodeGen/CGHLSLRuntime.cpp
+++ clang/lib/CodeGen/CGHLSLRuntime.cpp
@@ -19,6 +19,7 @@
 #include "llvm/IR/IntrinsicsDirectX.h"
 #include "llvm/IR/Metadata.h"
 #include "llvm/IR/Module.h"
+#include "llvm/Support/FormatVariadic.h"
 
 using namespace clang;
 using namespace CodeGen;
@@ -98,6 +99,13 @@
   const StringRef ShaderAttrKindStr = "hlsl.shader";
   Fn->addFnAttr(ShaderAttrKindStr,
 ShaderAttr->ConvertShaderTypeToStr(ShaderAttr->getType()));
+  if (HLSLNumThreadsAttr *NumThreadsAttr = FD->getAttr()) {
+const StringRef NumThreadsKindStr = "hlsl.numthreads";
+std::string NumThreadsStr =
+formatv("{0},{1},{2}", NumThreadsAttr->getX(), NumThreadsAttr->getY(),
+NumThreadsAttr->getZ());
+Fn->addFnAttr(NumThreadsKindStr, NumThreadsStr);
+  }
 }
 
 llvm::Value *CGHLSLRuntime::emitInputSemantic(IRBuilder<> &B,


Index: clang/test/CodeGenHLSL/entry.hlsl
===
--- clang/test/CodeGenHLSL/entry.hlsl
+++ clang/test/CodeGenHLSL/entry.hlsl
@@ -2,9 +2,10 @@
 
 // Make sure not mangle entry.
 // CHECK:define void @foo()
-// Make sure add function attribute.
+// Make sure add function attribute and numthreads attribute.
+// CHECK:"hlsl.numthreads"="16,8,1"
 // CHECK:"hlsl.shader"="compute"
-[numthreads(1,1,1)]
+[numthreads(16,8,1)]
 void foo() {
 
 }
Index: clang/lib/CodeGen/CGHLSLRuntime.cpp
===
--- clang/lib/CodeGen/CGHLSLRuntime.cpp
+++ clang/lib/CodeGen/CGHLSLRuntime.cpp
@@ -19,6 +19,7 @@
 #include "llvm/IR/IntrinsicsDirectX.h"
 #include "llvm/IR/Metadata.h"
 #include "llvm/IR/Module.h"
+#include "llvm/Support/FormatVariadic.h"
 
 using namespace clang;
 using namespace CodeGen;
@@ -98,6 +99,13 @@
   const StringRef ShaderAttrKindStr = "hlsl.shader";
   Fn->addFnAttr(ShaderAttrKindStr,
 ShaderAttr->ConvertShaderTypeToStr(ShaderAttr->getType()));
+  if (HLSLNumThreadsAttr *NumThreadsAttr = FD->getAttr()) {
+const StringRef NumThreadsKindStr = "hlsl.numthreads";
+std::string NumThreadsStr =
+formatv("{0},{1},{2}", NumThreadsAttr->getX(), NumThreadsAttr->getY(),
+NumThreadsAttr->getZ());
+Fn->addFnAttr(NumThreadsKindStr, NumThreadsStr);
+  }
 }
 
 llvm::Value *CGHLSLRuntime::emitInputSemantic(IRBuilder<> &B,
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D132749: Expose QualType::getUnqualifiedType in libclang

2022-08-26 Thread Luca Di sera via Phabricator via cfe-commits
diseraluca added a comment.

I recently encountered a few cases, at work, as an employee of The Qt Company, 
where we would have liked to have access to `getUnqualifiedType` in libclang.

I found a precedence on the old mailing list, from 2018 
(https://lists.llvm.org/pipermail/cfe-dev/2018-February/056874.html), for a 
similar request, where it seemed it wouldn't be disruptive to expose it to 
libclang.

This is my first contribution to llvm-project, so I apologize if I missed some 
requirement or pushed a patch that is incorrect. 
I'm obviously open to spend more time on this patch if there is something that 
should be modified.

Originally the patch contained the addition of `clang_getNonReferenceType` too, 
as that is something else that we would like to have access to.
I avoided including it into this patch because:

- As I understand it, having both in one patch would not comply with the 
isolated changes requirement in 
https://www.llvm.org/docs/Contributing.html#how-to-submit-a-patch.
- I could not find any precedence for requesting that specific interface and am 
unsure if the correct etiquette requires that a discussion is opened BEFORE 
pushing this kind of patch.
- First pushing a smaller patch would allow me to get accustomed to the 
contributing workflow and understand what I might have done incorrectly, so as 
to push an higher quality patch.

Any clarification on if a patch that exposes `getNonReferencedType` requires a 
discussion to be opened before being pushed for acceptance and review is 
appreciated.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132749

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


[PATCH] D132236: [analyzer] Fix liveness of LazyCompoundVals

2022-08-26 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added a comment.

> So, what you are suggesting here is an alternative solution to the one you 
> already proposed in your last comment?

I was just expanding the initial suggestion but also symbol reaper is too 
complicated for me to make such suggestions confidently. So I'm just sharing 
some ideas but you'll probably have to dig deeper to understand whether they're 
correct.

> Unfortunately, we found many FPs introduced by this change; so this should be 
> definitely blocked.

Interesting, I didn't expect that. It could be insanely valuable to make tests 
out of those so that future generations didn't make the same mistake! Symbol 
reaper seems to be very under-tested for its complexity.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132236

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


[PATCH] D131979: [clang][UBSan] Fix __builtin_assume_aligned crash

2022-08-26 Thread John McCall via Phabricator via cfe-commits
rjmccall added a comment.

From the test case, it looks like the builtin just ignores pointer to volatile, 
which should be preserved by the conversions you're now doing in Sema.  That 
is, you should be able to just check 
`Ptr->getType()->castAs()->isVolatile()`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131979

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


[PATCH] D132030: [analyzer] Pass correct bldrCtx to computeObjectUnderConstruction

2022-08-26 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added inline comments.



Comment at: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h:753
 
-SVal V = computeObjectUnderConstruction(E, State, LCtx, CC, CallOpts, Idx);
+SVal V = computeObjectUnderConstruction(E, State, currBldrCtx, LCtx, CC,
+CallOpts, Idx);

tomasz-kaminski-sonarsource wrote:
> tomasz-kaminski-sonarsource wrote:
> > NoQ wrote:
> > > You probably want an updated builder context here as well. This function 
> > > should be a simple wrapper, it should be completely interchangeable with 
> > > calling both functions directly.
> > Could you please elaborate more? I would see a reason to create a context 
> > here if I would expect that `currBlrdCtx` refers to a different `Block` 
> > that we want to perform construction in. And there is no indication on 
> > another `Block` being inplay here, and I would construct `NodeBlockCtx` 
> > with same block as `currBldrCtx`.
> > In other words,  I expect this function to be `handeConstructionContext` in 
> > current `Block`. 
> Or to say it differently, I expect `BldCtx` not being `currBldrCtx` to be an 
> unusual situation, that is limited to the construction of return value. Thus 
> having it in `convenience` would only make it more currbesome.
No-no, I mean, it's not any concrete bug that I see, it's maintaining API 
contracts to make the code easy to understand and make it harder to make 
mistakes in the future.

The function `handleConstructionContext()` , by design, is supposed to be 
equivalent to calling `computeObjectUnderConstruction()` and 
`updateObjectsUnderConstruction()`. Whenever someone has to perform both steps, 
they can combine them together with this convenience wrapper.

After your patch, they won't be able to combine the two calls in a situation 
when they need to pass a non-current builder context to 
`computeObjectUnderConstruction()`. I hope they'll be able to figure out that 
they need to add another parameter but I'm worried that they may think "oh this 
big function doesn't need that parameter, let's drop it". Because the bug 
you've found is quite subtle, it's easy to miss why we even need to pass that 
parameter.

So I suggest to add the new parameter to `handleConstructionContext()` as well, 
and pass it manually on all call sites.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132030

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


[PATCH] D132749: Expose QualType::getUnqualifiedType in libclang

2022-08-26 Thread Luca Di sera via Phabricator via cfe-commits
diseraluca created this revision.
diseraluca added a reviewer: aaron.ballman.
Herald added a subscriber: arphaman.
Herald added a project: All.
diseraluca requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

The method is now wrapped by `clang_getUnqualifiedType`.

A declaration for `clang_getUnqualifiedType` was added to
`clang-c/Index.h` to expose it to user of the library.

An implementation for `clang_getUnqualifiedType` was introduced in
`CXType.cpp` that wraps the equivalent method of the underlying
`QualType` of a `CXType`.

An export symbol was added to `libclang.map` under the new version entry
`LLVM_16`.

A test was added to `LibclangTest.cpp` that tests the removal of
qualifiers for some `CXType`s.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D132749

Files:
  clang/include/clang-c/Index.h
  clang/tools/libclang/CXType.cpp
  clang/tools/libclang/libclang.map
  clang/unittests/libclang/LibclangTest.cpp

Index: clang/unittests/libclang/LibclangTest.cpp
===
--- clang/unittests/libclang/LibclangTest.cpp
+++ clang/unittests/libclang/LibclangTest.cpp
@@ -843,6 +843,54 @@
   },
   nullptr);
 }
+
+TEST_F(LibclangParseTest, clang_getUnqualifiedTypeRemovesQualifiers) {
+  std::string Header = "header.h";
+  WriteFile(Header, "void foo1(const int);\n"
+"void foo2(volatile int);\n"
+"void foo3(const volatile int);\n"
+"void foo4(int* const);\n"
+"void foo5(int* volatile);\n"
+"void foo6(int* restrict);\n"
+"void foo7(int* const volatile);\n"
+"void foo8(int* volatile restrict);\n"
+"void foo9(int* const restrict);\n"
+"void foo10(int* const volatile restrict);\n");
+
+  auto is_qualified = [](CXType type) -> bool {
+return clang_isConstQualifiedType(type) ||
+   clang_isVolatileQualifiedType(type) ||
+   clang_isRestrictQualifiedType(type);
+  };
+
+  auto from_CXString = [](CXString cx_string) -> std::string {
+std::string string{clang_getCString(cx_string)};
+
+clang_disposeString(cx_string);
+
+return string;
+  };
+
+  ClangTU = clang_parseTranslationUnit(Index, Header.c_str(), nullptr, 0,
+   nullptr, 0, TUFlags);
+
+  Traverse([&is_qualified, &from_CXString](CXCursor cursor, CXCursor) {
+if (clang_getCursorKind(cursor) == CXCursor_FunctionDecl) {
+  CXType arg_type = clang_getArgType(clang_getCursorType(cursor), 0);
+  EXPECT_TRUE(is_qualified(arg_type))
+  << "Input data '" << from_CXString(clang_getCursorSpelling(cursor))
+  << "' first argument does not have a qualified type.";
+
+  CXType unqualified_arg_type = clang_getUnqualifiedType(arg_type);
+  EXPECT_FALSE(is_qualified(unqualified_arg_type))
+  << "The type '" << from_CXString(clang_getTypeSpelling(arg_type))
+  << "' was not unqualified after a call to clang_getUnqualifiedType.";
+}
+
+return CXChildVisit_Continue;
+  });
+}
+
 class LibclangRewriteTest : public LibclangParseTest {
 public:
   CXRewriter Rew = nullptr;
Index: clang/tools/libclang/libclang.map
===
--- clang/tools/libclang/libclang.map
+++ clang/tools/libclang/libclang.map
@@ -405,6 +405,11 @@
   local: *;
 };
 
+LLVM_16 {
+  global:
+clang_getUnqualifiedType;
+};
+
 # Example of how to add a new symbol version entry.  If you do add a new symbol
 # version, please update the example to depend on the version you added.
 # LLVM_X {
Index: clang/tools/libclang/CXType.cpp
===
--- clang/tools/libclang/CXType.cpp
+++ clang/tools/libclang/CXType.cpp
@@ -484,6 +484,10 @@
   return MakeCXType(T, GetTU(CT));
 }
 
+CXType clang_getUnqualifiedType(CXType CT) {
+  return MakeCXType(GetQualType(CT).getUnqualifiedType(), GetTU(CT));
+}
+
 CXCursor clang_getTypeDeclaration(CXType CT) {
   if (CT.kind == CXType_Invalid)
 return cxcursor::MakeCXCursorInvalid(CXCursor_NoDeclFound);
Index: clang/include/clang-c/Index.h
===
--- clang/include/clang-c/Index.h
+++ clang/include/clang-c/Index.h
@@ -3760,6 +3760,43 @@
  */
 CINDEX_LINKAGE CXType clang_getPointeeType(CXType T);
 
+/**
+ * Retrieve the unqualified variant of the given type, removing as
+ * little sugar as possible.
+ *
+ * For example, given the following series of typedefs:
+ *
+ * \code
+ * typedef int Integer;
+ * typedef const Integer CInteger;
+ * typedef CInteger DifferenceType;
+ * \endcode
+ *
+ * Executing \c clang_getUnuqalifiedType() on a \c CXType that
+ * represents \c DifferenceType, will desugar to a type representing
+ * \c Integer, that has no qualifiers.
+ *
+ * And, executing

[PATCH] D131979: [clang][UBSan] Fix __builtin_assume_aligned crash

2022-08-26 Thread Wang Yihan via Phabricator via cfe-commits
yihanaa added a comment.

In D131979#3752131 , @rjmccall wrote:

> I'm a little worried about the shift to emit an unconditional error on 
> `volatile`.  Can we at least separate that into its own patch and just fix 
> the bug in this one?  And please try to reach out whoever originally added 
> this feature to see if that restriction is okay vs. just ignoring it, because 
> it certainly looks like the `volatile` exception was intentionally designed.
>
> Other than that, this looks great, thank you.

Thanks for your review, John,I agree. If we just fix this crash, I didn't think 
of a good way to remove the call to getSubExprAsWritten in CodeGen. But I'll 
try to fix crash first.

Maybe there should be a discussion about emit an error for volatile in the 
community.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131979

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


[PATCH] D132186: Clang: Add a new flag Wmisnoinline for printing hot noinline functions

2022-08-26 Thread Paul Kirth via Phabricator via cfe-commits
paulkirth added a comment.

In D132186#3751985 , @tejohnson wrote:

> I have seen a few cases where noinline was used for performance, in addition 
> to other cases like avoiding too much stack growth.

Well, I stand corrected. I'm curious about what these cases are, but in any 
case if there are cases where its done, then I agree that a diagnostic would be 
helpful.

> I've also seen it used without any comment whatsoever. So I think it would be 
> good to make it easier to identify cases where we are blocked from inlining 
> at hot callsites because of the attribute.

I wonder if there is some analysis or heuristic we could use to distinguish 
those cases? Nothing really comes to mind, but it would be nice if we had one.

> It is a little different than misexpect though in that the expect hints are 
> pretty much only for performance, so it is more useful to be able to issue a 
> strong warning that can be turned into an error if they are wrong. And also 
> there was no way to report the misuse of expects earlier, unlike inlining 
> where we already had the remarks plumbing.
>
> I haven't looked through the patch in detail, but is it possible to use your 
> changes to emit a better missed opt remark from the inliner for these cases 
> (I assume we will already emit a -Rpass-missed=inline for the noinline 
> attribute case, just not highlighting that it is hot and would have been 
> inlined for performance reasons otherwise)? I suppose one main reason for 
> adding a warning is that the missed inline remarks can be really noisy and 
> not really useful to the user vs a compiler optimization engineer doing 
> inliner/compiler tuning, and therefore a warning would make it easier to turn 
> on more widely as user feedback that can/should be addressed in user code.

Yeah, I was thinking we could emit a new remark type for this to differentiate, 
but it seems simpler more user friendly to emit some clar diagnostic directly.

I think we’re starting to accumulate a few of these diagnostics now that are 
trying to diagnose potential performance deficiencies based on profiling 
information. Originally we had prototyped a tool for misexpect based on 
libtooling that ran over the build based on the compile commands DB and 
reported everything it found.  I wonder if reviving that would be useful in 
these cases when you want to look for performance issues like this, misexpect, 
and other cases? Making ORE diagnostic output queryable through a tool may also 
be a good option, but I'm not too familiar with what already exists in that 
area.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132186

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


[PATCH] D128745: [c++] implements DR692, DR1395 and tentatively DR1432, about partial ordering of variadic template partial specialization or function template

2022-08-26 Thread Yuanfang Chen via Phabricator via cfe-commits
ychen added a comment.

In D128745#3751471 , @joanahalili 
wrote:

> We have some compilation failures on our end because of function template 
> parameter deduction when passing the function template to a function pointer.
>
>   typedef void (*f)(const int&);
>   
>   template 
>   void F(T value) {}
>   
>   template 
>   void F(const T& value){}
>   
>   void q(f);
>   
>   void w() {
>   q(&F);
>   }
>
> https://gcc.godbolt.org/z/faoq74q7G
> Is this an intended outcome for this patch?

Thanks for the report. No that's not the intent. This should only affect 
partial ordering but not which candidate is viable (error message `candidate 
function not viable ...`). I'll take a look.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128745

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


[PATCH] D132712: [Clang] Fix assert in Sema::LookupTemplateName so that it does not attempt an unconditional cast to TagType

2022-08-26 Thread Shafik Yaghmour via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG21dfe482e13e: [Clang] Fix assert in Sema::LookupTemplateName 
so that it does not attempt an… (authored by shafik).
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132712

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Sema/SemaTemplate.cpp
  clang/test/SemaCXX/member-expr.cpp


Index: clang/test/SemaCXX/member-expr.cpp
===
--- clang/test/SemaCXX/member-expr.cpp
+++ clang/test/SemaCXX/member-expr.cpp
@@ -228,3 +228,19 @@
 .i;  // expected-error {{member reference type 'S *' is a pointer; did 
you mean to use '->'}}
   }
 }
+
+namespace LookupTemplateNameAssert {
+void f() {}
+
+typedef int at[];
+const at& f2(){}
+
+void g() {
+  f().junk(); // expected-error {{member reference base type 'void' is 
not a structure or union}}
+// expected-error@-1 {{expected '(' for function-style cast or type 
construction}}
+// expected-error@-2 {{expected expression}}
+  f2().junk(); // expected-error {{member reference base type 'const at' 
(aka 'const int[]') is not a structure or union}}
+// expected-error@-1 {{expected '(' for function-style cast or type 
construction}}
+// expected-error@-2 {{expected expression}}
+}
+}
Index: clang/lib/Sema/SemaTemplate.cpp
===
--- clang/lib/Sema/SemaTemplate.cpp
+++ clang/lib/Sema/SemaTemplate.cpp
@@ -399,6 +399,7 @@
 LookupCtx = computeDeclContext(ObjectType);
 IsDependent = !LookupCtx && ObjectType->isDependentType();
 assert((IsDependent || !ObjectType->isIncompleteType() ||
+!ObjectType->getAs() ||
 ObjectType->castAs()->isBeingDefined()) &&
"Caller should have completed object type");
 
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -81,6 +81,9 @@
 - Fix a crash when generating code coverage information for an
   ``if consteval`` statement. This fixes
   `Issue 57377 `_.
+- Fix assert that triggers a crash during template name lookup when a type was
+  incomplete but was not also a TagType. This fixes
+  `Issue 57387 `_.
 
 
 Improvements to Clang's diagnostics


Index: clang/test/SemaCXX/member-expr.cpp
===
--- clang/test/SemaCXX/member-expr.cpp
+++ clang/test/SemaCXX/member-expr.cpp
@@ -228,3 +228,19 @@
 .i;  // expected-error {{member reference type 'S *' is a pointer; did you mean to use '->'}}
   }
 }
+
+namespace LookupTemplateNameAssert {
+void f() {}
+
+typedef int at[];
+const at& f2(){}
+
+void g() {
+  f().junk(); // expected-error {{member reference base type 'void' is not a structure or union}}
+// expected-error@-1 {{expected '(' for function-style cast or type construction}}
+// expected-error@-2 {{expected expression}}
+  f2().junk(); // expected-error {{member reference base type 'const at' (aka 'const int[]') is not a structure or union}}
+// expected-error@-1 {{expected '(' for function-style cast or type construction}}
+// expected-error@-2 {{expected expression}}
+}
+}
Index: clang/lib/Sema/SemaTemplate.cpp
===
--- clang/lib/Sema/SemaTemplate.cpp
+++ clang/lib/Sema/SemaTemplate.cpp
@@ -399,6 +399,7 @@
 LookupCtx = computeDeclContext(ObjectType);
 IsDependent = !LookupCtx && ObjectType->isDependentType();
 assert((IsDependent || !ObjectType->isIncompleteType() ||
+!ObjectType->getAs() ||
 ObjectType->castAs()->isBeingDefined()) &&
"Caller should have completed object type");
 
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -81,6 +81,9 @@
 - Fix a crash when generating code coverage information for an
   ``if consteval`` statement. This fixes
   `Issue 57377 `_.
+- Fix assert that triggers a crash during template name lookup when a type was
+  incomplete but was not also a TagType. This fixes
+  `Issue 57387 `_.
 
 
 Improvements to Clang's diagnostics
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 21dfe48 - [Clang] Fix assert in Sema::LookupTemplateName so that it does not attempt an unconditional cast to TagType

2022-08-26 Thread Shafik Yaghmour via cfe-commits

Author: Shafik Yaghmour
Date: 2022-08-26T09:40:43-07:00
New Revision: 21dfe482e13e3b64801372f8b3db75eeb85b3135

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

LOG: [Clang] Fix assert in Sema::LookupTemplateName so that it does not attempt 
an unconditional cast to TagType

In Sema::LookupTemplateName(...) seeks to assert that the ObjectType is complete
or being defined. If the type is incomplete it will attempt to unconditionally
cast it to a TagType and not all incomplete types are a TagType. For example the
type could be void or it could be an IncompleteArray.

This change adds an additional check to confirm it is a TagType before 
attempting
to check if it is incomplete or being defined

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

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/SemaTemplate.cpp
clang/test/SemaCXX/member-expr.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index b6d1dbedb2c59..b19a81e848387 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -81,6 +81,9 @@ Bug Fixes
 - Fix a crash when generating code coverage information for an
   ``if consteval`` statement. This fixes
   `Issue 57377 `_.
+- Fix assert that triggers a crash during template name lookup when a type was
+  incomplete but was not also a TagType. This fixes
+  `Issue 57387 `_.
 
 
 Improvements to Clang's diagnostics

diff  --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 1d9c364771927..b06612d02797b 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -399,6 +399,7 @@ bool Sema::LookupTemplateName(LookupResult &Found,
 LookupCtx = computeDeclContext(ObjectType);
 IsDependent = !LookupCtx && ObjectType->isDependentType();
 assert((IsDependent || !ObjectType->isIncompleteType() ||
+!ObjectType->getAs() ||
 ObjectType->castAs()->isBeingDefined()) &&
"Caller should have completed object type");
 

diff  --git a/clang/test/SemaCXX/member-expr.cpp 
b/clang/test/SemaCXX/member-expr.cpp
index 3497ef596480e..75c9ef0caa2e0 100644
--- a/clang/test/SemaCXX/member-expr.cpp
+++ b/clang/test/SemaCXX/member-expr.cpp
@@ -228,3 +228,19 @@ namespace pr16676 {
 .i;  // expected-error {{member reference type 'S *' is a pointer; did 
you mean to use '->'}}
   }
 }
+
+namespace LookupTemplateNameAssert {
+void f() {}
+
+typedef int at[];
+const at& f2(){}
+
+void g() {
+  f().junk(); // expected-error {{member reference base type 'void' is 
not a structure or union}}
+// expected-error@-1 {{expected '(' for function-style cast or type 
construction}}
+// expected-error@-2 {{expected expression}}
+  f2().junk(); // expected-error {{member reference base type 'const at' 
(aka 'const int[]') is not a structure or union}}
+// expected-error@-1 {{expected '(' for function-style cast or type 
construction}}
+// expected-error@-2 {{expected expression}}
+}
+}



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


[PATCH] D131979: [clang][UBSan] Fix __builtin_assume_aligned crash

2022-08-26 Thread John McCall via Phabricator via cfe-commits
rjmccall added a comment.

I'm a little worried about the shift to emit an unconditional error on 
`volatile`.  Can we at least separate that into its own patch and just fix the 
bug in this one?  And please try to reach out whoever originally added this 
feature to see if that restriction is okay vs. just ignoring it, because it 
certainly looks like the `volatile` exception was intentionally designed.

Other than that, this looks great, thank you.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131979

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


[PATCH] D132712: [Clang] Fix assert in Sema::LookupTemplateName so that it does not attempt an unconditional cast to TagType

2022-08-26 Thread Erich Keane via Phabricator via cfe-commits
erichkeane accepted this revision.
erichkeane added a comment.

LGTM.


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

https://reviews.llvm.org/D132712

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


[PATCH] D130207: [HLSL] Move DXIL validation version out of ModuleFlags

2022-08-26 Thread Xiang Li via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGa0ecb4a2991d: [HLSL] Move DXIL validation version out of 
ModuleFlags (authored by python3kgae).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130207

Files:
  clang/lib/CodeGen/CGHLSLRuntime.cpp
  clang/test/CodeGenHLSL/validator_version.hlsl
  llvm/lib/Target/DirectX/DXILTranslateMetadata.cpp
  llvm/test/CodeGen/DirectX/dxil_ver.ll

Index: llvm/test/CodeGen/DirectX/dxil_ver.ll
===
--- llvm/test/CodeGen/DirectX/dxil_ver.ll
+++ llvm/test/CodeGen/DirectX/dxil_ver.ll
@@ -3,18 +3,18 @@
 target triple = "dxil-pc-shadermodel6.3-library"
 
 ; Make sure dx.valver metadata is generated.
-; CHECK:!dx.valver = !{![[valver:[0-9]+]]}
+; CHECK-DAG:!dx.valver = !{![[valver:[0-9]+]]}
 ; Make sure module flags still exist and only have 1 operand left.
-; CHECK:!llvm.module.flags = !{{{![0-9]}}}
+; CHECK-DAG:!llvm.module.flags = !{{{![0-9]}}}
 ; Make sure validator version is 1.1.
-; CHECK:![[valver]] = !{i32 1, i32 1}
+; CHECK-DAG:![[valver]] = !{i32 1, i32 1}
 ; Make sure wchar_size still exist.
-; CHECK:!{i32 1, !"wchar_size", i32 4}
+; CHECK-DAG:!{i32 1, !"wchar_size", i32 4}
 
-!llvm.module.flags = !{!0, !1}
-!llvm.ident = !{!3}
+!llvm.module.flags = !{!0}
+!dx.valver = !{!1}
+!llvm.ident = !{!2}
 
 !0 = !{i32 1, !"wchar_size", i32 4}
-!1 = !{i32 6, !"dx.valver", !2}
-!2 = !{i32 1, i32 1}
-!3 = !{!"clang version 15.0.0 (https://github.com/llvm/llvm-project 71de12113a0661649ecb2f533fba4a2818a1ad68)"}
+!1 = !{i32 1, i32 1}
+!2 = !{!"clang version 15.0.0 (https://github.com/llvm/llvm-project 71de12113a0661649ecb2f533fba4a2818a1ad68)"}
Index: llvm/lib/Target/DirectX/DXILTranslateMetadata.cpp
===
--- llvm/lib/Target/DirectX/DXILTranslateMetadata.cpp
+++ llvm/lib/Target/DirectX/DXILTranslateMetadata.cpp
@@ -58,32 +58,6 @@
   return VersionTuple(Major, Minor);
 }
 
-static void cleanModuleFlags(Module &M) {
-  constexpr StringLiteral DeadKeys[] = {ValVerKey};
-  // Collect DeadKeys in ModuleFlags.
-  StringSet<> DeadKeySet;
-  for (auto &Key : DeadKeys) {
-if (M.getModuleFlag(Key))
-  DeadKeySet.insert(Key);
-  }
-  if (DeadKeySet.empty())
-return;
-
-  SmallVector ModuleFlags;
-  M.getModuleFlagsMetadata(ModuleFlags);
-  NamedMDNode *MDFlags = M.getModuleFlagsMetadata();
-  MDFlags->eraseFromParent();
-  // Add ModuleFlag which not dead.
-  for (auto &Flag : ModuleFlags) {
-StringRef Key = Flag.Key->getString();
-if (DeadKeySet.contains(Key))
-  continue;
-M.addModuleFlag(Flag.Behavior, Key, Flag.Val);
-  }
-}
-
-static void cleanModule(Module &M) { cleanModuleFlags(M); }
-
 namespace {
 class DXILTranslateMetadata : public ModulePass {
 public:
@@ -101,13 +75,12 @@
 } // namespace
 
 bool DXILTranslateMetadata::runOnModule(Module &M) {
-  if (MDNode *ValVerMD = cast_or_null(M.getModuleFlag(ValVerKey))) {
-auto ValVer = loadDXILValidatorVersion(ValVerMD);
+  if (NamedMDNode *ValVerMD = M.getNamedMetadata(ValVerKey)) {
+VersionTuple ValVer = loadDXILValidatorVersion(ValVerMD->getOperand(0));
 if (!ValVer.empty())
   ValidatorVer = ValVer;
   }
   emitDXILValidatorVersion(M, ValidatorVer);
-  cleanModule(M);
   return false;
 }
 
Index: clang/test/CodeGenHLSL/validator_version.hlsl
===
--- clang/test/CodeGenHLSL/validator_version.hlsl
+++ clang/test/CodeGenHLSL/validator_version.hlsl
@@ -1,8 +1,11 @@
 // RUN: %clang -cc1 -S -triple dxil-pc-shadermodel6.3-library -S -emit-llvm -xhlsl -validator-version 1.1 -o - %s | FileCheck %s
+// RUN: %clang -cc1 -S -triple spirv32 -S -emit-llvm -xhlsl -validator-version 1.1 -o - %s | FileCheck %s --check-prefix=NOT_DXIL
 
-// CHECK:!"dx.valver", ![[valver:[0-9]+]]}
+// CHECK:!dx.valver = !{![[valver:[0-9]+]]}
 // CHECK:![[valver]] = !{i32 1, i32 1}
 
+// NOT_DXIL-NOT:!dx.valver
+
 float bar(float a, float b);
 
 float foo(float a, float b) {
Index: clang/lib/CodeGen/CGHLSLRuntime.cpp
===
--- clang/lib/CodeGen/CGHLSLRuntime.cpp
+++ clang/lib/CodeGen/CGHLSLRuntime.cpp
@@ -42,16 +42,18 @@
   IRBuilder<> B(M.getContext());
   MDNode *Val = MDNode::get(Ctx, {ConstantAsMetadata::get(B.getInt32(Major)),
   ConstantAsMetadata::get(B.getInt32(Minor))});
-  StringRef DxilValKey = "dx.valver";
-  M.addModuleFlag(llvm::Module::ModFlagBehavior::AppendUnique, DxilValKey, Val);
+  StringRef DXILValKey = "dx.valver";
+  auto *DXILValMD = M.getOrInsertNamedMetadata(DXILValKey);
+  DXILValMD->addOperand(Val);
 }
 } // namespace
 
 void CGHLSLRuntime::finishCodeGen() {
   auto &TargetOpts = CGM.getTarget().getTargetOpts();
-
   llvm::Module &M = CGM.getModule();
-  addDxilValVersion(TargetOpts.DxilValidato

[clang] a0ecb4a - [HLSL] Move DXIL validation version out of ModuleFlags

2022-08-26 Thread Xiang Li via cfe-commits

Author: Xiang Li
Date: 2022-08-26T09:20:45-07:00
New Revision: a0ecb4a2991d6163c16c29bee8cd63720ee7d3d7

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

LOG: [HLSL] Move DXIL validation version out of ModuleFlags

Put DXIL validation version into separate NamedMetadata to avoid update 
ModuleFlags.

Currently DXIL validation version is saved in ModuleFlags in clang codeGen.
Then in DirectX backend, the data will be extracted from ModuleFlags and cause 
rebuild of ModuleFlags.
This patch will build NamedMetadata for DXIL validation version and remove the 
code to rebuild ModuleFlags.

Reviewed By: beanz

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

Added: 


Modified: 
clang/lib/CodeGen/CGHLSLRuntime.cpp
clang/test/CodeGenHLSL/validator_version.hlsl
llvm/lib/Target/DirectX/DXILTranslateMetadata.cpp
llvm/test/CodeGen/DirectX/dxil_ver.ll

Removed: 




diff  --git a/clang/lib/CodeGen/CGHLSLRuntime.cpp 
b/clang/lib/CodeGen/CGHLSLRuntime.cpp
index fa7bab9121b7a..9ca3b64996edd 100644
--- a/clang/lib/CodeGen/CGHLSLRuntime.cpp
+++ b/clang/lib/CodeGen/CGHLSLRuntime.cpp
@@ -42,16 +42,18 @@ void addDxilValVersion(StringRef ValVersionStr, 
llvm::Module &M) {
   IRBuilder<> B(M.getContext());
   MDNode *Val = MDNode::get(Ctx, {ConstantAsMetadata::get(B.getInt32(Major)),
   ConstantAsMetadata::get(B.getInt32(Minor))});
-  StringRef DxilValKey = "dx.valver";
-  M.addModuleFlag(llvm::Module::ModFlagBehavior::AppendUnique, DxilValKey, 
Val);
+  StringRef DXILValKey = "dx.valver";
+  auto *DXILValMD = M.getOrInsertNamedMetadata(DXILValKey);
+  DXILValMD->addOperand(Val);
 }
 } // namespace
 
 void CGHLSLRuntime::finishCodeGen() {
   auto &TargetOpts = CGM.getTarget().getTargetOpts();
-
   llvm::Module &M = CGM.getModule();
-  addDxilValVersion(TargetOpts.DxilValidatorVersion, M);
+  Triple T(M.getTargetTriple());
+  if (T.getArch() == Triple::ArchType::dxil)
+addDxilValVersion(TargetOpts.DxilValidatorVersion, M);
 }
 
 void CGHLSLRuntime::annotateHLSLResource(const VarDecl *D, GlobalVariable *GV) 
{

diff  --git a/clang/test/CodeGenHLSL/validator_version.hlsl 
b/clang/test/CodeGenHLSL/validator_version.hlsl
index eee83bd9677be..426918a7221c4 100644
--- a/clang/test/CodeGenHLSL/validator_version.hlsl
+++ b/clang/test/CodeGenHLSL/validator_version.hlsl
@@ -1,8 +1,11 @@
 // RUN: %clang -cc1 -S -triple dxil-pc-shadermodel6.3-library -S -emit-llvm 
-xhlsl -validator-version 1.1 -o - %s | FileCheck %s
+// RUN: %clang -cc1 -S -triple spirv32 -S -emit-llvm -xhlsl -validator-version 
1.1 -o - %s | FileCheck %s --check-prefix=NOT_DXIL
 
-// CHECK:!"dx.valver", ![[valver:[0-9]+]]}
+// CHECK:!dx.valver = !{![[valver:[0-9]+]]}
 // CHECK:![[valver]] = !{i32 1, i32 1}
 
+// NOT_DXIL-NOT:!dx.valver
+
 float bar(float a, float b);
 
 float foo(float a, float b) {

diff  --git a/llvm/lib/Target/DirectX/DXILTranslateMetadata.cpp 
b/llvm/lib/Target/DirectX/DXILTranslateMetadata.cpp
index 634ead98a6ae7..85f1b0784cda3 100644
--- a/llvm/lib/Target/DirectX/DXILTranslateMetadata.cpp
+++ b/llvm/lib/Target/DirectX/DXILTranslateMetadata.cpp
@@ -58,32 +58,6 @@ static VersionTuple loadDXILValidatorVersion(MDNode 
*ValVerMD) {
   return VersionTuple(Major, Minor);
 }
 
-static void cleanModuleFlags(Module &M) {
-  constexpr StringLiteral DeadKeys[] = {ValVerKey};
-  // Collect DeadKeys in ModuleFlags.
-  StringSet<> DeadKeySet;
-  for (auto &Key : DeadKeys) {
-if (M.getModuleFlag(Key))
-  DeadKeySet.insert(Key);
-  }
-  if (DeadKeySet.empty())
-return;
-
-  SmallVector ModuleFlags;
-  M.getModuleFlagsMetadata(ModuleFlags);
-  NamedMDNode *MDFlags = M.getModuleFlagsMetadata();
-  MDFlags->eraseFromParent();
-  // Add ModuleFlag which not dead.
-  for (auto &Flag : ModuleFlags) {
-StringRef Key = Flag.Key->getString();
-if (DeadKeySet.contains(Key))
-  continue;
-M.addModuleFlag(Flag.Behavior, Key, Flag.Val);
-  }
-}
-
-static void cleanModule(Module &M) { cleanModuleFlags(M); }
-
 namespace {
 class DXILTranslateMetadata : public ModulePass {
 public:
@@ -101,13 +75,12 @@ class DXILTranslateMetadata : public ModulePass {
 } // namespace
 
 bool DXILTranslateMetadata::runOnModule(Module &M) {
-  if (MDNode *ValVerMD = cast_or_null(M.getModuleFlag(ValVerKey))) {
-auto ValVer = loadDXILValidatorVersion(ValVerMD);
+  if (NamedMDNode *ValVerMD = M.getNamedMetadata(ValVerKey)) {
+VersionTuple ValVer = loadDXILValidatorVersion(ValVerMD->getOperand(0));
 if (!ValVer.empty())
   ValidatorVer = ValVer;
   }
   emitDXILValidatorVersion(M, ValidatorVer);
-  cleanModule(M);
   return false;
 }
 

diff  --git a/llvm/test/CodeGen/DirectX/dxil_ver.ll 
b/llvm/test/CodeGen/DirectX/dxil_ver.ll
index dcc9b6a797f6a..e9923a3abce02 100644
--- a/l

[PATCH] D132712: [Clang] Fix assert in Sema::LookupTemplateName so that it does not attempt an unconditional cast to TagType

2022-08-26 Thread Shafik Yaghmour via Phabricator via cfe-commits
shafik updated this revision to Diff 455935.
shafik marked an inline comment as done.
shafik added a comment.

- Change to order of operations in assert to put off more costly check
- Add release note


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

https://reviews.llvm.org/D132712

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Sema/SemaTemplate.cpp
  clang/test/SemaCXX/member-expr.cpp


Index: clang/test/SemaCXX/member-expr.cpp
===
--- clang/test/SemaCXX/member-expr.cpp
+++ clang/test/SemaCXX/member-expr.cpp
@@ -228,3 +228,19 @@
 .i;  // expected-error {{member reference type 'S *' is a pointer; did 
you mean to use '->'}}
   }
 }
+
+namespace LookupTemplateNameAssert {
+void f() {}
+
+typedef int at[];
+const at& f2(){}
+
+void g() {
+  f().junk(); // expected-error {{member reference base type 'void' is 
not a structure or union}}
+// expected-error@-1 {{expected '(' for function-style cast or type 
construction}}
+// expected-error@-2 {{expected expression}}
+  f2().junk(); // expected-error {{member reference base type 'const at' 
(aka 'const int[]') is not a structure or union}}
+// expected-error@-1 {{expected '(' for function-style cast or type 
construction}}
+// expected-error@-2 {{expected expression}}
+}
+}
Index: clang/lib/Sema/SemaTemplate.cpp
===
--- clang/lib/Sema/SemaTemplate.cpp
+++ clang/lib/Sema/SemaTemplate.cpp
@@ -399,6 +399,7 @@
 LookupCtx = computeDeclContext(ObjectType);
 IsDependent = !LookupCtx && ObjectType->isDependentType();
 assert((IsDependent || !ObjectType->isIncompleteType() ||
+!ObjectType->getAs() ||
 ObjectType->castAs()->isBeingDefined()) &&
"Caller should have completed object type");
 
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -81,6 +81,9 @@
 - Fix a crash when generating code coverage information for an
   ``if consteval`` statement. This fixes
   `Issue 57377 `_.
+- Fix assert that triggers a crash during template name lookup when a type was
+  incomplete but was not also a TagType. This fixes
+  `Issue 57387 `_.
 
 
 Improvements to Clang's diagnostics


Index: clang/test/SemaCXX/member-expr.cpp
===
--- clang/test/SemaCXX/member-expr.cpp
+++ clang/test/SemaCXX/member-expr.cpp
@@ -228,3 +228,19 @@
 .i;  // expected-error {{member reference type 'S *' is a pointer; did you mean to use '->'}}
   }
 }
+
+namespace LookupTemplateNameAssert {
+void f() {}
+
+typedef int at[];
+const at& f2(){}
+
+void g() {
+  f().junk(); // expected-error {{member reference base type 'void' is not a structure or union}}
+// expected-error@-1 {{expected '(' for function-style cast or type construction}}
+// expected-error@-2 {{expected expression}}
+  f2().junk(); // expected-error {{member reference base type 'const at' (aka 'const int[]') is not a structure or union}}
+// expected-error@-1 {{expected '(' for function-style cast or type construction}}
+// expected-error@-2 {{expected expression}}
+}
+}
Index: clang/lib/Sema/SemaTemplate.cpp
===
--- clang/lib/Sema/SemaTemplate.cpp
+++ clang/lib/Sema/SemaTemplate.cpp
@@ -399,6 +399,7 @@
 LookupCtx = computeDeclContext(ObjectType);
 IsDependent = !LookupCtx && ObjectType->isDependentType();
 assert((IsDependent || !ObjectType->isIncompleteType() ||
+!ObjectType->getAs() ||
 ObjectType->castAs()->isBeingDefined()) &&
"Caller should have completed object type");
 
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -81,6 +81,9 @@
 - Fix a crash when generating code coverage information for an
   ``if consteval`` statement. This fixes
   `Issue 57377 `_.
+- Fix assert that triggers a crash during template name lookup when a type was
+  incomplete but was not also a TagType. This fixes
+  `Issue 57387 `_.
 
 
 Improvements to Clang's diagnostics
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D132745: [clang] Fix ambiguous use of `report_fatal_error`.

2022-08-26 Thread weiyi via Phabricator via cfe-commits
wyt created this revision.
Herald added a project: All.
wyt requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

`report_fatal_error` is overloaded on `StringRef` and `Twine &`, therefore 
passing a `std::string` argument leads to ambiguity as it is convertible to 
either type.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D132745

Files:
  clang/lib/Basic/SanitizerSpecialCaseList.cpp


Index: clang/lib/Basic/SanitizerSpecialCaseList.cpp
===
--- clang/lib/Basic/SanitizerSpecialCaseList.cpp
+++ clang/lib/Basic/SanitizerSpecialCaseList.cpp
@@ -33,7 +33,7 @@
   std::string Error;
   if (auto SSCL = create(Paths, VFS, Error))
 return SSCL;
-  llvm::report_fatal_error(Error);
+  llvm::report_fatal_error(llvm::StringRef(Error));
 }
 
 void SanitizerSpecialCaseList::createSanitizerSections() {


Index: clang/lib/Basic/SanitizerSpecialCaseList.cpp
===
--- clang/lib/Basic/SanitizerSpecialCaseList.cpp
+++ clang/lib/Basic/SanitizerSpecialCaseList.cpp
@@ -33,7 +33,7 @@
   std::string Error;
   if (auto SSCL = create(Paths, VFS, Error))
 return SSCL;
-  llvm::report_fatal_error(Error);
+  llvm::report_fatal_error(llvm::StringRef(Error));
 }
 
 void SanitizerSpecialCaseList::createSanitizerSections() {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D132723: [Clang] Fix crash in coverage of if consteval.

2022-08-26 Thread Corentin Jabot via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG463e30f51fd0: [Clang] Fix crash in coverage of if consteval. 
(authored by cor3ntin).

Changed prior to commit:
  https://reviews.llvm.org/D132723?vs=455917&id=455930#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132723

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/CodeGen/CoverageMappingGen.cpp
  clang/test/CoverageMapping/if.cpp

Index: clang/test/CoverageMapping/if.cpp
===
--- clang/test/CoverageMapping/if.cpp
+++ clang/test/CoverageMapping/if.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -mllvm -emptyline-comment-coverage=false -fprofile-instrument=clang -fcoverage-mapping -dump-coverage-mapping -emit-llvm-only -std=c++1z -triple %itanium_abi_triple -main-file-name if.cpp %s | FileCheck %s
+// RUN: %clang_cc1 -mllvm -emptyline-comment-coverage=false -fprofile-instrument=clang -fcoverage-mapping -dump-coverage-mapping -emit-llvm-only -std=c++2b -triple %itanium_abi_triple -main-file-name if.cpp %s | FileCheck %s
 
 int nop() { return 0; }
 
@@ -13,6 +13,22 @@
 ++j;// CHECK-NEXT: Branch,File 0, [[@LINE-1]]:7 -> [[@LINE-1]]:8 = #1, (#0 - #1)
 }   // CHECK-NEXT: [[@LINE-2]]:9 -> [[@LINE-1]]:5 = #1
 // CHECK-NEXT: [[@LINE-2]]:5 -> [[@LINE-2]]:8 = #1
+
+// FIXME: Do not generate coverage for discarded branches in if consteval and if constexpr statements
+constexpr int check_consteval(int i) {
+if consteval {
+  i++;
+}
+if !consteval {
+  i++;
+}
+if consteval {
+return 42;
+} else {
+return i;
+}
+}
+
 // CHECK-LABEL: main:
 int main() {// CHECK: File 0, [[@LINE]]:12 -> {{[0-9]+}}:2 = #0
   int i = 0;
@@ -50,6 +66,10 @@
 // CHECK-NEXT: File 0, [[@LINE+1]]:14 -> [[@LINE+1]]:20 = #6
   i = i == 0?i + 12:i + 10; // CHECK-NEXT: File 0, [[@LINE]]:21 -> [[@LINE]]:27 = (#0 - #6)
 
+  // GH-57377
+  constexpr int c_i = check_consteval(0);
+  check_consteval(i);
+
   return 0;
 }
 
Index: clang/lib/CodeGen/CoverageMappingGen.cpp
===
--- clang/lib/CodeGen/CoverageMappingGen.cpp
+++ clang/lib/CodeGen/CoverageMappingGen.cpp
@@ -1377,19 +1377,23 @@
 
 // Extend into the condition before we propagate through it below - this is
 // needed to handle macros that generate the "if" but not the condition.
-extendRegion(S->getCond());
+if (!S->isConsteval())
+  extendRegion(S->getCond());
 
 Counter ParentCount = getRegion().getCounter();
 Counter ThenCount = getRegionCounter(S);
 
-// Emitting a counter for the condition makes it easier to interpret the
-// counter for the body when looking at the coverage.
-propagateCounts(ParentCount, S->getCond());
+if (!S->isConsteval()) {
+  // Emitting a counter for the condition makes it easier to interpret the
+  // counter for the body when looking at the coverage.
+  propagateCounts(ParentCount, S->getCond());
 
-// The 'then' count applies to the area immediately after the condition.
-auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getThen()));
-if (Gap)
-  fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ThenCount);
+  // The 'then' count applies to the area immediately after the condition.
+  Optional Gap =
+  findGapAreaBetween(S->getRParenLoc(), getStart(S->getThen()));
+  if (Gap)
+fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ThenCount);
+}
 
 extendRegion(S->getThen());
 Counter OutCount = propagateCounts(ThenCount, S->getThen());
@@ -1398,9 +1402,9 @@
 if (const Stmt *Else = S->getElse()) {
   bool ThenHasTerminateStmt = HasTerminateStmt;
   HasTerminateStmt = false;
-
   // The 'else' count applies to the area immediately after the 'then'.
-  Gap = findGapAreaBetween(getEnd(S->getThen()), getStart(Else));
+  Optional Gap =
+  findGapAreaBetween(getEnd(S->getThen()), getStart(Else));
   if (Gap)
 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ElseCount);
   extendRegion(Else);
@@ -1416,9 +1420,11 @@
   GapRegionCounter = OutCount;
 }
 
-// Create Branch Region around condition.
-createBranchRegion(S->getCond(), ThenCount,
-   subtractCounters(ParentCount, ThenCount));
+if (!S->isConsteval()) {
+  // Create Branch Region around condition.
+  createBranchRegion(S->getCond(), ThenCount,
+ subtractCounters(ParentCount, ThenCount));
+}
   }
 
   void VisitCXXTryStmt(const CXXTryStmt *S) {
Index: clang/docs/ReleaseNotes.rst
=

[clang] 463e30f - [Clang] Fix crash in coverage of if consteval.

2022-08-26 Thread Corentin Jabot via cfe-commits

Author: Corentin Jabot
Date: 2022-08-26T17:46:53+02:00
New Revision: 463e30f51fd07921f32c6630afb3f8dd18d6d2f5

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

LOG: [Clang] Fix crash in coverage of if consteval.

Clang crashes when encountering an `if consteval` statement.
This is the minimum fix not to crash.
The fix is consistent with the current behavior of if constexpr,
which does generate coverage data for the discarded branches.
This is of course not correct and a better solution is
needed for both if constexpr and if consteval.
See https://github.com/llvm/llvm-project/issues/54419.

Fixes #57377

Reviewed By: aaron.ballman

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

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/CodeGen/CoverageMappingGen.cpp
clang/test/CoverageMapping/if.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 3f7eec1effd46..b6d1dbedb2c59 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -78,6 +78,10 @@ Bug Fixes
 - ``-Wtautological-compare`` missed warnings for tautological comparisons
   involving a negative integer literal. This fixes
   `Issue 42918 `_.
+- Fix a crash when generating code coverage information for an
+  ``if consteval`` statement. This fixes
+  `Issue 57377 `_.
+
 
 Improvements to Clang's diagnostics
 ^^^

diff  --git a/clang/lib/CodeGen/CoverageMappingGen.cpp 
b/clang/lib/CodeGen/CoverageMappingGen.cpp
index 0fe084b628dab..836aabf80179d 100644
--- a/clang/lib/CodeGen/CoverageMappingGen.cpp
+++ b/clang/lib/CodeGen/CoverageMappingGen.cpp
@@ -1377,19 +1377,23 @@ struct CounterCoverageMappingBuilder
 
 // Extend into the condition before we propagate through it below - this is
 // needed to handle macros that generate the "if" but not the condition.
-extendRegion(S->getCond());
+if (!S->isConsteval())
+  extendRegion(S->getCond());
 
 Counter ParentCount = getRegion().getCounter();
 Counter ThenCount = getRegionCounter(S);
 
-// Emitting a counter for the condition makes it easier to interpret the
-// counter for the body when looking at the coverage.
-propagateCounts(ParentCount, S->getCond());
+if (!S->isConsteval()) {
+  // Emitting a counter for the condition makes it easier to interpret the
+  // counter for the body when looking at the coverage.
+  propagateCounts(ParentCount, S->getCond());
 
-// The 'then' count applies to the area immediately after the condition.
-auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getThen()));
-if (Gap)
-  fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ThenCount);
+  // The 'then' count applies to the area immediately after the condition.
+  Optional Gap =
+  findGapAreaBetween(S->getRParenLoc(), getStart(S->getThen()));
+  if (Gap)
+fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ThenCount);
+}
 
 extendRegion(S->getThen());
 Counter OutCount = propagateCounts(ThenCount, S->getThen());
@@ -1398,9 +1402,9 @@ struct CounterCoverageMappingBuilder
 if (const Stmt *Else = S->getElse()) {
   bool ThenHasTerminateStmt = HasTerminateStmt;
   HasTerminateStmt = false;
-
   // The 'else' count applies to the area immediately after the 'then'.
-  Gap = findGapAreaBetween(getEnd(S->getThen()), getStart(Else));
+  Optional Gap =
+  findGapAreaBetween(getEnd(S->getThen()), getStart(Else));
   if (Gap)
 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ElseCount);
   extendRegion(Else);
@@ -1416,9 +1420,11 @@ struct CounterCoverageMappingBuilder
   GapRegionCounter = OutCount;
 }
 
-// Create Branch Region around condition.
-createBranchRegion(S->getCond(), ThenCount,
-   subtractCounters(ParentCount, ThenCount));
+if (!S->isConsteval()) {
+  // Create Branch Region around condition.
+  createBranchRegion(S->getCond(), ThenCount,
+ subtractCounters(ParentCount, ThenCount));
+}
   }
 
   void VisitCXXTryStmt(const CXXTryStmt *S) {

diff  --git a/clang/test/CoverageMapping/if.cpp 
b/clang/test/CoverageMapping/if.cpp
index 5b705cd46ab72..de3554c100b96 100644
--- a/clang/test/CoverageMapping/if.cpp
+++ b/clang/test/CoverageMapping/if.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -mllvm -emptyline-comment-coverage=false 
-fprofile-instrument=clang -fcoverage-mapping -dump-coverage-mapping 
-emit-llvm-only -std=c++1z -triple %itanium_abi_triple -main-file-name if.cpp 
%s | FileCheck %s
+// RUN: %clang_cc1 -mllvm -emptyline-comment-c

  1   2   >