From 7982d1ea2c5eb2ea2261fd82ebd7eebdda0e58b3 Mon Sep 17 00:00:00 2001 From: Dimitry Andric Date: Thu, 14 Jul 2022 20:58:48 +0200 Subject: Merge llvm-project main llvmorg-15-init-16436-g18a6ab5b8d1f This updates llvm, clang, compiler-rt, libc++, libunwind, lld, lldb and openmp to llvmorg-15-init-16436-g18a6ab5b8d1f. PR: 265425 MFC after: 2 weeks (cherry picked from commit 753f127f3ace09432b2baeffd71a308760641a62) --- .../clang/include/clang/APINotes/Types.h | 2 +- .../clang/include/clang/AST/ASTContext.h | 42 +- .../clang/include/clang/AST/ASTImportError.h | 1 - .../clang/include/clang/AST/DeclTemplate.h | 13 +- .../clang/include/clang/AST/PropertiesBase.td | 10 +- .../FlowSensitive/DataflowAnalysisContext.h | 28 +- .../clang/Analysis/FlowSensitive/DebugSupport.h | 63 + .../include/clang/Analysis/FlowSensitive/Solver.h | 62 +- .../clang/include/clang/Analysis/SelectorExtras.h | 2 +- .../clang/include/clang/Basic/AlignedAllocation.h | 4 +- .../llvm-project/clang/include/clang/Basic/Attr.td | 11 + .../clang/include/clang/Basic/AttrDocs.td | 47 +- .../clang/include/clang/Basic/BuiltinsX86.def | 1 + .../clang/include/clang/Basic/CodeGenOptions.def | 1 + .../clang/include/clang/Basic/CodeGenOptions.h | 3 + .../include/clang/Basic/DiagnosticDriverKinds.td | 2 - .../clang/include/clang/Basic/DiagnosticGroups.td | 4 + .../include/clang/Basic/DiagnosticLexKinds.td | 11 +- .../include/clang/Basic/DiagnosticSemaKinds.td | 34 +- .../clang/include/clang/Basic/MakeSupport.h | 23 + .../clang/include/clang/Basic/TargetInfo.h | 6 +- .../clang/include/clang/Basic/riscv_vector.td | 99 +- .../clang/include/clang/Driver/Options.td | 27 +- .../clang/include/clang/Frontend/FrontendActions.h | 4 + .../clang/include/clang/Lex/Preprocessor.h | 63 + .../include/clang/Sema/HLSLExternalSemaSource.h | 41 + .../llvm-project/clang/include/clang/Sema/Sema.h | 45 +- .../StaticAnalyzer/Core/PathSensitive/CallEvent.h | 5 +- .../Core/PathSensitive/ConstraintManager.h | 12 +- .../Core/PathSensitive/SMTConstraintManager.h | 2 +- .../include/clang/Support/RISCVVIntrinsicUtils.h | 6 +- .../DependencyScanningFilesystem.h | 4 +- .../DependencyScanning/DependencyScanningTool.h | 12 +- .../DependencyScanning/ModuleDepCollector.h | 31 +- contrib/llvm-project/clang/lib/AST/ASTContext.cpp | 169 +- contrib/llvm-project/clang/lib/AST/ASTImporter.cpp | 10 - contrib/llvm-project/clang/lib/AST/AttrImpl.cpp | 6 +- contrib/llvm-project/clang/lib/AST/DeclPrinter.cpp | 6 + .../llvm-project/clang/lib/AST/FormatString.cpp | 6 + .../clang/lib/AST/Interp/ByteCodeExprGen.cpp | 2 +- .../llvm-project/clang/lib/Analysis/BodyFarm.cpp | 4 +- .../Analysis/FlowSensitive/ControlFlowContext.cpp | 2 +- .../FlowSensitive/DataflowAnalysisContext.cpp | 8 +- .../lib/Analysis/FlowSensitive/DebugSupport.cpp | 197 ++ .../FlowSensitive/TypeErasedDataflowAnalysis.cpp | 6 +- .../FlowSensitive/WatchedLiteralsSolver.cpp | 66 +- .../clang/lib/Analysis/PathDiagnostic.cpp | 4 +- .../clang/lib/Analysis/UninitializedValues.cpp | 4 +- .../llvm-project/clang/lib/Basic/LangStandards.cpp | 4 +- .../llvm-project/clang/lib/Basic/MakeSupport.cpp | 35 + .../llvm-project/clang/lib/Basic/TargetInfo.cpp | 2 +- .../llvm-project/clang/lib/Basic/Targets/RISCV.cpp | 2 +- .../llvm-project/clang/lib/Basic/Targets/SystemZ.h | 8 + .../llvm-project/clang/lib/Basic/Targets/X86.cpp | 6 + contrib/llvm-project/clang/lib/Basic/Targets/X86.h | 7 +- .../llvm-project/clang/lib/CodeGen/BackendUtil.cpp | 12 + .../llvm-project/clang/lib/CodeGen/CGCUDANV.cpp | 11 +- contrib/llvm-project/clang/lib/CodeGen/CGCall.cpp | 3 + contrib/llvm-project/clang/lib/CodeGen/CGClass.cpp | 4 +- .../clang/lib/CodeGen/CGOpenMPRuntime.cpp | 140 +- .../clang/lib/CodeGen/CGOpenMPRuntime.h | 10 +- .../clang/lib/CodeGen/CGStmtOpenMP.cpp | 48 +- .../clang/lib/CodeGen/CodeGenFunction.cpp | 14 + .../clang/lib/CodeGen/CodeGenModule.cpp | 10 + .../llvm-project/clang/lib/CodeGen/CodeGenModule.h | 19 + .../llvm-project/clang/lib/CodeGen/CodeGenTBAA.cpp | 37 +- .../clang/lib/CodeGen/SanitizerMetadata.cpp | 18 +- contrib/llvm-project/clang/lib/Driver/Driver.cpp | 39 +- .../clang/lib/Driver/ToolChains/AVR.cpp | 8 +- .../clang/lib/Driver/ToolChains/Clang.cpp | 234 +- .../clang/lib/Driver/ToolChains/CommonArgs.cpp | 3 +- .../clang/lib/Driver/ToolChains/Darwin.cpp | 14 +- .../clang/lib/Driver/ToolChains/Gnu.cpp | 2 +- .../clang/lib/Driver/ToolChains/Hexagon.cpp | 4 +- .../clang/lib/Driver/ToolChains/MinGW.cpp | 28 +- .../clang/lib/Driver/ToolChains/MinGW.h | 1 + .../clang/lib/Driver/ToolChains/RISCVToolchain.cpp | 7 +- .../Serialization/SymbolGraphSerializer.cpp | 4 +- .../clang/lib/Format/ContinuationIndenter.cpp | 6 +- .../clang/lib/Format/ContinuationIndenter.h | 2 +- contrib/llvm-project/clang/lib/Format/Format.cpp | 31 +- .../llvm-project/clang/lib/Format/FormatToken.cpp | 2 +- .../llvm-project/clang/lib/Format/FormatToken.h | 9 + .../clang/lib/Format/MacroCallReconstructor.cpp | 573 +++++ contrib/llvm-project/clang/lib/Format/Macros.h | 279 ++- .../clang/lib/Format/TokenAnnotator.cpp | 8 +- .../clang/lib/Format/UnwrappedLineFormatter.cpp | 15 +- .../clang/lib/Format/UnwrappedLineParser.cpp | 16 +- .../clang/lib/Format/UnwrappedLineParser.h | 3 +- .../clang/lib/Frontend/CompilerInstance.cpp | 21 +- .../clang/lib/Frontend/CompilerInvocation.cpp | 28 +- .../clang/lib/Frontend/FrontendAction.cpp | 9 + .../clang/lib/Frontend/FrontendActions.cpp | 3 +- .../clang/lib/Frontend/InitPreprocessor.cpp | 4 +- .../clang/lib/Headers/hlsl/hlsl_basic_types.h | 54 +- contrib/llvm-project/clang/lib/Headers/opencl-c.h | 18 - .../llvm-project/clang/lib/Headers/rdpruintrin.h | 57 + contrib/llvm-project/clang/lib/Headers/stdatomic.h | 4 - contrib/llvm-project/clang/lib/Headers/x86intrin.h | 4 + .../clang/lib/Lex/DependencyDirectivesScanner.cpp | 2 +- contrib/llvm-project/clang/lib/Lex/Lexer.cpp | 117 +- .../llvm-project/clang/lib/Lex/LiteralSupport.cpp | 10 +- contrib/llvm-project/clang/lib/Lex/MacroInfo.cpp | 2 +- contrib/llvm-project/clang/lib/Lex/ModuleMap.cpp | 4 +- .../llvm-project/clang/lib/Lex/PPDirectives.cpp | 90 +- .../clang/lib/Lex/PPMacroExpansion.cpp | 4 +- .../clang/lib/Lex/PreprocessingRecord.cpp | 2 +- .../llvm-project/clang/lib/Lex/Preprocessor.cpp | 14 + .../llvm-project/clang/lib/Parse/ParseOpenMP.cpp | 18 +- contrib/llvm-project/clang/lib/Parse/Parser.cpp | 18 +- .../clang/lib/Sema/HLSLExternalSemaSource.cpp | 96 + contrib/llvm-project/clang/lib/Sema/SemaCUDA.cpp | 13 +- .../llvm-project/clang/lib/Sema/SemaChecking.cpp | 403 ++-- .../clang/lib/Sema/SemaCodeComplete.cpp | 4 +- contrib/llvm-project/clang/lib/Sema/SemaDecl.cpp | 72 +- .../llvm-project/clang/lib/Sema/SemaDeclAttr.cpp | 46 +- contrib/llvm-project/clang/lib/Sema/SemaExpr.cpp | 48 +- .../llvm-project/clang/lib/Sema/SemaExprCXX.cpp | 35 + contrib/llvm-project/clang/lib/Sema/SemaModule.cpp | 13 + contrib/llvm-project/clang/lib/Sema/SemaOpenMP.cpp | 79 +- .../llvm-project/clang/lib/Sema/SemaTemplate.cpp | 65 +- .../clang/lib/Sema/SemaTemplateInstantiateDecl.cpp | 9 +- .../clang/lib/Serialization/ASTReader.cpp | 16 +- .../clang/lib/Serialization/ASTWriter.cpp | 13 +- .../Checkers/BasicObjCFoundationChecks.cpp | 4 +- .../lib/StaticAnalyzer/Checkers/CStringChecker.cpp | 2 +- .../lib/StaticAnalyzer/Checkers/MallocChecker.cpp | 9 +- .../Checkers/NonNullParamChecker.cpp | 4 +- .../lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp | 3 +- .../lib/StaticAnalyzer/Core/AnalyzerOptions.cpp | 6 +- .../clang/lib/StaticAnalyzer/Core/BugReporter.cpp | 6 +- .../StaticAnalyzer/Core/BugReporterVisitors.cpp | 8 +- .../Core/ExprEngineCallAndReturn.cpp | 2 +- .../lib/StaticAnalyzer/Core/PlistDiagnostics.cpp | 4 +- .../clang/lib/StaticAnalyzer/Core/SValBuilder.cpp | 6 + .../clang/lib/Support/RISCVVIntrinsicUtils.cpp | 4 +- .../DependencyScanning/DependencyScanningTool.cpp | 19 +- .../DependencyScanning/ModuleDepCollector.cpp | 45 +- .../clang/tools/clang-format/ClangFormat.cpp | 16 +- contrib/llvm-project/clang/tools/driver/driver.cpp | 4 +- .../clang/utils/TableGen/RISCVVEmitter.cpp | 22 +- .../compiler-rt/lib/asan/asan_globals.cpp | 4 +- .../compiler-rt/lib/asan/asan_interceptors.cpp | 4 +- .../llvm-project/compiler-rt/lib/asan/asan_rtl.cpp | 3 - .../llvm-project/compiler-rt/lib/hwasan/hwasan.cpp | 6 + .../compiler-rt/lib/hwasan/hwasan_fuchsia.cpp | 6 +- .../lib/hwasan/hwasan_interface_internal.h | 8 + .../compiler-rt/lib/hwasan/hwasan_linux.cpp | 26 +- .../compiler-rt/lib/memprof/memprof_rtl.cpp | 3 - .../compiler-rt/lib/orc/elfnix_platform.cpp | 13 + .../compiler-rt/lib/orc/elfnix_tls.aarch64.S | 94 + .../compiler-rt/lib/profile/GCDAProfiling.c | 11 +- .../lib/sanitizer_common/sanitizer_common.h | 1 - .../sanitizer_common_interceptors.inc | 28 +- .../lib/sanitizer_common/sanitizer_flags.inc | 7 +- .../lib/sanitizer_common/sanitizer_fuchsia.cpp | 1 - .../lib/sanitizer_common/sanitizer_linux.cpp | 30 +- .../lib/sanitizer_common/sanitizer_linux.h | 3 + .../lib/sanitizer_common/sanitizer_mac.cpp | 136 +- .../lib/sanitizer_common/sanitizer_platform.h | 7 +- .../sanitizer_platform_limits_posix.cpp | 10 +- .../sanitizer_common/sanitizer_procmaps_mac.cpp | 8 +- .../lib/sanitizer_common/sanitizer_vector.h | 4 +- .../lib/sanitizer_common/sanitizer_win.cpp | 4 - .../compiler-rt/lib/scudo/standalone/fuchsia.cpp | 9 +- .../lib/scudo/standalone/include/scudo/interface.h | 14 +- .../compiler-rt/lib/scudo/standalone/release.h | 5 +- .../compiler-rt/lib/scudo/standalone/vector.h | 7 +- .../compiler-rt/lib/tsan/rtl/tsan_rtl.cpp | 3 - .../libcxx/include/__algorithm/binary_search.h | 10 +- .../libcxx/include/__algorithm/count.h | 4 +- .../libcxx/include/__algorithm/equal_range.h | 18 +- .../llvm-project/libcxx/include/__algorithm/fill.h | 12 +- .../libcxx/include/__algorithm/fill_n.h | 8 +- .../llvm-project/libcxx/include/__algorithm/find.h | 4 +- .../libcxx/include/__algorithm/find_end.h | 181 +- .../include/__algorithm/iterator_operations.h | 68 +- .../libcxx/include/__algorithm/lower_bound.h | 15 +- .../libcxx/include/__algorithm/make_heap.h | 43 +- .../libcxx/include/__algorithm/make_projected.h | 22 +- .../libcxx/include/__algorithm/minmax_element.h | 8 +- .../libcxx/include/__algorithm/nth_element.h | 44 +- .../libcxx/include/__algorithm/partial_sort.h | 9 +- .../libcxx/include/__algorithm/pop_heap.h | 60 +- .../libcxx/include/__algorithm/push_heap.h | 71 +- .../include/__algorithm/ranges_binary_search.h | 4 +- .../include/__algorithm/ranges_equal_range.h | 74 + .../libcxx/include/__algorithm/ranges_find_end.h | 113 + .../libcxx/include/__algorithm/ranges_generate.h | 73 + .../libcxx/include/__algorithm/ranges_generate_n.h | 65 + .../libcxx/include/__algorithm/ranges_includes.h | 75 + .../include/__algorithm/ranges_inplace_merge.h | 73 + .../libcxx/include/__algorithm/ranges_is_heap.h | 70 + .../include/__algorithm/ranges_is_heap_until.h | 71 + .../include/__algorithm/ranges_lower_bound.h | 4 +- .../libcxx/include/__algorithm/ranges_make_heap.h | 79 + .../libcxx/include/__algorithm/ranges_merge.h | 142 ++ .../include/__algorithm/ranges_nth_element.h | 79 + .../include/__algorithm/ranges_partial_sort_copy.h | 88 + .../libcxx/include/__algorithm/ranges_partition.h | 74 + .../include/__algorithm/ranges_partition_copy.h | 82 + .../include/__algorithm/ranges_partition_point.h | 71 + .../libcxx/include/__algorithm/ranges_pop_heap.h | 80 + .../libcxx/include/__algorithm/ranges_push_heap.h | 79 + .../libcxx/include/__algorithm/ranges_remove.h | 64 + .../include/__algorithm/ranges_remove_copy.h | 81 + .../include/__algorithm/ranges_remove_copy_if.h | 80 + .../libcxx/include/__algorithm/ranges_remove_if.h | 85 + .../include/__algorithm/ranges_replace_copy.h | 84 + .../include/__algorithm/ranges_replace_copy_if.h | 81 + .../include/__algorithm/ranges_reverse_copy.h | 67 + .../include/__algorithm/ranges_rotate_copy.h | 68 + .../libcxx/include/__algorithm/ranges_search.h | 134 ++ .../libcxx/include/__algorithm/ranges_search_n.h | 120 ++ .../include/__algorithm/ranges_set_difference.h | 104 + .../include/__algorithm/ranges_set_intersection.h | 117 + .../__algorithm/ranges_set_symmetric_difference.h | 116 + .../libcxx/include/__algorithm/ranges_set_union.h | 86 + .../libcxx/include/__algorithm/ranges_shuffle.h | 74 + .../libcxx/include/__algorithm/ranges_sort_heap.h | 79 + .../include/__algorithm/ranges_stable_partition.h | 75 + .../libcxx/include/__algorithm/ranges_unique.h | 74 + .../include/__algorithm/ranges_unique_copy.h | 88 + .../include/__algorithm/ranges_upper_bound.h | 4 +- .../libcxx/include/__algorithm/remove.h | 6 +- .../libcxx/include/__algorithm/remove_copy.h | 4 +- .../libcxx/include/__algorithm/search.h | 176 +- .../libcxx/include/__algorithm/search_n.h | 159 +- .../libcxx/include/__algorithm/set_difference.h | 81 +- .../libcxx/include/__algorithm/set_intersection.h | 101 +- .../include/__algorithm/set_symmetric_difference.h | 111 +- .../llvm-project/libcxx/include/__algorithm/sort.h | 7 +- .../libcxx/include/__algorithm/sort_heap.h | 33 +- .../libcxx/include/__algorithm/upper_bound.h | 12 +- .../llvm-project/libcxx/include/__bit_reference | 16 +- contrib/llvm-project/libcxx/include/__bits | 17 + .../libcxx/include/__charconv/tables.h | 50 + .../libcxx/include/__charconv/to_chars_base_10.h | 60 +- contrib/llvm-project/libcxx/include/__chrono/day.h | 23 +- .../libcxx/include/__chrono/duration.h | 8 +- .../libcxx/include/__chrono/time_point.h | 4 +- .../llvm-project/libcxx/include/__chrono/year.h | 9 +- .../libcxx/include/__chrono/year_month_weekday.h | 8 +- contrib/llvm-project/libcxx/include/__config | 56 +- contrib/llvm-project/libcxx/include/__debug | 16 - .../libcxx/include/__debug_utils/randomize_range.h | 42 + .../libcxx/include/__filesystem/copy_options.h | 34 +- .../include/__filesystem/directory_options.h | 46 +- .../libcxx/include/__filesystem/operations.h | 22 +- .../libcxx/include/__filesystem/perm_options.h | 34 +- .../libcxx/include/__filesystem/perms.h | 28 +- .../libcxx/include/__format/format_arg.h | 23 +- .../libcxx/include/__format/format_arg_store.h | 10 +- .../libcxx/include/__format/formatter.h | 227 -- .../libcxx/include/__format/formatter_bool.h | 1 + .../libcxx/include/__format/formatter_char.h | 2 +- .../include/__format/formatter_floating_point.h | 415 ++-- .../libcxx/include/__format/formatter_integer.h | 33 +- .../libcxx/include/__format/formatter_integral.h | 5 +- .../libcxx/include/__format/formatter_output.h | 59 +- .../include/__format/parser_std_format_spec.h | 893 +------- .../libcxx/include/__functional/default_searcher.h | 8 +- .../libcxx/include/__functional/function.h | 4 +- contrib/llvm-project/libcxx/include/__hash_table | 63 +- .../include/__iterator/back_insert_iterator.h | 8 +- .../include/__iterator/front_insert_iterator.h | 8 +- .../libcxx/include/__iterator/insert_iterator.h | 8 +- .../libcxx/include/__iterator/iterator_traits.h | 12 + .../libcxx/include/__iterator/ostream_iterator.h | 4 +- .../libcxx/include/__iterator/reverse_iterator.h | 17 +- contrib/llvm-project/libcxx/include/__mutex_base | 12 +- .../llvm-project/libcxx/include/__numeric/iota.h | 6 +- .../__random/piecewise_constant_distribution.h | 20 +- .../__random/piecewise_linear_distribution.h | 20 +- .../libcxx/include/__ranges/zip_view.h | 8 +- contrib/llvm-project/libcxx/include/__split_buffer | 26 +- .../libcxx/include/__string/char_traits.h | 4 +- .../libcxx/include/__threading_support | 22 +- contrib/llvm-project/libcxx/include/__tree | 32 +- contrib/llvm-project/libcxx/include/__tuple | 6 +- .../libcxx/include/__type_traits/extent.h | 6 +- .../include/__type_traits/has_virtual_destructor.h | 2 +- .../libcxx/include/__type_traits/is_array.h | 4 +- .../libcxx/include/__type_traits/is_assignable.h | 6 +- .../libcxx/include/__type_traits/is_compound.h | 6 +- .../libcxx/include/__type_traits/is_const.h | 4 +- .../libcxx/include/__type_traits/is_convertible.h | 6 +- .../libcxx/include/__type_traits/is_destructible.h | 6 +- .../libcxx/include/__type_traits/is_function.h | 4 +- .../libcxx/include/__type_traits/is_fundamental.h | 6 +- .../libcxx/include/__type_traits/is_integral.h | 4 +- .../__type_traits/is_member_function_pointer.h | 6 +- .../__type_traits/is_member_object_pointer.h | 6 +- .../include/__type_traits/is_member_pointer.h | 6 +- .../include/__type_traits/is_nothrow_assignable.h | 4 +- .../__type_traits/is_nothrow_constructible.h | 4 +- .../libcxx/include/__type_traits/is_object.h | 6 +- .../libcxx/include/__type_traits/is_pod.h | 4 +- .../libcxx/include/__type_traits/is_pointer.h | 6 +- .../libcxx/include/__type_traits/is_reference.h | 10 +- .../libcxx/include/__type_traits/is_scalar.h | 6 +- .../libcxx/include/__type_traits/is_signed.h | 6 +- .../include/__type_traits/is_standard_layout.h | 2 +- .../libcxx/include/__type_traits/is_trivial.h | 2 +- .../__type_traits/is_trivially_destructible.h | 6 +- .../libcxx/include/__type_traits/is_unsigned.h | 6 +- .../libcxx/include/__type_traits/is_void.h | 4 +- .../libcxx/include/__type_traits/is_volatile.h | 4 +- contrib/llvm-project/libcxx/include/algorithm | 234 ++ contrib/llvm-project/libcxx/include/any | 2 +- contrib/llvm-project/libcxx/include/array | 7 +- contrib/llvm-project/libcxx/include/atomic | 9 +- contrib/llvm-project/libcxx/include/barrier | 8 +- contrib/llvm-project/libcxx/include/charconv | 135 +- contrib/llvm-project/libcxx/include/chrono | 12 +- contrib/llvm-project/libcxx/include/cmath | 6 +- contrib/llvm-project/libcxx/include/codecvt | 96 +- .../llvm-project/libcxx/include/condition_variable | 2 +- contrib/llvm-project/libcxx/include/deque | 18 +- contrib/llvm-project/libcxx/include/exception | 6 +- .../libcxx/include/experimental/functional | 6 +- .../llvm-project/libcxx/include/experimental/simd | 12 +- contrib/llvm-project/libcxx/include/ext/hash_map | 24 +- contrib/llvm-project/libcxx/include/ext/hash_set | 24 +- contrib/llvm-project/libcxx/include/format | 93 +- contrib/llvm-project/libcxx/include/forward_list | 42 +- contrib/llvm-project/libcxx/include/future | 8 +- contrib/llvm-project/libcxx/include/list | 16 +- contrib/llvm-project/libcxx/include/map | 64 +- contrib/llvm-project/libcxx/include/memory | 4 +- .../libcxx/include/module.modulemap.in | 41 + contrib/llvm-project/libcxx/include/regex | 29 +- .../llvm-project/libcxx/include/scoped_allocator | 18 +- contrib/llvm-project/libcxx/include/shared_mutex | 4 +- contrib/llvm-project/libcxx/include/string_view | 4 +- contrib/llvm-project/libcxx/include/system_error | 4 +- contrib/llvm-project/libcxx/include/tuple | 16 +- contrib/llvm-project/libcxx/include/unordered_map | 52 +- contrib/llvm-project/libcxx/include/unordered_set | 40 +- contrib/llvm-project/libcxx/include/variant | 4 +- contrib/llvm-project/libcxx/include/vector | 68 +- contrib/llvm-project/libcxx/include/wchar.h | 8 +- contrib/llvm-project/lld/COFF/Config.h | 4 + contrib/llvm-project/lld/COFF/Driver.cpp | 35 +- contrib/llvm-project/lld/COFF/Options.td | 2 + contrib/llvm-project/lld/ELF/Arch/RISCV.cpp | 306 ++- contrib/llvm-project/lld/ELF/Config.h | 3 +- contrib/llvm-project/lld/ELF/Driver.cpp | 22 +- contrib/llvm-project/lld/ELF/InputSection.cpp | 29 +- contrib/llvm-project/lld/ELF/InputSection.h | 29 +- contrib/llvm-project/lld/ELF/LTO.cpp | 7 +- contrib/llvm-project/lld/ELF/Options.td | 2 + contrib/llvm-project/lld/ELF/OutputSections.cpp | 30 +- contrib/llvm-project/lld/ELF/OutputSections.h | 4 +- contrib/llvm-project/lld/ELF/Relocations.cpp | 9 +- contrib/llvm-project/lld/ELF/Relocations.h | 13 +- contrib/llvm-project/lld/ELF/Target.h | 4 + contrib/llvm-project/lld/ELF/Thunks.cpp | 29 +- contrib/llvm-project/lld/ELF/Writer.cpp | 38 +- contrib/llvm-project/lld/MachO/Arch/ARM.cpp | 36 + contrib/llvm-project/lld/MachO/Arch/ARM64.cpp | 208 +- .../llvm-project/lld/MachO/Arch/ARM64Common.cpp | 18 + contrib/llvm-project/lld/MachO/Arch/ARM64Common.h | 3 + contrib/llvm-project/lld/MachO/Arch/X86_64.cpp | 23 + contrib/llvm-project/lld/MachO/Config.h | 3 - contrib/llvm-project/lld/MachO/Driver.cpp | 1 - contrib/llvm-project/lld/MachO/InputFiles.cpp | 77 +- contrib/llvm-project/lld/MachO/InputFiles.h | 1 + contrib/llvm-project/lld/MachO/InputSection.cpp | 6 + contrib/llvm-project/lld/MachO/SymbolTable.cpp | 4 + contrib/llvm-project/lld/MachO/Target.h | 9 + .../llvm-project/lld/MachO/UnwindInfoSection.cpp | 2 +- contrib/llvm-project/lld/docs/ReleaseNotes.rst | 8 +- contrib/llvm-project/lld/tools/lld/lld.cpp | 6 + .../lldb/bindings/interface/SBSection.i | 4 + .../llvm-project/lldb/bindings/interface/SBTrace.i | 2 + .../llvm-project/lldb/include/lldb/API/SBSection.h | 6 + .../llvm-project/lldb/include/lldb/API/SBTrace.h | 22 + .../lldb/include/lldb/Core/Disassembler.h | 17 +- .../lldb/include/lldb/Expression/DWARFExpression.h | 128 +- .../include/lldb/Expression/DWARFExpressionList.h | 151 ++ .../lldb/include/lldb/Interpreter/CommandObject.h | 3 - .../lldb/include/lldb/Symbol/Function.h | 16 +- .../lldb/include/lldb/Symbol/ObjectFile.h | 2 + .../lldb/include/lldb/Symbol/TypeList.h | 7 +- .../lldb/include/lldb/Symbol/TypeMap.h | 8 +- .../lldb/include/lldb/Symbol/Variable.h | 14 +- .../lldb/include/lldb/Target/StackFrame.h | 4 +- .../llvm-project/lldb/include/lldb/Target/Trace.h | 26 +- .../lldb/include/lldb/Target/TraceCursor.h | 10 + .../lldb/include/lldb/Target/TraceDumper.h | 3 + .../lldb/include/lldb/Utility/Environment.h | 2 +- .../lldb/include/lldb/Utility/RangeMap.h | 4 + .../lldb/Utility/TraceIntelPTGDBRemotePackets.h | 5 + .../lldb/include/lldb/lldb-enumerations.h | 47 +- .../llvm-project/lldb/include/lldb/lldb-forward.h | 1 + .../llvm-project/lldb/source/API/SBInstruction.cpp | 7 +- .../lldb/source/API/SBInstructionList.cpp | 5 +- contrib/llvm-project/lldb/source/API/SBSection.cpp | 9 + contrib/llvm-project/lldb/source/API/SBTrace.cpp | 18 + .../source/Commands/CommandObjectDisassemble.cpp | 8 + .../source/Commands/CommandObjectDisassemble.h | 1 + .../lldb/source/Commands/CommandObjectProcess.cpp | 128 +- .../lldb/source/Commands/CommandObjectTarget.cpp | 69 +- .../lldb/source/Commands/CommandObjectThread.cpp | 33 +- .../lldb/source/Commands/CommandObjectTrace.cpp | 116 +- .../llvm-project/lldb/source/Commands/Options.td | 28 +- contrib/llvm-project/lldb/source/Core/Debugger.cpp | 15 +- .../llvm-project/lldb/source/Core/Disassembler.cpp | 376 +++- .../lldb/source/Core/DumpDataExtractor.cpp | 5 +- contrib/llvm-project/lldb/source/Core/Module.cpp | 19 +- .../lldb/source/Core/ValueObjectVariable.cpp | 19 +- .../lldb/source/Expression/DWARFExpression.cpp | 334 +-- .../lldb/source/Expression/DWARFExpressionList.cpp | 248 +++ .../lldb/source/Expression/IRExecutionUnit.cpp | 4 +- .../lldb/source/Expression/Materializer.cpp | 2 +- .../lldb/source/Interpreter/CommandObject.cpp | 21 +- .../source/Plugins/ABI/X86/ABIWindows_x86_64.h | 11 +- .../Disassembler/LLVMC/DisassemblerLLVMC.cpp | 6 +- .../Clang/ClangExpressionDeclMap.cpp | 53 +- .../Clang/ClangExpressionDeclMap.h | 4 +- .../Language/CPlusPlus/CPlusPlusLanguage.cpp | 8 + .../source/Plugins/Language/CPlusPlus/LibCxx.cpp | 279 ++- .../source/Plugins/Language/CPlusPlus/LibCxx.h | 50 + .../BSD-Archive/ObjectContainerBSDArchive.cpp | 208 +- .../BSD-Archive/ObjectContainerBSDArchive.h | 22 +- .../Plugins/ObjectFile/ELF/ObjectFileELF.cpp | 3 +- .../Plugins/ObjectFile/PDB/ObjectFilePDB.cpp | 2 - .../gdb-remote/GDBRemoteCommunicationClient.cpp | 4 +- .../gdb-remote/GDBRemoteCommunicationClient.h | 2 - .../SymbolFile/DWARF/DWARFASTParserClang.cpp | 2 +- .../source/Plugins/SymbolFile/DWARF/DWARFDIE.cpp | 2 +- .../source/Plugins/SymbolFile/DWARF/DWARFDIE.h | 11 +- .../SymbolFile/DWARF/DWARFDebugInfoEntry.cpp | 19 +- .../Plugins/SymbolFile/DWARF/DWARFDebugInfoEntry.h | 2 +- .../source/Plugins/SymbolFile/DWARF/DWARFUnit.cpp | 11 + .../source/Plugins/SymbolFile/DWARF/DWARFUnit.h | 2 + .../Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp | 83 +- .../Plugins/SymbolFile/DWARF/SymbolFileDWARF.h | 1 + .../NativePDB/DWARFLocationExpression.cpp | 4 +- .../Plugins/SymbolFile/NativePDB/PdbUtil.cpp | 10 +- .../source/Plugins/SymbolFile/NativePDB/PdbUtil.h | 4 +- .../SymbolFile/NativePDB/SymbolFileNativePDB.cpp | 28 +- .../PDB/PDBLocationToDWARFExpression.cpp | 2 +- .../Plugins/SymbolFile/PDB/SymbolFilePDB.cpp | 7 +- .../intel-pt/CommandObjectTraceStartIntelPT.cpp | 89 +- .../intel-pt/CommandObjectTraceStartIntelPT.h | 18 + .../Plugins/Trace/intel-pt/DecodedThread.cpp | 32 +- .../source/Plugins/Trace/intel-pt/DecodedThread.h | 23 +- .../Plugins/Trace/intel-pt/LibiptDecoder.cpp | 2 + .../Trace/intel-pt/PerfContextSwitchDecoder.cpp | 45 +- .../Trace/intel-pt/PerfContextSwitchDecoder.h | 5 + .../lldb/source/Plugins/Trace/intel-pt/TaskTimer.h | 4 +- .../Plugins/Trace/intel-pt/ThreadDecoder.cpp | 5 +- .../Plugins/Trace/intel-pt/TraceCursorIntelPT.cpp | 4 + .../Plugins/Trace/intel-pt/TraceCursorIntelPT.h | 2 + .../source/Plugins/Trace/intel-pt/TraceIntelPT.cpp | 175 +- .../source/Plugins/Trace/intel-pt/TraceIntelPT.h | 23 +- .../Trace/intel-pt/TraceIntelPTBundleSaver.cpp | 138 +- .../Trace/intel-pt/TraceIntelPTBundleSaver.h | 12 +- .../Plugins/Trace/intel-pt/TraceIntelPTConstants.h | 1 + .../Trace/intel-pt/TraceIntelPTMultiCpuDecoder.cpp | 77 +- .../Trace/intel-pt/TraceIntelPTMultiCpuDecoder.h | 16 +- .../Plugins/Trace/intel-pt/TraceIntelPTOptions.td | 29 +- .../Plugins/TraceExporter/common/TraceHTR.cpp | 6 +- .../InstEmulation/UnwindAssemblyInstEmulation.cpp | 4 +- .../llvm-project/lldb/source/Symbol/Function.cpp | 14 +- contrib/llvm-project/lldb/source/Symbol/Symbol.cpp | 5 +- .../llvm-project/lldb/source/Symbol/TypeList.cpp | 9 +- .../llvm-project/lldb/source/Symbol/TypeMap.cpp | 41 +- .../llvm-project/lldb/source/Symbol/Variable.cpp | 30 +- .../lldb/source/Target/RegisterContextUnwind.cpp | 20 +- .../llvm-project/lldb/source/Target/StackFrame.cpp | 10 +- .../lldb/source/Target/ThreadPlanTracer.cpp | 5 +- .../lldb/source/Target/TraceCursor.cpp | 3 + .../lldb/source/Target/TraceDumper.cpp | 105 +- contrib/llvm-project/lldb/source/Utility/Args.cpp | 1 + .../Utility/TraceIntelPTGDBRemotePackets.cpp | 12 +- .../llvm-project/llvm/include/llvm-c/BitReader.h | 9 +- contrib/llvm-project/llvm/include/llvm-c/Core.h | 36 +- .../llvm/include/llvm/ADT/ScopedHashTable.h | 13 +- .../llvm-project/llvm/include/llvm/ADT/StringMap.h | 30 +- .../include/llvm/Analysis/BlockFrequencyInfoImpl.h | 8 +- .../llvm/include/llvm/Analysis/GlobalsModRef.h | 6 +- .../include/llvm/Analysis/InstSimplifyFolder.h | 17 +- .../llvm/include/llvm/Analysis/ScalarEvolution.h | 6 +- .../llvm/include/llvm/Analysis/TargetFolder.h | 53 +- .../include/llvm/Analysis/TargetTransformInfo.h | 14 +- .../llvm/Analysis/TargetTransformInfoImpl.h | 4 +- .../llvm/include/llvm/Analysis/ValueTracking.h | 6 +- .../llvm/include/llvm/Analysis/VectorUtils.h | 6 +- .../llvm/include/llvm/AsmParser/LLToken.h | 5 +- .../llvm/include/llvm/BinaryFormat/ELF.h | 1 + .../llvm/include/llvm/Bitcode/LLVMBitCodes.h | 5 +- .../llvm/include/llvm/Bitstream/BitstreamWriter.h | 4 +- .../llvm/include/llvm/CodeGen/AsmPrinter.h | 7 +- .../llvm/include/llvm/CodeGen/BasicTTIImpl.h | 2 +- .../llvm/CodeGen/GlobalISel/InstructionSelector.h | 4 + .../CodeGen/GlobalISel/InstructionSelectorImpl.h | 21 +- .../llvm/CodeGen/GlobalISel/LegalizerHelper.h | 3 - .../llvm/CodeGen/GlobalISel/MachineIRBuilder.h | 41 + .../llvm/include/llvm/CodeGen/ISDOpcodes.h | 7 + .../llvm/include/llvm/CodeGen/MachineScheduler.h | 2 + .../llvm/include/llvm/CodeGen/SelectionDAGISel.h | 1 + .../llvm/include/llvm/CodeGen/SelectionDAGNodes.h | 4 + .../llvm/include/llvm/CodeGen/TargetLowering.h | 3 + .../llvm/include/llvm/DWARFLinker/DWARFLinker.h | 3 - .../include/llvm/DebugInfo/Symbolize/Symbolize.h | 2 + .../llvm/include/llvm/Debuginfod/Debuginfod.h | 83 +- .../llvm/include/llvm/Debuginfod/HTTPServer.h | 123 ++ .../include/llvm/ExecutionEngine/JITLink/COFF.h | 39 + .../llvm/ExecutionEngine/JITLink/COFF_x86_64.h | 38 + .../include/llvm/ExecutionEngine/JITLink/aarch64.h | 14 +- .../llvm/ExecutionEngine/Orc/MachOPlatform.h | 3 - .../llvm/include/llvm/Frontend/OpenACC/ACC.td | 5 +- .../include/llvm/Frontend/OpenMP/OMPIRBuilder.h | 23 +- .../llvm/include/llvm/Frontend/OpenMP/OMPKinds.def | 10 + .../llvm/include/llvm/IR/Attributes.td | 4 + .../llvm-project/llvm/include/llvm/IR/Constant.h | 4 - .../llvm/include/llvm/IR/ConstantFolder.h | 50 +- .../llvm-project/llvm/include/llvm/IR/Constants.h | 36 +- .../llvm/include/llvm/IR/FixedMetadataKinds.def | 1 + .../llvm/include/llvm/IR/GlobalValue.h | 48 +- .../llvm-project/llvm/include/llvm/IR/IRBuilder.h | 24 +- .../llvm/include/llvm/IR/IRBuilderFolder.h | 10 +- .../llvm-project/llvm/include/llvm/IR/InlineAsm.h | 9 +- .../llvm/include/llvm/IR/Instructions.h | 12 +- .../llvm/include/llvm/IR/Intrinsics.td | 2 +- .../llvm/include/llvm/IR/IntrinsicsAArch64.td | 43 +- .../llvm/include/llvm/IR/IntrinsicsAMDGPU.td | 2 +- .../llvm/include/llvm/IR/IntrinsicsDirectX.td | 10 +- .../llvm/include/llvm/IR/IntrinsicsX86.td | 6 + .../llvm-project/llvm/include/llvm/IR/Metadata.h | 20 +- contrib/llvm-project/llvm/include/llvm/IR/Module.h | 4 + .../llvm/include/llvm/IR/ModuleSummaryIndex.h | 2 +- .../llvm-project/llvm/include/llvm/IR/NoFolder.h | 18 +- .../llvm-project/llvm/include/llvm/IR/OptBisect.h | 4 +- .../llvm-project/llvm/include/llvm/LTO/Config.h | 6 +- .../llvm-project/llvm/include/llvm/MC/MCDwarf.h | 4 +- .../llvm/include/llvm/MC/MCSymbolWasm.h | 10 +- .../llvm/include/llvm/MC/MCSymbolXCOFF.h | 2 +- .../llvm/include/llvm/ObjCopy/CommonConfig.h | 1 + .../llvm/include/llvm/Object/Decompressor.h | 4 +- .../llvm/include/llvm/Support/ARMTargetParser.def | 3 + .../llvm/include/llvm/Support/Allocator.h | 21 +- .../llvm/include/llvm/Support/AllocatorBase.h | 22 + .../llvm/include/llvm/Support/Casting.h | 4 +- .../llvm/include/llvm/Support/CodeGen.h | 7 + .../llvm/include/llvm/Support/Compression.h | 23 +- .../llvm/include/llvm/Support/ConvertUTF.h | 2 + .../llvm-project/llvm/include/llvm/Support/Error.h | 2 +- .../llvm/include/llvm/Support/TargetOpcodes.def | 2 + .../llvm/include/llvm/Support/X86TargetParser.def | 1 + .../llvm/include/llvm/Target/GenericOpcodes.td | 2 + .../llvm/Target/GlobalISel/SelectionDAGCompat.td | 4 + .../llvm/include/llvm/Target/TargetSelectionDAG.td | 58 + .../llvm/Transforms/IPO/PassManagerBuilder.h | 2 - .../llvm/include/llvm/Transforms/Utils/Debugify.h | 66 +- .../llvm/include/llvm/Transforms/Utils/LoopUtils.h | 8 +- .../include/llvm/Transforms/Utils/ModuleUtils.h | 3 +- .../Vectorize/LoopVectorizationLegality.h | 7 - .../llvm/lib/Analysis/BranchProbabilityInfo.cpp | 11 +- .../llvm/lib/Analysis/ConstantFolding.cpp | 15 +- .../llvm/lib/Analysis/GlobalsModRef.cpp | 16 - .../llvm/lib/Analysis/IRSimilarityIdentifier.cpp | 4 +- .../llvm/lib/Analysis/InlineAdvisor.cpp | 13 +- .../llvm-project/llvm/lib/Analysis/InlineCost.cpp | 17 +- .../llvm/lib/Analysis/InstructionSimplify.cpp | 45 +- .../llvm/lib/Analysis/LazyValueInfo.cpp | 6 +- contrib/llvm-project/llvm/lib/Analysis/Loads.cpp | 5 +- .../llvm/lib/Analysis/MemoryBuiltins.cpp | 4 +- .../llvm-project/llvm/lib/Analysis/MustExecute.cpp | 2 +- .../llvm/lib/Analysis/ProfileSummaryInfo.cpp | 12 +- .../llvm/lib/Analysis/ScalarEvolution.cpp | 44 +- contrib/llvm-project/llvm/lib/Analysis/TFUtils.cpp | 11 +- .../llvm/lib/Analysis/TargetTransformInfo.cpp | 2 +- .../llvm/lib/Analysis/TypeBasedAliasAnalysis.cpp | 34 +- .../llvm/lib/Analysis/ValueTracking.cpp | 24 +- .../llvm-project/llvm/lib/Analysis/VectorUtils.cpp | 2 +- .../llvm-project/llvm/lib/AsmParser/LLLexer.cpp | 3 +- .../llvm-project/llvm/lib/AsmParser/LLParser.cpp | 84 +- .../llvm/lib/Bitcode/Reader/BitcodeReader.cpp | 15 +- .../llvm/lib/Bitcode/Writer/BitcodeWriter.cpp | 9 +- .../llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp | 125 +- .../lib/CodeGen/AsmPrinter/DIEHashAttributes.def | 2 +- .../llvm/lib/CodeGen/AtomicExpandPass.cpp | 2 + .../llvm/lib/CodeGen/ExpandVectorPredication.cpp | 3 +- .../llvm/lib/CodeGen/GlobalISel/CallLowering.cpp | 6 + .../llvm/lib/CodeGen/GlobalISel/CombinerHelper.cpp | 50 +- .../llvm/lib/CodeGen/GlobalISel/IRTranslator.cpp | 15 +- .../lib/CodeGen/GlobalISel/MachineIRBuilder.cpp | 31 + .../llvm/lib/CodeGen/InterleavedAccessPass.cpp | 9 +- .../CodeGen/LiveDebugValues/InstrRefBasedImpl.cpp | 46 +- .../llvm/lib/CodeGen/LiveIntervals.cpp | 17 +- .../llvm/lib/CodeGen/MIRParser/MIParser.cpp | 2 +- .../llvm/lib/CodeGen/MachineBasicBlock.cpp | 2 +- .../llvm/lib/CodeGen/MachineFunctionSplitter.cpp | 4 +- .../llvm/lib/CodeGen/MachineScheduler.cpp | 7 +- .../llvm/lib/CodeGen/MachineVerifier.cpp | 1 + .../llvm/lib/CodeGen/ModuloSchedule.cpp | 8 +- .../llvm/lib/CodeGen/PrologEpilogInserter.cpp | 2 +- .../llvm/lib/CodeGen/RegAllocEvictionAdvisor.h | 3 - .../llvm/lib/CodeGen/SelectOptimize.cpp | 4 +- .../llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp | 128 +- .../CodeGen/SelectionDAG/LegalizeFloatTypes.cpp | 17 + .../CodeGen/SelectionDAG/LegalizeIntegerTypes.cpp | 93 +- .../llvm/lib/CodeGen/SelectionDAG/LegalizeTypes.h | 3 + .../CodeGen/SelectionDAG/LegalizeVectorTypes.cpp | 8 +- .../llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp | 38 +- .../CodeGen/SelectionDAG/SelectionDAGBuilder.cpp | 168 +- .../lib/CodeGen/SelectionDAG/SelectionDAGBuilder.h | 2 +- .../CodeGen/SelectionDAG/SelectionDAGDumper.cpp | 2 + .../lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp | 99 +- .../CodeGen/SelectionDAG/StatepointLowering.cpp | 4 +- .../lib/CodeGen/SelectionDAG/TargetLowering.cpp | 160 +- .../lib/CodeGen/TargetLoweringObjectFileImpl.cpp | 6 +- .../llvm/lib/DWARFLinker/DWARFLinker.cpp | 1 + .../llvm/lib/DebugInfo/CodeView/CodeViewError.cpp | 5 +- .../llvm/lib/DebugInfo/DWARF/DWARFContext.cpp | 4 +- .../llvm/lib/DebugInfo/DWARF/DWARFDebugLine.cpp | 10 +- .../llvm/lib/DebugInfo/DWARF/DWARFDie.cpp | 29 +- .../llvm/lib/DebugInfo/DWARF/DWARFVerifier.cpp | 8 + .../llvm/lib/DebugInfo/MSF/MSFError.cpp | 7 +- .../llvm/lib/DebugInfo/PDB/DIA/DIAError.cpp | 7 +- .../llvm/lib/DebugInfo/PDB/GenericError.cpp | 7 +- .../llvm/lib/DebugInfo/PDB/Native/RawError.cpp | 7 +- .../llvm/lib/DebugInfo/Symbolize/Symbolize.cpp | 4 +- .../llvm/lib/Debuginfod/Debuginfod.cpp | 315 ++- .../llvm/lib/Debuginfod/HTTPServer.cpp | 189 ++ .../ExecutionEngine/GDBRegistrationListener.cpp | 30 +- .../llvm/lib/ExecutionEngine/JITLink/COFF.cpp | 137 ++ .../JITLink/COFFLinkGraphBuilder.cpp | 527 +++++ .../ExecutionEngine/JITLink/COFFLinkGraphBuilder.h | 199 ++ .../lib/ExecutionEngine/JITLink/COFF_x86_64.cpp | 216 ++ .../lib/ExecutionEngine/JITLink/EHFrameSupport.cpp | 5 +- .../lib/ExecutionEngine/JITLink/ELF_aarch64.cpp | 161 +- .../llvm/lib/ExecutionEngine/JITLink/ELF_riscv.cpp | 30 +- .../llvm/lib/ExecutionEngine/JITLink/JITLink.cpp | 11 +- .../lib/ExecutionEngine/JITLink/MachO_arm64.cpp | 2 +- .../llvm/lib/ExecutionEngine/JITLink/aarch64.cpp | 8 +- .../lib/ExecutionEngine/Orc/ELFNixPlatform.cpp | 6 +- .../llvm/lib/ExecutionEngine/Orc/LLJIT.cpp | 5 +- .../ExecutionEngine/Orc/ObjectFileInterface.cpp | 52 + .../llvm/lib/ExecutionEngine/Orc/OrcABISupport.cpp | 4 +- .../lib/ExecutionEngine/Orc/Shared/OrcError.cpp | 10 +- .../Orc/TargetProcess/JITLoaderGDB.cpp | 8 +- .../PerfJITEvents/PerfJITEventListener.cpp | 10 +- .../ExecutionEngine/RuntimeDyld/RuntimeDyld.cpp | 6 +- .../ExecutionEngine/RuntimeDyld/RuntimeDyldELF.cpp | 2 +- .../llvm/lib/Frontend/OpenMP/OMPContext.cpp | 4 +- .../llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp | 115 +- contrib/llvm-project/llvm/lib/IR/AsmWriter.cpp | 14 +- contrib/llvm-project/llvm/lib/IR/ConstantFold.cpp | 27 +- contrib/llvm-project/llvm/lib/IR/Constants.cpp | 183 +- .../llvm-project/llvm/lib/IR/ConstantsContext.h | 60 +- contrib/llvm-project/llvm/lib/IR/Core.cpp | 86 +- contrib/llvm-project/llvm/lib/IR/InlineAsm.cpp | 43 +- contrib/llvm-project/llvm/lib/IR/Instructions.cpp | 17 +- contrib/llvm-project/llvm/lib/IR/IntrinsicInst.cpp | 10 +- .../llvm-project/llvm/lib/IR/LLVMContextImpl.cpp | 5 +- contrib/llvm-project/llvm/lib/IR/Metadata.cpp | 7 - contrib/llvm-project/llvm/lib/IR/Module.cpp | 12 + contrib/llvm-project/llvm/lib/IR/OptBisect.cpp | 7 +- contrib/llvm-project/llvm/lib/IR/PassRegistry.cpp | 10 +- .../llvm/lib/InterfaceStub/IFSHandler.cpp | 21 +- contrib/llvm-project/llvm/lib/LTO/LTOBackend.cpp | 52 +- contrib/llvm-project/llvm/lib/Linker/IRMover.cpp | 28 +- .../llvm-project/llvm/lib/MC/ELFObjectWriter.cpp | 14 +- contrib/llvm-project/llvm/lib/MC/MCContext.cpp | 4 +- .../llvm/lib/MC/MCDisassembler/MCDisassembler.cpp | 4 +- .../llvm/lib/MC/MCParser/ELFAsmParser.cpp | 2 + .../llvm/lib/MC/MCParser/MasmParser.cpp | 92 +- contrib/llvm-project/llvm/lib/MC/MCSchedule.cpp | 8 +- contrib/llvm-project/llvm/lib/MC/MCSectionELF.cpp | 2 + .../llvm-project/llvm/lib/MC/MCSectionXCOFF.cpp | 4 +- .../llvm/lib/ObjCopy/ConfigManager.cpp | 28 +- .../llvm/lib/ObjCopy/ELF/ELFObjcopy.cpp | 125 +- .../llvm/lib/ObjCopy/ELF/ELFObject.cpp | 24 +- .../llvm-project/llvm/lib/ObjCopy/ELF/ELFObject.h | 2 +- .../llvm-project/llvm/lib/Object/Decompressor.cpp | 7 +- contrib/llvm-project/llvm/lib/Object/ELF.cpp | 1 + .../llvm-project/llvm/lib/Object/ELFObjectFile.cpp | 18 +- contrib/llvm-project/llvm/lib/Object/Error.cpp | 6 +- .../llvm/lib/ObjectYAML/DXContainerEmitter.cpp | 6 +- .../llvm-project/llvm/lib/ObjectYAML/ELFYAML.cpp | 1 + .../llvm/lib/Passes/PassBuilderPipelines.cpp | 3 +- .../llvm/lib/Passes/StandardInstrumentations.cpp | 5 +- .../lib/ProfileData/Coverage/CoverageMapping.cpp | 6 +- .../ProfileData/Coverage/CoverageMappingReader.cpp | 12 +- .../ProfileData/Coverage/CoverageMappingWriter.cpp | 12 +- .../llvm/lib/ProfileData/InstrProf.cpp | 32 +- .../llvm/lib/ProfileData/SampleProf.cpp | 6 +- .../llvm/lib/ProfileData/SampleProfReader.cpp | 10 +- .../llvm/lib/ProfileData/SampleProfWriter.cpp | 11 +- .../llvm-project/llvm/lib/Support/CommandLine.cpp | 6 +- .../llvm-project/llvm/lib/Support/Compression.cpp | 52 +- .../llvm-project/llvm/lib/Support/ConvertUTF.cpp | 10 + contrib/llvm-project/llvm/lib/Support/Error.cpp | 12 +- contrib/llvm-project/llvm/lib/Support/Process.cpp | 2 +- contrib/llvm-project/llvm/lib/Support/Unicode.cpp | 2 +- .../llvm-project/llvm/lib/Support/Unix/Process.inc | 8 +- .../llvm/lib/Support/VirtualFileSystem.cpp | 6 +- .../llvm/lib/Support/Windows/Signals.inc | 5 + .../llvm/lib/Support/X86TargetParser.cpp | 6 +- .../llvm-project/llvm/lib/Support/raw_ostream.cpp | 2 +- contrib/llvm-project/llvm/lib/TableGen/Record.cpp | 2 +- .../llvm/lib/Target/AArch64/AArch64.td | 11 +- .../llvm/lib/Target/AArch64/AArch64AsmPrinter.cpp | 2 + .../lib/Target/AArch64/AArch64ISelLowering.cpp | 239 +- .../llvm/lib/Target/AArch64/AArch64ISelLowering.h | 4 + .../llvm/lib/Target/AArch64/AArch64InstrAtomics.td | 38 +- .../llvm/lib/Target/AArch64/AArch64InstrFormats.td | 2 +- .../llvm/lib/Target/AArch64/AArch64InstrInfo.td | 2 + .../llvm/lib/Target/AArch64/AArch64SVEInstrInfo.td | 73 +- .../llvm/lib/Target/AArch64/AArch64SchedA53.td | 3 +- .../llvm/lib/Target/AArch64/AArch64SchedA55.td | 2 +- .../llvm/lib/Target/AArch64/AArch64SchedA57.td | 7 +- .../llvm/lib/Target/AArch64/AArch64SchedA64FX.td | 4 +- .../llvm/lib/Target/AArch64/AArch64SchedAmpere1.td | 4 +- .../llvm/lib/Target/AArch64/AArch64SchedCyclone.td | 3 +- .../lib/Target/AArch64/AArch64SchedExynosM3.td | 3 +- .../lib/Target/AArch64/AArch64SchedExynosM4.td | 3 +- .../lib/Target/AArch64/AArch64SchedExynosM5.td | 3 +- .../llvm/lib/Target/AArch64/AArch64SchedFalkor.td | 3 +- .../llvm/lib/Target/AArch64/AArch64SchedKryo.td | 3 +- .../lib/Target/AArch64/AArch64SchedNeoverseN2.td | 2279 ++++++++++++++++++++ .../llvm/lib/Target/AArch64/AArch64SchedTSV110.td | 3 +- .../lib/Target/AArch64/AArch64SchedThunderX.td | 3 +- .../lib/Target/AArch64/AArch64SchedThunderX2T99.td | 3 +- .../Target/AArch64/AArch64SchedThunderX3T110.td | 3 +- .../Target/AArch64/AArch64TargetTransformInfo.cpp | 47 + .../Target/AArch64/AArch64TargetTransformInfo.h | 6 +- .../Target/AArch64/GISel/AArch64CallLowering.cpp | 29 +- .../lib/Target/AArch64/GISel/AArch64CallLowering.h | 4 + .../AArch64/GISel/AArch64InstructionSelector.cpp | 57 +- .../Target/AArch64/GISel/AArch64LegalizerInfo.cpp | 35 +- .../AArch64/MCTargetDesc/AArch64MCCodeEmitter.cpp | 14 +- .../AArch64/MCTargetDesc/AArch64MCTargetDesc.cpp | 1 + .../AArch64/MCTargetDesc/AArch64MCTargetDesc.h | 1 + .../llvm/lib/Target/AArch64/SMEInstrFormats.td | 34 + .../llvm/lib/Target/AArch64/SVEInstrFormats.td | 10 +- .../lib/Target/AArch64/Utils/AArch64BaseInfo.h | 3 +- .../llvm-project/llvm/lib/Target/AMDGPU/AMDGPU.h | 3 + .../lib/Target/AMDGPU/AMDGPUCodeGenPrepare.cpp | 4 +- .../llvm/lib/Target/AMDGPU/AMDGPUISelDAGToDAG.cpp | 53 +- .../llvm/lib/Target/AMDGPU/AMDGPUISelDAGToDAG.h | 8 +- .../llvm/lib/Target/AMDGPU/AMDGPUISelLowering.cpp | 2 + .../Target/AMDGPU/AMDGPUInstructionSelector.cpp | 47 +- .../llvm/lib/Target/AMDGPU/AMDGPUInstructions.td | 76 +- .../llvm/lib/Target/AMDGPU/AMDGPUMCInstLower.cpp | 4 + .../lib/Target/AMDGPU/AMDGPUMachineModuleInfo.h | 4 +- .../llvm/lib/Target/AMDGPU/AMDGPUSubtarget.cpp | 11 +- .../llvm/lib/Target/AMDGPU/AMDGPUTargetMachine.cpp | 13 + .../llvm/lib/Target/AMDGPU/BUFInstructions.td | 27 +- .../llvm/lib/Target/AMDGPU/DSInstructions.td | 77 +- .../llvm/lib/Target/AMDGPU/FLATInstructions.td | 27 +- .../llvm/lib/Target/AMDGPU/GCNCreateVOPD.cpp | 175 ++ .../llvm/lib/Target/AMDGPU/GCNDPPCombine.cpp | 127 +- .../llvm/lib/Target/AMDGPU/GCNVOPDUtils.cpp | 212 ++ .../llvm/lib/Target/AMDGPU/GCNVOPDUtils.h | 32 + .../AMDGPU/MCTargetDesc/AMDGPUMCCodeEmitter.h | 6 - .../AMDGPU/MCTargetDesc/AMDGPUMCTargetDesc.cpp | 1 + .../AMDGPU/MCTargetDesc/AMDGPUMCTargetDesc.h | 1 + .../AMDGPU/MCTargetDesc/R600MCCodeEmitter.cpp | 13 +- .../AMDGPU/MCTargetDesc/R600MCTargetDesc.cpp | 2 + .../Target/AMDGPU/MCTargetDesc/R600MCTargetDesc.h | 1 + .../Target/AMDGPU/MCTargetDesc/SIMCCodeEmitter.cpp | 8 +- .../llvm/lib/Target/AMDGPU/R600ISelLowering.cpp | 2 +- .../llvm/lib/Target/AMDGPU/R600ISelLowering.h | 4 +- .../llvm/lib/Target/AMDGPU/R600MCInstLower.cpp | 4 + .../llvm/lib/Target/AMDGPU/SIISelLowering.cpp | 2 +- .../llvm/lib/Target/AMDGPU/SIInstrInfo.cpp | 19 +- .../llvm/lib/Target/AMDGPU/SIInstrInfo.h | 3 + .../llvm/lib/Target/AMDGPU/SIInstrInfo.td | 125 +- .../llvm/lib/Target/AMDGPU/SIInstructions.td | 37 + .../llvm/lib/Target/AMDGPU/SILowerControlFlow.cpp | 1 + .../llvm/lib/Target/AMDGPU/SILowerSGPRSpills.cpp | 2 +- .../llvm/lib/Target/AMDGPU/SIMachineScheduler.cpp | 6 + .../llvm/lib/Target/AMDGPU/SIMemoryLegalizer.cpp | 8 +- .../lib/Target/AMDGPU/SIOptimizeExecMasking.cpp | 524 ++--- .../Target/AMDGPU/SIOptimizeExecMaskingPreRA.cpp | 15 +- .../llvm/lib/Target/AMDGPU/SIRegisterInfo.cpp | 4 + .../llvm/lib/Target/AMDGPU/SIRegisterInfo.h | 2 + .../lib/Target/AMDGPU/Utils/AMDGPUBaseInfo.cpp | 34 + .../llvm/lib/Target/AMDGPU/Utils/AMDGPUBaseInfo.h | 14 + .../llvm/lib/Target/AMDGPU/VOP2Instructions.td | 6 +- .../llvm/lib/Target/AMDGPU/VOPCInstructions.td | 2 - .../llvm/lib/Target/AMDGPU/VOPInstructions.td | 6 +- .../llvm/lib/Target/ARC/ARCAsmPrinter.cpp | 3 + .../Target/ARC/MCTargetDesc/ARCMCTargetDesc.cpp | 1 + .../lib/Target/ARC/MCTargetDesc/ARCMCTargetDesc.h | 1 + contrib/llvm-project/llvm/lib/Target/ARM/ARM.td | 11 +- .../llvm/lib/Target/ARM/ARMAsmPrinter.cpp | 4 + .../llvm/lib/Target/ARM/ARMISelLowering.cpp | 14 +- .../llvm/lib/Target/ARM/ARMTargetTransformInfo.cpp | 6 +- .../llvm/lib/Target/ARM/ARMTargetTransformInfo.h | 2 +- .../Target/ARM/MCTargetDesc/ARMMCTargetDesc.cpp | 1 + .../lib/Target/ARM/MCTargetDesc/ARMMCTargetDesc.h | 1 + .../lib/Target/ARM/MVEGatherScatterLowering.cpp | 8 +- .../llvm/lib/Target/AVR/AVRAsmPrinter.cpp | 4 + .../Target/AVR/MCTargetDesc/AVRMCTargetDesc.cpp | 1 + .../lib/Target/AVR/MCTargetDesc/AVRMCTargetDesc.h | 1 + .../lib/Target/BPF/BPFAbstractMemberAccess.cpp | 79 + .../llvm/lib/Target/BPF/BPFAsmPrinter.cpp | 3 + contrib/llvm-project/llvm/lib/Target/BPF/BTF.h | 2 + .../Target/BPF/MCTargetDesc/BPFMCCodeEmitter.cpp | 15 +- .../Target/BPF/MCTargetDesc/BPFMCTargetDesc.cpp | 1 + .../lib/Target/BPF/MCTargetDesc/BPFMCTargetDesc.h | 1 + .../llvm/lib/Target/CSKY/CSKYAsmPrinter.cpp | 3 + .../llvm/lib/Target/CSKY/CSKYInstrInfo.td | 2 +- .../llvm/lib/Target/CSKY/CSKYInstrInfo16Instr.td | 2 +- .../Target/CSKY/MCTargetDesc/CSKYMCTargetDesc.cpp | 1 + .../Target/CSKY/MCTargetDesc/CSKYMCTargetDesc.h | 1 + .../llvm-project/llvm/lib/Target/DirectX/DXIL.td | 8 +- .../DirectX/DXILWriter/DXILBitcodeWriter.cpp | 4 + .../llvm/lib/Target/Hexagon/HexagonAsmPrinter.cpp | 3 + .../lib/Target/Hexagon/HexagonFrameLowering.cpp | 2 +- .../Hexagon/MCTargetDesc/HexagonMCCodeEmitter.cpp | 3 - .../Hexagon/MCTargetDesc/HexagonMCCodeEmitter.h | 5 - .../Hexagon/MCTargetDesc/HexagonMCTargetDesc.cpp | 1 + .../Hexagon/MCTargetDesc/HexagonMCTargetDesc.h | 1 + .../lib/Target/Lanai/AsmParser/LanaiAsmParser.cpp | 4 +- .../llvm/lib/Target/Lanai/LanaiAsmPrinter.cpp | 3 + .../Lanai/MCTargetDesc/LanaiMCTargetDesc.cpp | 1 + .../Target/Lanai/MCTargetDesc/LanaiMCTargetDesc.h | 1 + .../lib/Target/LoongArch/LoongArchAsmPrinter.cpp | 3 + .../lib/Target/LoongArch/LoongArchAsmPrinter.h | 4 + .../Target/LoongArch/LoongArchFloat32InstrInfo.td | 52 + .../Target/LoongArch/LoongArchFloat64InstrInfo.td | 54 + .../Target/LoongArch/LoongArchFrameLowering.cpp | 172 +- .../lib/Target/LoongArch/LoongArchFrameLowering.h | 18 + .../lib/Target/LoongArch/LoongArchISelDAGToDAG.cpp | 56 +- .../lib/Target/LoongArch/LoongArchISelDAGToDAG.h | 5 + .../lib/Target/LoongArch/LoongArchISelLowering.cpp | 569 +++++ .../lib/Target/LoongArch/LoongArchISelLowering.h | 26 + .../lib/Target/LoongArch/LoongArchInstrInfo.cpp | 70 +- .../llvm/lib/Target/LoongArch/LoongArchInstrInfo.h | 10 + .../lib/Target/LoongArch/LoongArchInstrInfo.td | 218 +- .../lib/Target/LoongArch/LoongArchMCInstLower.cpp | 33 +- .../lib/Target/LoongArch/LoongArchRegisterInfo.cpp | 24 +- .../Target/LoongArch/LoongArchTargetMachine.cpp | 7 + .../MCTargetDesc/LoongArchMCTargetDesc.cpp | 1 + .../LoongArch/MCTargetDesc/LoongArchMCTargetDesc.h | 1 + .../llvm/lib/Target/M68k/M68kAsmPrinter.cpp | 3 + .../Target/M68k/MCTargetDesc/M68kMCTargetDesc.cpp | 1 + .../Target/M68k/MCTargetDesc/M68kMCTargetDesc.h | 1 + .../MSP430/MCTargetDesc/MSP430MCTargetDesc.cpp | 1 + .../MSP430/MCTargetDesc/MSP430MCTargetDesc.h | 1 + .../llvm/lib/Target/MSP430/MSP430AsmPrinter.cpp | 3 + .../Target/Mips/MCTargetDesc/MipsMCTargetDesc.cpp | 1 + .../Target/Mips/MCTargetDesc/MipsMCTargetDesc.h | 1 + .../llvm/lib/Target/Mips/MipsAsmPrinter.cpp | 4 + .../NVPTX/MCTargetDesc/NVPTXMCTargetDesc.cpp | 1 + .../Target/NVPTX/MCTargetDesc/NVPTXMCTargetDesc.h | 1 + contrib/llvm-project/llvm/lib/Target/NVPTX/NVPTX.h | 1 + .../llvm/lib/Target/NVPTX/NVPTXAsmPrinter.cpp | 3 + .../llvm/lib/Target/NVPTX/NVPTXGenericToNVVM.cpp | 4 - .../llvm/lib/Target/NVPTX/NVPTXISelLowering.cpp | 2 +- .../llvm/lib/Target/NVPTX/NVPTXImageOptimizer.cpp | 2 + .../lib/Target/NVPTX/NVPTXPrologEpilogPass.cpp | 2 + .../llvm/lib/Target/NVPTX/NVPTXUtilities.cpp | 54 +- .../PowerPC/MCTargetDesc/PPCMCCodeEmitter.cpp | 10 +- .../Target/PowerPC/MCTargetDesc/PPCMCCodeEmitter.h | 6 - .../PowerPC/MCTargetDesc/PPCMCTargetDesc.cpp | 1 + .../Target/PowerPC/MCTargetDesc/PPCMCTargetDesc.h | 1 + .../llvm/lib/Target/PowerPC/PPCAsmPrinter.cpp | 48 +- .../llvm/lib/Target/PowerPC/PPCISelLowering.cpp | 9 +- .../llvm/lib/Target/PowerPC/PPCISelLowering.h | 1 + .../llvm/lib/Target/PowerPC/PPCTLSDynamicCall.cpp | 20 +- .../RISCV/MCTargetDesc/RISCVMCCodeEmitter.cpp | 10 - .../RISCV/MCTargetDesc/RISCVMCTargetDesc.cpp | 1 + .../Target/RISCV/MCTargetDesc/RISCVMCTargetDesc.h | 1 + .../llvm/lib/Target/RISCV/RISCVAsmPrinter.cpp | 3 + .../llvm/lib/Target/RISCV/RISCVFrameLowering.cpp | 17 +- .../llvm/lib/Target/RISCV/RISCVFrameLowering.h | 4 +- .../llvm/lib/Target/RISCV/RISCVISelDAGToDAG.cpp | 646 +++--- .../llvm/lib/Target/RISCV/RISCVISelDAGToDAG.h | 13 +- .../llvm/lib/Target/RISCV/RISCVISelLowering.cpp | 105 +- .../llvm/lib/Target/RISCV/RISCVISelLowering.h | 6 +- .../llvm/lib/Target/RISCV/RISCVInstrInfo.td | 1 - .../llvm/lib/Target/RISCV/RISCVInstrInfoV.td | 85 +- .../lib/Target/RISCV/RISCVInstrInfoVSDPatterns.td | 36 +- .../lib/Target/RISCV/RISCVInstrInfoVVLPatterns.td | 16 +- .../llvm/lib/Target/RISCV/RISCVInstrInfoZb.td | 28 +- .../lib/Target/RISCV/RISCVMakeCompressible.cpp | 10 +- .../llvm/lib/Target/RISCV/RISCVScheduleV.td | 28 + .../lib/Target/RISCV/RISCVTargetTransformInfo.h | 4 + .../SPIRV/MCTargetDesc/SPIRVMCCodeEmitter.cpp | 10 - .../SPIRV/MCTargetDesc/SPIRVMCTargetDesc.cpp | 1 + .../Target/SPIRV/MCTargetDesc/SPIRVMCTargetDesc.h | 1 + .../llvm/lib/Target/SPIRV/SPIRVAsmPrinter.cpp | 3 + .../llvm/lib/Target/SPIRV/SPIRVCallLowering.cpp | 6 + .../lib/Target/SPIRV/SPIRVDuplicatesTracker.cpp | 95 + .../llvm/lib/Target/SPIRV/SPIRVDuplicatesTracker.h | 174 ++ .../llvm/lib/Target/SPIRV/SPIRVGlobalRegistry.cpp | 52 +- .../llvm/lib/Target/SPIRV/SPIRVGlobalRegistry.h | 41 +- .../lib/Target/SPIRV/SPIRVInstructionSelector.cpp | 34 +- .../llvm/lib/Target/SPIRV/SPIRVModuleAnalysis.cpp | 101 +- .../llvm/lib/Target/SPIRV/SPIRVModuleAnalysis.h | 6 + .../Sparc/MCTargetDesc/SparcMCCodeEmitter.cpp | 15 +- .../Sparc/MCTargetDesc/SparcMCTargetDesc.cpp | 1 + .../Target/Sparc/MCTargetDesc/SparcMCTargetDesc.h | 1 + .../llvm/lib/Target/Sparc/SparcAsmPrinter.cpp | 2 + .../SystemZ/MCTargetDesc/SystemZMCCodeEmitter.cpp | 17 +- .../SystemZ/MCTargetDesc/SystemZMCTargetDesc.cpp | 1 + .../SystemZ/MCTargetDesc/SystemZMCTargetDesc.h | 1 + .../llvm/lib/Target/SystemZ/SystemZAsmPrinter.cpp | 3 + .../llvm/lib/Target/SystemZ/SystemZCallingConv.td | 6 +- .../lib/Target/SystemZ/SystemZFrameLowering.cpp | 113 +- .../llvm/lib/Target/TargetLoweringObjectFile.cpp | 7 + .../lib/Target/VE/MCTargetDesc/VEMCCodeEmitter.cpp | 15 +- .../lib/Target/VE/MCTargetDesc/VEMCTargetDesc.cpp | 1 + .../lib/Target/VE/MCTargetDesc/VEMCTargetDesc.h | 1 + .../llvm/lib/Target/VE/VEAsmPrinter.cpp | 2 + .../llvm-project/llvm/lib/Target/VE/VEInstrInfo.td | 8 +- .../llvm/lib/Target/VE/VERegisterInfo.cpp | 203 +- .../llvm/lib/Target/VE/VVPISelLowering.cpp | 2 +- .../AsmParser/WebAssemblyAsmTypeCheck.cpp | 7 +- .../MCTargetDesc/WebAssemblyMCTargetDesc.cpp | 1 + .../MCTargetDesc/WebAssemblyMCTargetDesc.h | 1 + .../TargetInfo/WebAssemblyTargetInfo.cpp | 1 + .../WebAssembly/Utils/WebAssemblyTypeUtilities.cpp | 33 +- .../WebAssembly/Utils/WebAssemblyTypeUtilities.h | 8 +- .../WebAssembly/Utils/WebAssemblyUtilities.cpp | 22 + .../WebAssembly/Utils/WebAssemblyUtilities.h | 4 + .../Target/WebAssembly/WebAssemblyAsmPrinter.cpp | 2 + .../Target/WebAssembly/WebAssemblyCFGStackify.cpp | 22 +- .../Target/WebAssembly/WebAssemblyInstrInfo.cpp | 18 +- .../WebAssemblyLowerEmscriptenEHSjLj.cpp | 2 +- .../Target/WebAssembly/WebAssemblyMCInstLower.cpp | 25 +- .../lib/Target/WebAssembly/WebAssemblyPeephole.cpp | 27 +- .../WebAssemblyRuntimeLibcallSignatures.cpp | 17 +- .../Target/X86/MCTargetDesc/X86InstComments.cpp | 2 +- .../X86/MCTargetDesc/X86InstrRelaxTables.cpp | 8 +- .../Target/X86/MCTargetDesc/X86MCTargetDesc.cpp | 1 + contrib/llvm-project/llvm/lib/Target/X86/X86.h | 4 + contrib/llvm-project/llvm/lib/Target/X86/X86.td | 3 + .../llvm/lib/Target/X86/X86EvexToVex.cpp | 1 + .../llvm/lib/Target/X86/X86ISelLowering.cpp | 193 +- .../llvm/lib/Target/X86/X86InstrCompiler.td | 38 - .../llvm/lib/Target/X86/X86InstrFMA3Info.cpp | 2 +- .../llvm/lib/Target/X86/X86InstrFoldTables.cpp | 8 +- .../llvm/lib/Target/X86/X86InstrInfo.td | 1 + .../llvm/lib/Target/X86/X86InstrSystem.td | 9 + .../llvm/lib/Target/X86/X86IntrinsicsInfo.h | 3 +- .../llvm/lib/Target/X86/X86MCInstLower.cpp | 4 + .../llvm/lib/Target/X86/X86PartialReduction.cpp | 6 +- .../llvm/lib/Target/X86/X86ReturnThunks.cpp | 92 + .../llvm/lib/Target/X86/X86TargetMachine.cpp | 2 + .../XCore/MCTargetDesc/XCoreMCTargetDesc.cpp | 1 + .../Target/XCore/MCTargetDesc/XCoreMCTargetDesc.h | 1 + .../llvm/lib/Target/XCore/XCoreAsmPrinter.cpp | 3 + .../llvm/lib/ToolDrivers/llvm-lib/Options.td | 2 + .../llvm/lib/Transforms/Coroutines/CoroFrame.cpp | 49 +- .../llvm/lib/Transforms/Coroutines/CoroSplit.cpp | 2 +- .../llvm/lib/Transforms/IPO/Attributor.cpp | 12 +- .../lib/Transforms/IPO/AttributorAttributes.cpp | 173 +- .../llvm/lib/Transforms/IPO/GlobalOpt.cpp | 6 +- .../llvm/lib/Transforms/IPO/IROutliner.cpp | 34 +- .../llvm/lib/Transforms/IPO/OpenMPOpt.cpp | 9 +- .../llvm/lib/Transforms/IPO/PassManagerBuilder.cpp | 177 -- .../lib/Transforms/IPO/SampleContextTracker.cpp | 2 +- .../llvm/lib/Transforms/IPO/SampleProfile.cpp | 4 +- .../Transforms/InstCombine/InstCombineAddSub.cpp | 105 +- .../Transforms/InstCombine/InstCombineAndOrXor.cpp | 13 +- .../InstCombine/InstCombineAtomicRMW.cpp | 8 +- .../Transforms/InstCombine/InstCombineCalls.cpp | 7 +- .../Transforms/InstCombine/InstCombineCasts.cpp | 9 +- .../Transforms/InstCombine/InstCombineCompares.cpp | 13 +- .../InstCombine/InstCombineMulDivRem.cpp | 42 +- .../InstCombine/InstCombineSimplifyDemanded.cpp | 4 +- .../InstCombine/InstCombineVectorOps.cpp | 16 +- .../InstCombine/InstructionCombining.cpp | 22 +- .../Instrumentation/AddressSanitizer.cpp | 4 + .../lib/Transforms/Instrumentation/CGProfile.cpp | 3 +- .../Instrumentation/HWAddressSanitizer.cpp | 147 +- .../Transforms/Instrumentation/InstrProfiling.cpp | 1 + .../Transforms/Instrumentation/ThreadSanitizer.cpp | 2 +- .../lib/Transforms/Scalar/ConstantHoisting.cpp | 4 +- .../llvm/lib/Transforms/Scalar/GVN.cpp | 25 +- .../llvm/lib/Transforms/Scalar/IndVarSimplify.cpp | 60 +- .../Scalar/InductiveRangeCheckElimination.cpp | 16 +- .../llvm/lib/Transforms/Scalar/JumpThreading.cpp | 17 +- .../llvm/lib/Transforms/Scalar/LICM.cpp | 3 +- .../llvm/lib/Transforms/Scalar/LoopDistribute.cpp | 4 +- .../lib/Transforms/Scalar/LoopIdiomRecognize.cpp | 4 +- .../lib/Transforms/Scalar/LoopStrengthReduce.cpp | 29 +- .../lib/Transforms/Scalar/LoopUnrollAndJamPass.cpp | 8 +- .../llvm/lib/Transforms/Scalar/LoopUnrollPass.cpp | 14 +- .../llvm/lib/Transforms/Scalar/Reassociate.cpp | 19 +- .../llvm/lib/Transforms/Utils/BasicBlockUtils.cpp | 7 +- .../lib/Transforms/Utils/BreakCriticalEdges.cpp | 8 +- .../llvm/lib/Transforms/Utils/CodeExtractor.cpp | 3 +- .../llvm/lib/Transforms/Utils/Debugify.cpp | 47 +- .../lib/Transforms/Utils/LoopUnrollRuntime.cpp | 2 +- .../llvm/lib/Transforms/Utils/LoopUtils.cpp | 65 +- .../llvm/lib/Transforms/Utils/LowerAtomic.cpp | 4 + .../llvm/lib/Transforms/Utils/MisExpect.cpp | 4 +- .../llvm/lib/Transforms/Utils/ModuleUtils.cpp | 10 +- .../Transforms/Utils/PromoteMemoryToRegister.cpp | 30 +- .../llvm/lib/Transforms/Utils/SCCPSolver.cpp | 43 +- .../Transforms/Utils/ScalarEvolutionExpander.cpp | 3 +- .../llvm/lib/Transforms/Utils/SimplifyCFG.cpp | 205 +- .../llvm/lib/Transforms/Utils/SimplifyIndVar.cpp | 74 +- .../llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp | 189 +- .../Vectorize/LoopVectorizationLegality.cpp | 30 - .../Vectorize/LoopVectorizationPlanner.h | 51 +- .../lib/Transforms/Vectorize/LoopVectorize.cpp | 733 +++---- .../lib/Transforms/Vectorize/SLPVectorizer.cpp | 18 +- .../lib/Transforms/Vectorize/VPRecipeBuilder.h | 3 +- .../llvm/lib/Transforms/Vectorize/VPlan.cpp | 73 +- .../llvm/lib/Transforms/Vectorize/VPlan.h | 62 +- .../llvm/lib/Transforms/Vectorize/VPlanRecipes.cpp | 365 +++- .../llvm/lib/Transforms/Vectorize/VPlanValue.h | 2 + .../lib/Transforms/Vectorize/VPlanVerifier.cpp | 69 +- .../lib/Transforms/Vectorize/VectorCombine.cpp | 174 +- .../llvm-project/llvm/tools/bugpoint/bugpoint.cpp | 1 - contrib/llvm-project/llvm/tools/llc/llc.cpp | 15 +- contrib/llvm-project/llvm/tools/lli/lli.cpp | 5 +- .../llvm-project/llvm/tools/llvm-as/llvm-as.cpp | 1 - .../llvm/tools/llvm-cov/CoverageExporterJson.cpp | 4 +- .../llvm-project/llvm/tools/llvm-cov/llvm-cov.cpp | 1 - .../llvm/tools/llvm-lto2/llvm-lto2.cpp | 30 +- .../llvm-project/llvm/tools/llvm-mc/llvm-mc.cpp | 2 +- .../tools/llvm-mca/Views/InstructionInfoView.cpp | 2 +- .../llvm-project/llvm/tools/llvm-mca/llvm-mca.cpp | 18 +- .../llvm/tools/llvm-objcopy/ObjcopyOptions.cpp | 58 +- .../llvm/tools/llvm-objcopy/ObjcopyOpts.td | 5 + .../llvm/tools/llvm-objdump/COFFDump.cpp | 32 +- .../llvm/tools/llvm-objdump/COFFDump.h | 4 +- .../llvm/tools/llvm-objdump/MachODump.cpp | 4 +- .../llvm/tools/llvm-objdump/OffloadDump.cpp | 24 +- .../llvm/tools/llvm-objdump/XCOFFDump.cpp | 27 +- .../llvm/tools/llvm-objdump/XCOFFDump.h | 8 +- .../llvm/tools/llvm-objdump/llvm-objdump.cpp | 276 +-- .../llvm/tools/llvm-objdump/llvm-objdump.h | 8 +- .../llvm/tools/llvm-pdbutil/llvm-pdbutil.cpp | 1 - .../llvm-project/llvm/tools/llvm-sim/llvm-sim.cpp | 4 +- .../llvm/tools/llvm-xray/xray-registry.cpp | 14 +- .../llvm-project/llvm/tools/opt/NewPMDriver.cpp | 39 +- contrib/llvm-project/llvm/tools/opt/NewPMDriver.h | 5 +- contrib/llvm-project/llvm/tools/opt/opt.cpp | 15 +- .../llvm/utils/TableGen/CodeEmitterGen.cpp | 133 -- .../llvm/utils/TableGen/CodeGenDAGPatterns.cpp | 158 +- .../llvm/utils/TableGen/CodeGenDAGPatterns.h | 8 +- .../llvm/utils/TableGen/CodeGenRegisters.cpp | 20 + .../llvm/utils/TableGen/CodeGenRegisters.h | 5 +- .../llvm/utils/TableGen/GlobalISelEmitter.cpp | 77 +- .../llvm/utils/TableGen/InstrInfoEmitter.cpp | 154 +- .../llvm/utils/TableGen/SubtargetFeatureInfo.cpp | 9 +- contrib/llvm-project/openmp/runtime/src/dllexports | 7 + contrib/llvm-project/openmp/runtime/src/kmp.h | 8 + .../openmp/runtime/src/kmp_csupport.cpp | 57 +- .../openmp/runtime/src/kmp_dispatch.cpp | 213 ++ etc/mtree/BSD.include.dist | 2 + lib/clang/headers/Makefile | 1 + lib/clang/include/VCSVersion.inc | 6 +- lib/clang/include/lld/Common/Version.inc | 2 +- lib/clang/include/llvm/Config/llvm-config.h | 3 + lib/clang/include/llvm/Support/VCSRevision.h | 2 +- lib/clang/libclang/Makefile | 6 + lib/clang/liblldb/LLDBWrapLua.cpp | 215 +- lib/clang/liblldb/Makefile | 1 + lib/clang/libllvm/Makefile | 6 +- lib/libc++/Makefile | 43 + lib/libc++/__config_site | 1 - lib/libc++/module.modulemap | 41 + tools/build/mk/OptionalObsoleteFiles.inc | 1 + 1068 files changed, 27183 insertions(+), 10472 deletions(-) create mode 100644 contrib/llvm-project/clang/include/clang/Analysis/FlowSensitive/DebugSupport.h create mode 100644 contrib/llvm-project/clang/include/clang/Basic/MakeSupport.h create mode 100644 contrib/llvm-project/clang/include/clang/Sema/HLSLExternalSemaSource.h create mode 100644 contrib/llvm-project/clang/lib/Analysis/FlowSensitive/DebugSupport.cpp create mode 100644 contrib/llvm-project/clang/lib/Basic/MakeSupport.cpp create mode 100644 contrib/llvm-project/clang/lib/Format/MacroCallReconstructor.cpp create mode 100644 contrib/llvm-project/clang/lib/Headers/rdpruintrin.h create mode 100644 contrib/llvm-project/clang/lib/Sema/HLSLExternalSemaSource.cpp create mode 100644 contrib/llvm-project/compiler-rt/lib/orc/elfnix_tls.aarch64.S create mode 100644 contrib/llvm-project/libcxx/include/__algorithm/ranges_equal_range.h create mode 100644 contrib/llvm-project/libcxx/include/__algorithm/ranges_find_end.h create mode 100644 contrib/llvm-project/libcxx/include/__algorithm/ranges_generate.h create mode 100644 contrib/llvm-project/libcxx/include/__algorithm/ranges_generate_n.h create mode 100644 contrib/llvm-project/libcxx/include/__algorithm/ranges_includes.h create mode 100644 contrib/llvm-project/libcxx/include/__algorithm/ranges_inplace_merge.h create mode 100644 contrib/llvm-project/libcxx/include/__algorithm/ranges_is_heap.h create mode 100644 contrib/llvm-project/libcxx/include/__algorithm/ranges_is_heap_until.h create mode 100644 contrib/llvm-project/libcxx/include/__algorithm/ranges_make_heap.h create mode 100644 contrib/llvm-project/libcxx/include/__algorithm/ranges_merge.h create mode 100644 contrib/llvm-project/libcxx/include/__algorithm/ranges_nth_element.h create mode 100644 contrib/llvm-project/libcxx/include/__algorithm/ranges_partial_sort_copy.h create mode 100644 contrib/llvm-project/libcxx/include/__algorithm/ranges_partition.h create mode 100644 contrib/llvm-project/libcxx/include/__algorithm/ranges_partition_copy.h create mode 100644 contrib/llvm-project/libcxx/include/__algorithm/ranges_partition_point.h create mode 100644 contrib/llvm-project/libcxx/include/__algorithm/ranges_pop_heap.h create mode 100644 contrib/llvm-project/libcxx/include/__algorithm/ranges_push_heap.h create mode 100644 contrib/llvm-project/libcxx/include/__algorithm/ranges_remove.h create mode 100644 contrib/llvm-project/libcxx/include/__algorithm/ranges_remove_copy.h create mode 100644 contrib/llvm-project/libcxx/include/__algorithm/ranges_remove_copy_if.h create mode 100644 contrib/llvm-project/libcxx/include/__algorithm/ranges_remove_if.h create mode 100644 contrib/llvm-project/libcxx/include/__algorithm/ranges_replace_copy.h create mode 100644 contrib/llvm-project/libcxx/include/__algorithm/ranges_replace_copy_if.h create mode 100644 contrib/llvm-project/libcxx/include/__algorithm/ranges_reverse_copy.h create mode 100644 contrib/llvm-project/libcxx/include/__algorithm/ranges_rotate_copy.h create mode 100644 contrib/llvm-project/libcxx/include/__algorithm/ranges_search.h create mode 100644 contrib/llvm-project/libcxx/include/__algorithm/ranges_search_n.h create mode 100644 contrib/llvm-project/libcxx/include/__algorithm/ranges_set_difference.h create mode 100644 contrib/llvm-project/libcxx/include/__algorithm/ranges_set_intersection.h create mode 100644 contrib/llvm-project/libcxx/include/__algorithm/ranges_set_symmetric_difference.h create mode 100644 contrib/llvm-project/libcxx/include/__algorithm/ranges_set_union.h create mode 100644 contrib/llvm-project/libcxx/include/__algorithm/ranges_shuffle.h create mode 100644 contrib/llvm-project/libcxx/include/__algorithm/ranges_sort_heap.h create mode 100644 contrib/llvm-project/libcxx/include/__algorithm/ranges_stable_partition.h create mode 100644 contrib/llvm-project/libcxx/include/__algorithm/ranges_unique.h create mode 100644 contrib/llvm-project/libcxx/include/__algorithm/ranges_unique_copy.h create mode 100644 contrib/llvm-project/libcxx/include/__debug_utils/randomize_range.h create mode 100644 contrib/llvm-project/lldb/include/lldb/Expression/DWARFExpressionList.h create mode 100644 contrib/llvm-project/lldb/source/Expression/DWARFExpressionList.cpp create mode 100644 contrib/llvm-project/llvm/include/llvm/Debuginfod/HTTPServer.h create mode 100644 contrib/llvm-project/llvm/include/llvm/ExecutionEngine/JITLink/COFF.h create mode 100644 contrib/llvm-project/llvm/include/llvm/ExecutionEngine/JITLink/COFF_x86_64.h create mode 100644 contrib/llvm-project/llvm/lib/Debuginfod/HTTPServer.cpp create mode 100644 contrib/llvm-project/llvm/lib/ExecutionEngine/JITLink/COFF.cpp create mode 100644 contrib/llvm-project/llvm/lib/ExecutionEngine/JITLink/COFFLinkGraphBuilder.cpp create mode 100644 contrib/llvm-project/llvm/lib/ExecutionEngine/JITLink/COFFLinkGraphBuilder.h create mode 100644 contrib/llvm-project/llvm/lib/ExecutionEngine/JITLink/COFF_x86_64.cpp create mode 100644 contrib/llvm-project/llvm/lib/Target/AArch64/AArch64SchedNeoverseN2.td create mode 100644 contrib/llvm-project/llvm/lib/Target/AMDGPU/GCNCreateVOPD.cpp create mode 100644 contrib/llvm-project/llvm/lib/Target/AMDGPU/GCNVOPDUtils.cpp create mode 100644 contrib/llvm-project/llvm/lib/Target/AMDGPU/GCNVOPDUtils.h create mode 100644 contrib/llvm-project/llvm/lib/Target/SPIRV/SPIRVDuplicatesTracker.cpp create mode 100644 contrib/llvm-project/llvm/lib/Target/SPIRV/SPIRVDuplicatesTracker.h create mode 100644 contrib/llvm-project/llvm/lib/Target/X86/X86ReturnThunks.cpp diff --git a/contrib/llvm-project/clang/include/clang/APINotes/Types.h b/contrib/llvm-project/clang/include/clang/APINotes/Types.h index d79586931995..0e5b43080e4b 100644 --- a/contrib/llvm-project/clang/include/clang/APINotes/Types.h +++ b/contrib/llvm-project/clang/include/clang/APINotes/Types.h @@ -76,7 +76,7 @@ public: } void setSwiftPrivate(llvm::Optional Private) { - SwiftPrivateSpecified = Private.hasValue(); + SwiftPrivateSpecified = Private.has_value(); SwiftPrivate = Private ? *Private : 0; } diff --git a/contrib/llvm-project/clang/include/clang/AST/ASTContext.h b/contrib/llvm-project/clang/include/clang/AST/ASTContext.h index 7db6af9cb87d..85eba45e4de6 100644 --- a/contrib/llvm-project/clang/include/clang/AST/ASTContext.h +++ b/contrib/llvm-project/clang/include/clang/AST/ASTContext.h @@ -130,6 +130,7 @@ class TemplateDecl; class TemplateParameterList; class TemplateTemplateParmDecl; class TemplateTypeParmDecl; +class TypeConstraint; class UnresolvedSetIterator; class UsingShadowDecl; class VarTemplateDecl; @@ -260,7 +261,7 @@ class ASTContext : public RefCountedBase { mutable llvm::FoldingSet DeducedTemplateSpecializationTypes; mutable llvm::FoldingSet AtomicTypes; - llvm::FoldingSet AttributedTypes; + mutable llvm::FoldingSet AttributedTypes; mutable llvm::FoldingSet PipeTypes; mutable llvm::FoldingSet BitIntTypes; mutable llvm::FoldingSet DependentBitIntTypes; @@ -1306,11 +1307,11 @@ public: /// declaration of a function with an exception specification is permitted /// and preserved. Other type sugar (for instance, typedefs) is not. QualType getFunctionTypeWithExceptionSpec( - QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI); + QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const; /// Determine whether two function types are the same, ignoring /// exception specifications in cases where they're part of the type. - bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U); + bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U) const; /// Change the exception specification on a function once it is /// delay-parsed, instantiated, or computed. @@ -1597,9 +1598,8 @@ public: QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const; - QualType getAttributedType(attr::Kind attrKind, - QualType modifiedType, - QualType equivalentType); + QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, + QualType equivalentType) const; QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr, QualType Wrapped); @@ -2654,25 +2654,33 @@ public: bool hasSameTemplateName(const TemplateName &X, const TemplateName &Y) const; /// Determine whether the two declarations refer to the same entity. - /// - /// FIXME: isSameEntity is not const due to its implementation calls - /// hasSameFunctionTypeIgnoringExceptionSpec which may alter this. - bool isSameEntity(const NamedDecl *X, const NamedDecl *Y); + bool isSameEntity(const NamedDecl *X, const NamedDecl *Y) const; /// Determine whether two template parameter lists are similar enough /// that they may be used in declarations of the same template. - /// - /// FIXME: isSameTemplateParameterList is not const since it calls - /// isSameTemplateParameter. bool isSameTemplateParameterList(const TemplateParameterList *X, - const TemplateParameterList *Y); + const TemplateParameterList *Y) const; /// Determine whether two template parameters are similar enough /// that they may be used in declarations of the same template. + bool isSameTemplateParameter(const NamedDecl *X, const NamedDecl *Y) const; + + /// Determine whether two 'requires' expressions are similar enough that they + /// may be used in re-declarations. /// - /// FIXME: isSameTemplateParameterList is not const since it calls - /// isSameEntity. - bool isSameTemplateParameter(const NamedDecl *X, const NamedDecl *Y); + /// Use of 'requires' isn't mandatory, works with constraints expressed in + /// other ways too. + bool isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const; + + /// Determine whether two type contraint are similar enough that they could + /// used in declarations of the same template. + bool isSameTypeConstraint(const TypeConstraint *XTC, + const TypeConstraint *YTC) const; + + /// Determine whether two default template arguments are similar enough + /// that they may be used in declarations of the same template. + bool isSameDefaultTemplateArgument(const NamedDecl *X, + const NamedDecl *Y) const; /// Retrieve the "canonical" template argument. /// diff --git a/contrib/llvm-project/clang/include/clang/AST/ASTImportError.h b/contrib/llvm-project/clang/include/clang/AST/ASTImportError.h index 405790b6ded3..728314ca0936 100644 --- a/contrib/llvm-project/clang/include/clang/AST/ASTImportError.h +++ b/contrib/llvm-project/clang/include/clang/AST/ASTImportError.h @@ -19,7 +19,6 @@ namespace clang { class ASTImportError : public llvm::ErrorInfo { - public: /// \brief Kind of error when importing an AST component. enum ErrorKind { diff --git a/contrib/llvm-project/clang/include/clang/AST/DeclTemplate.h b/contrib/llvm-project/clang/include/clang/AST/DeclTemplate.h index 3e4ccda73111..725bb0bced9c 100755 --- a/contrib/llvm-project/clang/include/clang/AST/DeclTemplate.h +++ b/contrib/llvm-project/clang/include/clang/AST/DeclTemplate.h @@ -15,6 +15,7 @@ #define LLVM_CLANG_AST_DECLTEMPLATE_H #include "clang/AST/ASTConcept.h" +#include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclBase.h" #include "clang/AST/DeclCXX.h" @@ -373,11 +374,19 @@ public: /// Set that the default argument was inherited from another parameter. void setInherited(const ASTContext &C, ParmDecl *InheritedFrom) { - assert(!isInherited() && "default argument already inherited"); InheritedFrom = getParmOwningDefaultArg(InheritedFrom); if (!isSet()) ValueOrInherited = InheritedFrom; - else + else if (auto *D = ValueOrInherited.template dyn_cast()) { + assert(C.isSameDefaultTemplateArgument(D, InheritedFrom)); + ValueOrInherited = + new (allocateDefaultArgStorageChain(C)) Chain{InheritedFrom, get()}; + } else if (auto *Inherited = + ValueOrInherited.template dyn_cast()) { + assert(C.isSameDefaultTemplateArgument(Inherited->PrevDeclWithDefaultArg, + InheritedFrom)); + Inherited->PrevDeclWithDefaultArg = InheritedFrom; + } else ValueOrInherited = new (allocateDefaultArgStorageChain(C)) Chain{InheritedFrom, ValueOrInherited.template get()}; } diff --git a/contrib/llvm-project/clang/include/clang/AST/PropertiesBase.td b/contrib/llvm-project/clang/include/clang/AST/PropertiesBase.td index 559f29edcf0f..ec310a459927 100644 --- a/contrib/llvm-project/clang/include/clang/AST/PropertiesBase.td +++ b/contrib/llvm-project/clang/include/clang/AST/PropertiesBase.td @@ -520,15 +520,15 @@ let Class = PropertyTypeCase in { if (hasBase) { if (isTypeInfo) { base = APValue::LValueBase::getTypeInfo( - TypeInfoLValue(typeInfo.getValue().getTypePtr()), type.getValue()); + TypeInfoLValue(typeInfo.value().getTypePtr()), type.value()); elemTy = base.getTypeInfoType(); } else if (isExpr) { - base = APValue::LValueBase(cast(stmt.getValue()), - callIndex.getValue(), version.getValue()); + base = APValue::LValueBase(cast(stmt.value()), + callIndex.value(), version.value()); elemTy = base.get()->getType(); } else { - base = APValue::LValueBase(cast(decl.getValue()), - callIndex.getValue(), version.getValue()); + base = APValue::LValueBase(cast(decl.value()), + callIndex.value(), version.value()); elemTy = base.get()->getType(); } } diff --git a/contrib/llvm-project/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h b/contrib/llvm-project/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h index c1100d8474aa..358ace0430f6 100644 --- a/contrib/llvm-project/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h +++ b/contrib/llvm-project/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h @@ -155,6 +155,7 @@ public: /// Returns a pointer value that represents a null pointer. Calls with /// `PointeeType` that are canonically equivalent will return the same result. + /// A null `PointeeType` can be used for the pointee of `std::nullptr_t`. PointerValue &getOrCreateNullPointerValue(QualType PointeeType); /// Returns a symbolic boolean value that models a boolean literal equal to @@ -251,6 +252,17 @@ public: bool equivalentBoolValues(BoolValue &Val1, BoolValue &Val2); private: + struct NullableQualTypeDenseMapInfo : private llvm::DenseMapInfo { + static QualType getEmptyKey() { + // Allow a NULL `QualType` by using a different value as the empty key. + return QualType::getFromOpaquePtr(reinterpret_cast(1)); + } + + using DenseMapInfo::getHashValue; + using DenseMapInfo::getTombstoneKey; + using DenseMapInfo::isEqual; + }; + /// Adds all constraints of the flow condition identified by `Token` and all /// of its transitive dependencies to `Constraints`. `VisitedTokens` is used /// to track tokens of flow conditions that were already visited by recursive @@ -259,17 +271,18 @@ private: AtomicBoolValue &Token, llvm::DenseSet &Constraints, llvm::DenseSet &VisitedTokens); - /// Returns the result of satisfiability checking on `Constraints`. - /// Possible return values are: - /// - `Satisfiable`: There exists a satisfying assignment for `Constraints`. - /// - `Unsatisfiable`: There is no satisfying assignment for `Constraints`. - /// - `TimedOut`: The solver gives up on finding a satisfying assignment. + /// Returns the outcome of satisfiability checking on `Constraints`. + /// Possible outcomes are: + /// - `Satisfiable`: A satisfying assignment exists and is returned. + /// - `Unsatisfiable`: A satisfying assignment does not exist. + /// - `TimedOut`: The search for a satisfying assignment was not completed. Solver::Result querySolver(llvm::DenseSet Constraints); /// Returns true if the solver is able to prove that there is no satisfying /// assignment for `Constraints` bool isUnsatisfiable(llvm::DenseSet Constraints) { - return querySolver(std::move(Constraints)) == Solver::Result::Unsatisfiable; + return querySolver(std::move(Constraints)).getStatus() == + Solver::Result::Status::Unsatisfiable; } /// Returns a boolean value as a result of substituting `Val` and its sub @@ -311,7 +324,8 @@ private: // required to initialize the `PointeeLoc` field in `PointerValue`. Consider // creating a type-independent `NullPointerValue` without a `PointeeLoc` // field. - llvm::DenseMap NullPointerVals; + llvm::DenseMap + NullPointerVals; AtomicBoolValue &TrueVal; AtomicBoolValue &FalseVal; diff --git a/contrib/llvm-project/clang/include/clang/Analysis/FlowSensitive/DebugSupport.h b/contrib/llvm-project/clang/include/clang/Analysis/FlowSensitive/DebugSupport.h new file mode 100644 index 000000000000..ef903d807e12 --- /dev/null +++ b/contrib/llvm-project/clang/include/clang/Analysis/FlowSensitive/DebugSupport.h @@ -0,0 +1,63 @@ +//===-- DebugSupport.h ------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file defines functions which generate more readable forms of data +// structures used in the dataflow analyses, for debugging purposes. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_DEBUGSUPPORT_H_ +#define LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_DEBUGSUPPORT_H_ + +#include +#include + +#include "clang/Analysis/FlowSensitive/Solver.h" +#include "clang/Analysis/FlowSensitive/Value.h" +#include "llvm/ADT/DenseMap.h" + +namespace clang { +namespace dataflow { +/// Returns a string representation for the boolean value `B`. +/// +/// Atomic booleans appearing in the boolean value `B` are assigned to labels +/// either specified in `AtomNames` or created by default rules as B0, B1, ... +/// +/// Requirements: +/// +/// Names assigned to atoms should not be repeated in `AtomNames`. +std::string debugString( + const BoolValue &B, + llvm::DenseMap AtomNames = {{}}); + +/// Returns a string representation for `Constraints` - a collection of boolean +/// formulas and the `Result` of satisfiability checking. +/// +/// Atomic booleans appearing in `Constraints` and `Result` are assigned to +/// labels either specified in `AtomNames` or created by default rules as B0, +/// B1, ... +/// +/// Requirements: +/// +/// Names assigned to atoms should not be repeated in `AtomNames`. +std::string debugString( + const std::vector &Constraints, const Solver::Result &Result, + llvm::DenseMap AtomNames = {{}}); +inline std::string debugString( + const llvm::DenseSet &Constraints, + const Solver::Result &Result, + llvm::DenseMap AtomNames = {{}}) { + std::vector ConstraintsVec(Constraints.begin(), + Constraints.end()); + return debugString(ConstraintsVec, Result, std::move(AtomNames)); +} + +} // namespace dataflow +} // namespace clang + +#endif // LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_DEBUGSUPPORT_H_ diff --git a/contrib/llvm-project/clang/include/clang/Analysis/FlowSensitive/Solver.h b/contrib/llvm-project/clang/include/clang/Analysis/FlowSensitive/Solver.h index 6b685b9b3c9a..93568b119793 100644 --- a/contrib/llvm-project/clang/include/clang/Analysis/FlowSensitive/Solver.h +++ b/contrib/llvm-project/clang/include/clang/Analysis/FlowSensitive/Solver.h @@ -15,7 +15,9 @@ #define LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_SOLVER_H #include "clang/Analysis/FlowSensitive/Value.h" +#include "llvm/ADT/DenseMap.h" #include "llvm/ADT/DenseSet.h" +#include "llvm/ADT/Optional.h" namespace clang { namespace dataflow { @@ -23,17 +25,58 @@ namespace dataflow { /// An interface for a SAT solver that can be used by dataflow analyses. class Solver { public: - enum class Result { - /// Indicates that there exists a satisfying assignment for a boolean + struct Result { + enum class Status { + /// Indicates that there exists a satisfying assignment for a boolean + /// formula. + Satisfiable, + + /// Indicates that there is no satisfying assignment for a boolean + /// formula. + Unsatisfiable, + + /// Indicates that the solver gave up trying to find a satisfying + /// assignment for a boolean formula. + TimedOut, + }; + + /// A boolean value is set to true or false in a truth assignment. + enum class Assignment : uint8_t { AssignedFalse = 0, AssignedTrue = 1 }; + + /// Constructs a result indicating that the queried boolean formula is + /// satisfiable. The result will hold a solution found by the solver. + static Result + Satisfiable(llvm::DenseMap Solution) { + return Result(Status::Satisfiable, std::move(Solution)); + } + + /// Constructs a result indicating that the queried boolean formula is + /// unsatisfiable. + static Result Unsatisfiable() { return Result(Status::Unsatisfiable, {}); } + + /// Constructs a result indicating that satisfiability checking on the + /// queried boolean formula was not completed. + static Result TimedOut() { return Result(Status::TimedOut, {}); } + + /// Returns the status of satisfiability checking on the queried boolean /// formula. - Satisfiable, + Status getStatus() const { return SATCheckStatus; } - /// Indicates that there is no satisfying assignment for a boolean formula. - Unsatisfiable, + /// Returns a truth assignment to boolean values that satisfies the queried + /// boolean formula if available. Otherwise, an empty optional is returned. + llvm::Optional> + getSolution() const { + return Solution; + } - /// Indicates that the solver gave up trying to find a satisfying assignment - /// for a boolean formula. - TimedOut, + private: + Result( + enum Status SATCheckStatus, + llvm::Optional> Solution) + : SATCheckStatus(SATCheckStatus), Solution(std::move(Solution)) {} + + Status SATCheckStatus; + llvm::Optional> Solution; }; virtual ~Solver() = default; @@ -44,9 +87,6 @@ public: /// Requirements: /// /// All elements in `Vals` must not be null. - /// - /// FIXME: Consider returning a model in case the conjunction of `Vals` is - /// satisfiable so that it can be used to generate warning messages. virtual Result solve(llvm::DenseSet Vals) = 0; }; diff --git a/contrib/llvm-project/clang/include/clang/Analysis/SelectorExtras.h b/contrib/llvm-project/clang/include/clang/Analysis/SelectorExtras.h index 278f20e87cc6..1e1daf5706bb 100644 --- a/contrib/llvm-project/clang/include/clang/Analysis/SelectorExtras.h +++ b/contrib/llvm-project/clang/include/clang/Analysis/SelectorExtras.h @@ -16,7 +16,7 @@ namespace clang { template static inline Selector getKeywordSelector(ASTContext &Ctx, IdentifierInfos *... IIs) { - static_assert(sizeof...(IdentifierInfos), + static_assert(sizeof...(IdentifierInfos) > 0, "keyword selectors must have at least one argument"); SmallVector II({&Ctx.Idents.get(IIs)...}); diff --git a/contrib/llvm-project/clang/include/clang/Basic/AlignedAllocation.h b/contrib/llvm-project/clang/include/clang/Basic/AlignedAllocation.h index c1187b81420b..949e54c8c030 100644 --- a/contrib/llvm-project/clang/include/clang/Basic/AlignedAllocation.h +++ b/contrib/llvm-project/clang/include/clang/Basic/AlignedAllocation.h @@ -26,8 +26,8 @@ inline llvm::VersionTuple alignedAllocMinVersion(llvm::Triple::OSType OS) { default: break; case llvm::Triple::Darwin: - case llvm::Triple::MacOSX: // Earliest supporting version is 10.14. - return llvm::VersionTuple(10U, 14U); + case llvm::Triple::MacOSX: // Earliest supporting version is 10.13. + return llvm::VersionTuple(10U, 13U); case llvm::Triple::IOS: case llvm::Triple::TvOS: // Earliest supporting version is 11.0.0. return llvm::VersionTuple(11U); diff --git a/contrib/llvm-project/clang/include/clang/Basic/Attr.td b/contrib/llvm-project/clang/include/clang/Basic/Attr.td index cb47215f7e1d..78e0fce917a0 100644 --- a/contrib/llvm-project/clang/include/clang/Basic/Attr.td +++ b/contrib/llvm-project/clang/include/clang/Basic/Attr.td @@ -4036,3 +4036,14 @@ def NoRandomizeLayout : InheritableAttr { let LangOpts = [COnly]; } def : MutualExclusions<[RandomizeLayout, NoRandomizeLayout]>; + +def FunctionReturnThunks : InheritableAttr, + TargetSpecificAttr { + let Spellings = [GCC<"function_return">]; + let Args = [EnumArgument<"ThunkType", "Kind", + ["keep", "thunk-extern"], + ["Keep", "Extern"] + >]; + let Subjects = SubjectList<[Function]>; + let Documentation = [FunctionReturnThunksDocs]; +} diff --git a/contrib/llvm-project/clang/include/clang/Basic/AttrDocs.td b/contrib/llvm-project/clang/include/clang/Basic/AttrDocs.td index 4e4d871a58a7..aff0dbbdd94d 100644 --- a/contrib/llvm-project/clang/include/clang/Basic/AttrDocs.td +++ b/contrib/llvm-project/clang/include/clang/Basic/AttrDocs.td @@ -3088,8 +3088,8 @@ def FormatDocs : Documentation { let Content = [{ Clang supports the ``format`` attribute, which indicates that the function -accepts a ``printf`` or ``scanf``-like format string and corresponding -arguments or a ``va_list`` that contains these arguments. +accepts (among other possibilities) a ``printf`` or ``scanf``-like format string +and corresponding arguments or a ``va_list`` that contains these arguments. Please see `GCC documentation about format attribute `_ to find details @@ -3143,6 +3143,27 @@ Clang implements two kinds of checks with this attribute. In this case Clang does not warn because the format string ``s`` and the corresponding arguments are annotated. If the arguments are incorrect, the caller of ``foo`` will receive a warning. + +As an extension to GCC's behavior, Clang accepts the ``format`` attribute on +non-variadic functions. Clang checks non-variadic format functions for the same +classes of issues that can be found on variadic functions, as controlled by the +same warning flags, except that the types of formatted arguments is forced by +the function signature. For example: + +.. code-block:: c + + __attribute__((__format__(__printf__, 1, 2))) + void fmt(const char *s, const char *a, int b); + + void bar(void) { + fmt("%s %i", "hello", 123); // OK + fmt("%i %g", "hello", 123); // warning: arguments don't match format + extern const char *fmt; + fmt(fmt, "hello", 123); // warning: format string is not a string literal + } + +Using the ``format`` attribute on a non-variadic function emits a GCC +compatibility diagnostic. }]; } @@ -6585,6 +6606,28 @@ evaluate to NULL. } return 0; } + }]; +} + +def FunctionReturnThunksDocs : Documentation { + let Category = DocCatFunction; + let Content = [{ +The attribute ``function_return`` can replace return instructions with jumps to +target-specific symbols. This attribute supports 2 possible values, +corresponding to the values supported by the ``-mfunction-return=`` command +line flag: + +* ``__attribute__((function_return("keep")))`` to disable related transforms. + This is useful for undoing global setting from ``-mfunction-return=`` locally + for individual functions. +* ``__attribute__((function_return("thunk-extern")))`` to replace returns with + jumps, while NOT emitting the thunk. + +The values ``thunk`` and ``thunk-inline`` from GCC are not supported. + +The symbol used for ``thunk-extern`` is target specific: +* X86: ``__x86_return_thunk`` +As such, this function attribute is currently only supported on X86 targets. }]; } diff --git a/contrib/llvm-project/clang/include/clang/Basic/BuiltinsX86.def b/contrib/llvm-project/clang/include/clang/Basic/BuiltinsX86.def index 3e5c376f9bc1..6bf35c340c2d 100644 --- a/contrib/llvm-project/clang/include/clang/Basic/BuiltinsX86.def +++ b/contrib/llvm-project/clang/include/clang/Basic/BuiltinsX86.def @@ -825,6 +825,7 @@ BUILTIN(__rdtsc, "UOi", "") BUILTIN(__builtin_ia32_rdtscp, "UOiUi*", "") TARGET_BUILTIN(__builtin_ia32_rdpid, "Ui", "n", "rdpid") +TARGET_BUILTIN(__builtin_ia32_rdpru, "ULLii", "n", "rdpru") // PKU TARGET_BUILTIN(__builtin_ia32_rdpkru, "Ui", "n", "pku") diff --git a/contrib/llvm-project/clang/include/clang/Basic/CodeGenOptions.def b/contrib/llvm-project/clang/include/clang/Basic/CodeGenOptions.def index 72b0e5d8eb41..b1d394edd04a 100644 --- a/contrib/llvm-project/clang/include/clang/Basic/CodeGenOptions.def +++ b/contrib/llvm-project/clang/include/clang/Basic/CodeGenOptions.def @@ -107,6 +107,7 @@ CODEGENOPT(CFProtectionReturn , 1, 0) ///< if -fcf-protection is CODEGENOPT(CFProtectionBranch , 1, 0) ///< if -fcf-protection is ///< set to full or branch. CODEGENOPT(IBTSeal, 1, 0) ///< set to optimize CFProtectionBranch. +CODEGENOPT(FunctionReturnThunks, 1, 0) ///< -mfunction-return={keep|thunk-extern} CODEGENOPT(XRayInstrumentFunctions , 1, 0) ///< Set when -fxray-instrument is ///< enabled. diff --git a/contrib/llvm-project/clang/include/clang/Basic/CodeGenOptions.h b/contrib/llvm-project/clang/include/clang/Basic/CodeGenOptions.h index 23d76c308d84..cd204e5d7c15 100644 --- a/contrib/llvm-project/clang/include/clang/Basic/CodeGenOptions.h +++ b/contrib/llvm-project/clang/include/clang/Basic/CodeGenOptions.h @@ -389,6 +389,9 @@ public: /// On AArch64 this can only be "sp_el0". std::string StackProtectorGuardReg; + /// Specify a symbol to be the guard value. + std::string StackProtectorGuardSymbol; + /// Path to ignorelist file specifying which objects /// (files, functions) listed for instrumentation by sanitizer /// coverage pass should actually not be instrumented. diff --git a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticDriverKinds.td b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticDriverKinds.td index 96219f83b0a5..68685baf7633 100644 --- a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticDriverKinds.td +++ b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticDriverKinds.td @@ -60,8 +60,6 @@ def err_drv_no_cuda_libdevice : Error< "cannot find libdevice for %0; provide path to different CUDA installation " "via '--cuda-path', or pass '-nocudalib' to build without linking with " "libdevice">; -def err_drv_no_rdc_new_driver : Error< - "Using '--offload-new-driver' requires '-fgpu-rdc'">; def err_drv_no_rocm_device_lib : Error< "cannot find ROCm device library%select{| for %1|for ABI version %1}0; provide its path via " diff --git a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticGroups.td b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticGroups.td index 10da02ecbf7e..53e246a39ed8 100644 --- a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticGroups.td +++ b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticGroups.td @@ -31,6 +31,7 @@ def GNUAnonymousStruct : DiagGroup<"gnu-anonymous-struct">; def GNUAutoType : DiagGroup<"gnu-auto-type">; def ArrayBounds : DiagGroup<"array-bounds">; def ArrayBoundsPointerArithmetic : DiagGroup<"array-bounds-pointer-arithmetic">; +def ArrayParameter : DiagGroup<"array-parameter">; def AutoDisableVptrSanitizer : DiagGroup<"auto-disable-vptr-sanitizer">; def Availability : DiagGroup<"availability">; def Section : DiagGroup<"section">; @@ -187,6 +188,7 @@ def UnguardedAvailability : DiagGroup<"unguarded-availability", def : DiagGroup<"partial-availability", [UnguardedAvailability]>; def DeprecatedDynamicExceptionSpec : DiagGroup<"deprecated-dynamic-exception-spec">; +def DeprecatedBuiltins : DiagGroup<"deprecated-builtins">; def DeprecatedImplementations :DiagGroup<"deprecated-implementations">; def DeprecatedIncrementBool : DiagGroup<"deprecated-increment-bool">; def DeprecatedRegister : DiagGroup<"deprecated-register">; @@ -209,6 +211,7 @@ def Deprecated : DiagGroup<"deprecated", [DeprecatedAnonEnumEnumConversion, DeprecatedEnumCompareConditional, DeprecatedEnumEnumConversion, DeprecatedEnumFloatConversion, + DeprecatedBuiltins, DeprecatedIncrementBool, DeprecatedPragma, DeprecatedRegister, @@ -978,6 +981,7 @@ def Extra : DiagGroup<"extra", [ ]>; def Most : DiagGroup<"most", [ + ArrayParameter, BoolOperation, CharSubscript, Comment, diff --git a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticLexKinds.td b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticLexKinds.td index ac86076140c5..dd0909704492 100644 --- a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticLexKinds.td +++ b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticLexKinds.td @@ -113,6 +113,8 @@ def warn_four_char_character_literal : Warning< // Unicode and UCNs def err_invalid_utf8 : Error< "source file is not valid UTF-8">; +def warn_invalid_utf8_in_comment : Extension< + "invalid UTF-8 in comment">, InGroup>; def err_character_not_allowed : Error< "unexpected character ">; def err_character_not_allowed_identifier : Error< @@ -128,8 +130,15 @@ def warn_utf8_symbol_zero_width : Warning< "some environments">, InGroup>; def ext_delimited_escape_sequence : Extension< - "%select{delimited|named}0 escape sequences are a Clang extension">, + "%select{delimited|named}0 escape sequences are a " + "%select{Clang|C++2b}1 extension">, InGroup>; + +def warn_cxx2b_delimited_escape_sequence : Warning< + "%select{delimited|named}0 escape sequences are " + "incompatible with C++ standards before C++2b">, + InGroup, DefaultIgnore; + def err_delimited_escape_empty : Error< "delimited escape sequence cannot be empty">; def err_delimited_escape_missing_brace: Error< diff --git a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticSemaKinds.td b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticSemaKinds.td index bc7aec3803e8..550029f58b54 100644 --- a/contrib/llvm-project/clang/include/clang/Basic/DiagnosticSemaKinds.td +++ b/contrib/llvm-project/clang/include/clang/Basic/DiagnosticSemaKinds.td @@ -3115,8 +3115,6 @@ def note_ownership_returns_index_mismatch : Note< "declared with index %0 here">; def err_format_strftime_third_parameter : Error< "strftime format attribute requires 3rd parameter to be 0">; -def err_format_attribute_requires_variadic : Error< - "format attribute requires variadic function">; def err_format_attribute_not : Error<"format argument not a string type">; def err_format_attribute_result_not : Error<"function does not return %0">; def err_format_attribute_implicit_this_format_string : Error< @@ -3343,10 +3341,11 @@ def warn_assume_aligned_too_great "alignment assumed">, InGroup>; def warn_not_xl_compatible - : Warning<"requesting an alignment of 16 bytes or greater for struct" - " members is not binary compatible with IBM XL C/C++ for AIX" - " 16.1.0 and older">, + : Warning<"alignment of 16 bytes for a struct member is not binary " + "compatible with IBM XL C/C++ for AIX 16.1.0 or older">, InGroup; +def note_misaligned_member_used_here : Note< + "passing byval argument %0 with potentially incompatible alignment here">; def warn_redeclaration_without_attribute_prev_attribute_ignored : Warning< "%q0 redeclared without %1 attribute: previous %1 ignored">, InGroup; @@ -4127,6 +4126,9 @@ def err_attribute_not_supported_on_arch def warn_gcc_ignores_type_attr : Warning< "GCC does not allow the %0 attribute to be written on a type">, InGroup; +def warn_gcc_requires_variadic_function : Warning< + "GCC requires a function with the %0 attribute to be variadic">, + InGroup; // Clang-Specific Attributes def warn_attribute_iboutlet : Warning< @@ -4829,8 +4831,12 @@ def warn_cxx14_compat_template_nontype_parm_auto_type : Warning< DefaultIgnore, InGroup; def err_template_param_default_arg_redefinition : Error< "template parameter redefines default argument">; +def err_template_param_default_arg_inconsistent_redefinition : Error< + "template parameter default argument is inconsistent with previous definition">; def note_template_param_prev_default_arg : Note< "previous default template argument defined here">; +def note_template_param_prev_default_arg_in_other_module : Note< + "previous default template argument defined in module %0">; def err_template_param_default_arg_missing : Error< "template parameter missing a default argument">; def ext_template_parameter_default_in_function_template : ExtWarn< @@ -5557,6 +5563,9 @@ def warn_deprecated_def : Warning< def warn_unavailable_def : Warning< "implementing unavailable method">, InGroup, DefaultIgnore; +def warn_deprecated_builtin : Warning< + "builtin %0 is deprecated; use %1 instead">, + InGroup; def err_unavailable : Error<"%0 is unavailable">; def err_property_method_unavailable : Error<"property access is using %0 method which is unavailable">; @@ -6605,13 +6614,16 @@ def warn_addition_in_bitshift : Warning< "'%1' will be evaluated first">, InGroup; def warn_self_assignment_builtin : Warning< - "explicitly assigning value of variable of type %0 to itself">, + "explicitly assigning value of variable of type %0 to itself%select{|; did " + "you mean to assign to member %2?}1">, InGroup, DefaultIgnore; def warn_self_assignment_overloaded : Warning< - "explicitly assigning value of variable of type %0 to itself">, + "explicitly assigning value of variable of type %0 to itself%select{|; did " + "you mean to assign to member %2?}1">, InGroup, DefaultIgnore; def warn_self_move : Warning< - "explicitly moving variable of type %0 to itself">, + "explicitly moving variable of type %0 to itself%select{|; did you mean to " + "move to member %2?}1">, InGroup, DefaultIgnore; def err_builtin_move_forward_unsupported : Error< @@ -9395,6 +9407,12 @@ def warn_array_index_exceeds_max_addressable_bounds : Warning< def note_array_declared_here : Note< "array %0 declared here">; +def warn_inconsistent_array_form : Warning< + "argument %0 of type %1 with mismatched bound">, + InGroup, DefaultIgnore; +def note_previous_declaration_as : Note< + "previously declared as %0 here">; + def warn_printf_insufficient_data_args : Warning< "more '%%' conversions than data arguments">, InGroup; def warn_printf_data_arg_not_used : Warning< diff --git a/contrib/llvm-project/clang/include/clang/Basic/MakeSupport.h b/contrib/llvm-project/clang/include/clang/Basic/MakeSupport.h new file mode 100644 index 000000000000..c663014ba7bc --- /dev/null +++ b/contrib/llvm-project/clang/include/clang/Basic/MakeSupport.h @@ -0,0 +1,23 @@ +//===- MakeSupport.h - Make Utilities ---------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_BASIC_MAKESUPPORT_H +#define LLVM_CLANG_BASIC_MAKESUPPORT_H + +#include "clang/Basic/LLVM.h" +#include "llvm/ADT/StringRef.h" + +namespace clang { + +/// Quote target names for inclusion in GNU Make dependency files. +/// Only the characters '$', '#', ' ', '\t' are quoted. +void quoteMakeTarget(StringRef Target, SmallVectorImpl &Res); + +} // namespace clang + +#endif // LLVM_CLANG_BASIC_MAKESUPPORT_H diff --git a/contrib/llvm-project/clang/include/clang/Basic/TargetInfo.h b/contrib/llvm-project/clang/include/clang/Basic/TargetInfo.h index 0ab3e9b67dfe..b4f3a69259fa 100644 --- a/contrib/llvm-project/clang/include/clang/Basic/TargetInfo.h +++ b/contrib/llvm-project/clang/include/clang/Basic/TargetInfo.h @@ -222,9 +222,7 @@ protected: mutable VersionTuple PlatformMinVersion; unsigned HasAlignMac68kSupport : 1; - unsigned RealTypeUsesObjCFPRetMask - : llvm::BitmaskEnumDetail::bitWidth( - (int)FloatModeKind::LLVM_BITMASK_LARGEST_ENUMERATOR); + unsigned RealTypeUsesObjCFPRetMask : llvm::BitWidth; unsigned ComplexLongDoubleUsesFP2Ret : 1; unsigned HasBuiltinMSVaList : 1; @@ -893,7 +891,7 @@ public: /// Check whether the given real type should use the "fpret" flavor of /// Objective-C message passing on this target. bool useObjCFPRetForRealType(FloatModeKind T) const { - return RealTypeUsesObjCFPRetMask & llvm::BitmaskEnumDetail::Underlying(T); + return (int)((FloatModeKind)RealTypeUsesObjCFPRetMask & T); } /// Check whether _Complex long double should use the "fp2ret" flavor diff --git a/contrib/llvm-project/clang/include/clang/Basic/riscv_vector.td b/contrib/llvm-project/clang/include/clang/Basic/riscv_vector.td index b11b780ec1f7..d96020ee40d0 100644 --- a/contrib/llvm-project/clang/include/clang/Basic/riscv_vector.td +++ b/contrib/llvm-project/clang/include/clang/Basic/riscv_vector.td @@ -582,18 +582,8 @@ class IsFloat { } let HasUnMaskedOverloaded = false, - MaskedPolicy = NonePolicy, - ManualCodegen = [{ - IntrinsicTypes = {ResultType, Ops[1]->getType()}; - Ops[0] = Builder.CreateBitCast(Ops[0], ResultType->getPointerTo()); - }], - MaskedManualCodegen= [{ - // Move mask to right before vl. - std::rotate(Ops.begin(), Ops.begin() + 1, Ops.end() - 1); - IntrinsicTypes = {ResultType, Ops[3]->getType()}; - Ops[1] = Builder.CreateBitCast(Ops[1], ResultType->getPointerTo()); - }] in { - class RVVVLEMaskBuiltin : RVVBuiltin<"m", "mPCUe", "c"> { + MaskedPolicy = NonePolicy in { + class RVVVLEMaskBuiltin : RVVOutBuiltin<"m", "mPCUe", "c"> { let Name = "vlm_v"; let IRName = "vlm"; let HasMasked = false; @@ -601,26 +591,15 @@ let HasUnMaskedOverloaded = false, } let HasUnMaskedOverloaded = false, - ManualCodegen = [{ - IntrinsicTypes = {ResultType, Ops[1]->getType()}; - Ops[0] = Builder.CreateBitCast(Ops[0], ResultType->getPointerTo()); - Ops.insert(Ops.begin(), llvm::UndefValue::get(ResultType)); - }], - MaskedManualCodegen= [{ - // Move mask to right before vl. - std::rotate(Ops.begin(), Ops.begin() + 1, Ops.end() - 1); - Ops.push_back(ConstantInt::get(Ops.back()->getType(), TAIL_UNDISTURBED)); - IntrinsicTypes = {ResultType, Ops[3]->getType()}; - Ops[1] = Builder.CreateBitCast(Ops[1], ResultType->getPointerTo()); - }] in { + UnMaskedPolicy = HasPassthruOperand in { multiclass RVVVLEBuiltin types> { let Name = NAME # "_v", IRName = "vle", MaskedIRName ="vle_mask" in { foreach type = types in { - def : RVVBuiltin<"v", "vPCe", type>; + def : RVVOutBuiltin<"v", "vPCe", type>; if !not(IsFloat.val) then { - def : RVVBuiltin<"Uv", "UvPCUe", type>; + def : RVVOutBuiltin<"Uv", "UvPCUe", type>; } } } @@ -685,61 +664,39 @@ multiclass RVVVLSEBuiltin types> { IRName = "vlse", MaskedIRName ="vlse_mask", HasUnMaskedOverloaded = false, - ManualCodegen = [{ - IntrinsicTypes = {ResultType, Ops[2]->getType()}; - Ops[0] = Builder.CreateBitCast(Ops[0], ResultType->getPointerTo()); - Ops.insert(Ops.begin(), llvm::UndefValue::get(ResultType)); - }], - MaskedManualCodegen= [{ - // Move mask to right before vl. - std::rotate(Ops.begin(), Ops.begin() + 1, Ops.end() - 1); - Ops.push_back(ConstantInt::get(Ops.back()->getType(), TAIL_UNDISTURBED)); - IntrinsicTypes = {ResultType, Ops[4]->getType()}; - Ops[1] = Builder.CreateBitCast(Ops[1], ResultType->getPointerTo()); - }] in { + UnMaskedPolicy = HasPassthruOperand in { foreach type = types in { - def : RVVBuiltin<"v", "vPCet", type>; + def : RVVOutBuiltin<"v", "vPCet", type>; if !not(IsFloat.val) then { - def : RVVBuiltin<"Uv", "UvPCUet", type>; + def : RVVOutBuiltin<"Uv", "UvPCUet", type>; } } } } multiclass RVVIndexedLoad { - let ManualCodegen = [{ - IntrinsicTypes = {ResultType, Ops[1]->getType(), Ops[2]->getType()}; - Ops[0] = Builder.CreateBitCast(Ops[0], ResultType->getPointerTo()); - Ops.insert(Ops.begin(), llvm::UndefValue::get(ResultType)); - }], - MaskedManualCodegen = [{ - // Move mask to right before vl. - std::rotate(Ops.begin(), Ops.begin() + 1, Ops.end() - 1); - Ops.push_back(ConstantInt::get(Ops.back()->getType(), TAIL_UNDISTURBED)); - IntrinsicTypes = {ResultType, Ops[2]->getType(), Ops[4]->getType()}; - Ops[1] = Builder.CreateBitCast(Ops[1], ResultType->getPointerTo()); - }] in { - foreach type = TypeList in { - foreach eew_list = EEWList[0-2] in { - defvar eew = eew_list[0]; - defvar eew_type = eew_list[1]; - let Name = op # eew # "_v", IRName = op, MaskedIRName = op # "_mask" in { - def: RVVBuiltin<"v", "vPCe" # eew_type # "Uv", type>; - if !not(IsFloat.val) then { - def: RVVBuiltin<"Uv", "UvPCUe" # eew_type # "Uv", type>; - } - } + let UnMaskedPolicy = HasPassthruOperand in { + foreach type = TypeList in { + foreach eew_list = EEWList[0-2] in { + defvar eew = eew_list[0]; + defvar eew_type = eew_list[1]; + let Name = op # eew # "_v", IRName = op, MaskedIRName = op # "_mask" in { + def: RVVOutOp1Builtin<"v", "vPCe" # eew_type # "Uv", type>; + if !not(IsFloat.val) then { + def: RVVOutOp1Builtin<"Uv", "UvPCUe" # eew_type # "Uv", type>; + } } - defvar eew64 = "64"; - defvar eew64_type = "(Log2EEW:6)"; - let Name = op # eew64 # "_v", IRName = op, MaskedIRName = op # "_mask", - RequiredFeatures = ["RV64"] in { - def: RVVBuiltin<"v", "vPCe" # eew64_type # "Uv", type>; - if !not(IsFloat.val) then { - def: RVVBuiltin<"Uv", "UvPCUe" # eew64_type # "Uv", type>; - } - } } + defvar eew64 = "64"; + defvar eew64_type = "(Log2EEW:6)"; + let Name = op # eew64 # "_v", IRName = op, MaskedIRName = op # "_mask", + RequiredFeatures = ["RV64"] in { + def: RVVOutOp1Builtin<"v", "vPCe" # eew64_type # "Uv", type>; + if !not(IsFloat.val) then { + def: RVVOutOp1Builtin<"Uv", "UvPCUe" # eew64_type # "Uv", type>; + } + } + } } } diff --git a/contrib/llvm-project/clang/include/clang/Driver/Options.td b/contrib/llvm-project/clang/include/clang/Driver/Options.td index f4fe08aa1a5b..532d7780c529 100644 --- a/contrib/llvm-project/clang/include/clang/Driver/Options.td +++ b/contrib/llvm-project/clang/include/clang/Driver/Options.td @@ -1998,6 +1998,13 @@ def fcf_protection : Flag<["-"], "fcf-protection">, Group, Flags<[CoreO HelpText<"Enable cf-protection in 'full' mode">; def mibt_seal : Flag<["-"], "mibt-seal">, Group, Flags<[CoreOption, CC1Option]>, HelpText<"Optimize fcf-protection=branch/full (requires LTO).">; +def mfunction_return_EQ : Joined<["-"], "mfunction-return=">, + Group, Flags<[CoreOption, CC1Option]>, + HelpText<"Replace returns with jumps to ``__x86_return_thunk`` (x86 only, error otherwise)">, + Values<"keep,thunk-extern">, + NormalizedValues<["Keep", "Extern"]>, + NormalizedValuesScope<"llvm::FunctionReturnThunksKind">, + MarshallingInfoEnum, "Keep">; defm xray_instrument : BoolFOption<"xray-instrument", LangOpts<"XRayInstrument">, DefaultFalse, @@ -3338,11 +3345,12 @@ def mhwmult_EQ : Joined<["-"], "mhwmult=">, Group; def mglobal_merge : Flag<["-"], "mglobal-merge">, Group, Flags<[CC1Option]>, HelpText<"Enable merging of globals">; def mhard_float : Flag<["-"], "mhard-float">, Group; -def miphoneos_version_min_EQ : Joined<["-"], "miphoneos-version-min=">, Group; def mios_version_min_EQ : Joined<["-"], "mios-version-min=">, - Alias, HelpText<"Set iOS deployment target">; + Group, HelpText<"Set iOS deployment target">; +def : Joined<["-"], "miphoneos-version-min=">, + Group, Alias; def mios_simulator_version_min_EQ : Joined<["-"], "mios-simulator-version-min=">; -def miphonesimulator_version_min_EQ : Joined<["-"], "miphonesimulator-version-min=">, Alias; +def : Joined<["-"], "miphonesimulator-version-min=">, Alias; def mkernel : Flag<["-"], "mkernel">, Group; def mlinker_version_EQ : Joined<["-"], "mlinker-version=">, Flags<[NoXarchOption]>; @@ -3354,10 +3362,10 @@ def mmlir : Separate<["-"], "mmlir">, Flags<[CoreOption,FC1Option,FlangOption]>, def ffuchsia_api_level_EQ : Joined<["-"], "ffuchsia-api-level=">, Group, Flags<[CC1Option]>, HelpText<"Set Fuchsia API level">, MarshallingInfoInt>; -def mmacosx_version_min_EQ : Joined<["-"], "mmacosx-version-min=">, - Group, HelpText<"Set Mac OS X deployment target">; def mmacos_version_min_EQ : Joined<["-"], "mmacos-version-min=">, - Group, Alias; + Group, HelpText<"Set macOS deployment target">; +def : Joined<["-"], "mmacosx-version-min=">, + Group, Alias; def mms_bitfields : Flag<["-"], "mms-bitfields">, Group, Flags<[CC1Option]>, HelpText<"Set the default structure layout to be compatible with the Microsoft compiler standard">, MarshallingInfoFlag>; @@ -3771,6 +3779,9 @@ def mstack_protector_guard_EQ : Joined<["-"], "mstack-protector-guard=">, Group< def mstack_protector_guard_offset_EQ : Joined<["-"], "mstack-protector-guard-offset=">, Group, Flags<[CC1Option]>, HelpText<"Use the given offset for addressing the stack-protector guard">, MarshallingInfoInt, "INT_MAX", "int">; +def mstack_protector_guard_symbol_EQ : Joined<["-"], "mstack-protector-guard-symbol=">, Group, Flags<[CC1Option]>, + HelpText<"Use the given symbol for addressing the stack-protector guard">, + MarshallingInfoString>; def mstack_protector_guard_reg_EQ : Joined<["-"], "mstack-protector-guard-reg=">, Group, Flags<[CC1Option]>, HelpText<"Use the given reg for addressing the stack-protector guard">, MarshallingInfoString>; @@ -3939,7 +3950,7 @@ def module_file_info : Flag<["-"], "module-file-info">, Flags<[NoXarchOption,CC1 HelpText<"Provide information about a particular module file">; def mthumb : Flag<["-"], "mthumb">, Group; def mtune_EQ : Joined<["-"], "mtune=">, Group, - HelpText<"Only supported on X86 and RISC-V. Otherwise accepted for compatibility with GCC.">; + HelpText<"Only supported on X86, RISC-V and SystemZ. Otherwise accepted for compatibility with GCC.">; def multi__module : Flag<["-"], "multi_module">; def multiply__defined__unused : Separate<["-"], "multiply_defined_unused">; def multiply__defined : Separate<["-"], "multiply_defined">; @@ -4570,6 +4581,8 @@ def mptwrite : Flag<["-"], "mptwrite">, Group; def mno_ptwrite : Flag<["-"], "mno-ptwrite">, Group; def mrdpid : Flag<["-"], "mrdpid">, Group; def mno_rdpid : Flag<["-"], "mno-rdpid">, Group; +def mrdpru : Flag<["-"], "mrdpru">, Group; +def mno_rdpru : Flag<["-"], "mno-rdpru">, Group; def mrdrnd : Flag<["-"], "mrdrnd">, Group; def mno_rdrnd : Flag<["-"], "mno-rdrnd">, Group; def mrtm : Flag<["-"], "mrtm">, Group; diff --git a/contrib/llvm-project/clang/include/clang/Frontend/FrontendActions.h b/contrib/llvm-project/clang/include/clang/Frontend/FrontendActions.h index ae829d741152..fe399850bd44 100644 --- a/contrib/llvm-project/clang/include/clang/Frontend/FrontendActions.h +++ b/contrib/llvm-project/clang/include/clang/Frontend/FrontendActions.h @@ -190,6 +190,10 @@ public: /// Dump information about the given module file, to be used for /// basic debugging and discovery. class DumpModuleInfoAction : public ASTFrontendAction { +public: + // Allow other tools (ex lldb) to direct output for their use. + llvm::raw_ostream *OutputStream = nullptr; + protected: std::unique_ptr CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override; diff --git a/contrib/llvm-project/clang/include/clang/Lex/Preprocessor.h b/contrib/llvm-project/clang/include/clang/Lex/Preprocessor.h index d130aba3ee3a..8fc24c731035 100644 --- a/contrib/llvm-project/clang/include/clang/Lex/Preprocessor.h +++ b/contrib/llvm-project/clang/include/clang/Lex/Preprocessor.h @@ -385,6 +385,7 @@ private: bool atTopLevel() { return S <= 0; } bool afterImportSeq() { return S == AfterImportSeq; } + bool afterTopLevelSeq() { return S == AfterTopLevelTokenSeq; } private: State S; @@ -397,6 +398,67 @@ private: /// Our current position within a C++20 import-seq. ImportSeq ImportSeqState = ImportSeq::AfterTopLevelTokenSeq; + /// Track whether we are in a Global Module Fragment + class TrackGMF { + public: + enum GMFState : int { + GMFActive = 1, + MaybeGMF = 0, + BeforeGMFIntroducer = -1, + GMFAbsentOrEnded = -2, + }; + + TrackGMF(GMFState S) : S(S) {} + + /// Saw a semicolon. + void handleSemi() { + // If it is immediately after the first instance of the module keyword, + // then that introduces the GMF. + if (S == MaybeGMF) + S = GMFActive; + } + + /// Saw an 'export' identifier. + void handleExport() { + // The presence of an 'export' keyword always ends or excludes a GMF. + S = GMFAbsentOrEnded; + } + + /// Saw an 'import' identifier. + void handleImport(bool AfterTopLevelTokenSeq) { + // If we see this before any 'module' kw, then we have no GMF. + if (AfterTopLevelTokenSeq && S == BeforeGMFIntroducer) + S = GMFAbsentOrEnded; + } + + /// Saw a 'module' identifier. + void handleModule(bool AfterTopLevelTokenSeq) { + // This was the first module identifier and not preceded by any token + // that would exclude a GMF. It could begin a GMF, but only if directly + // followed by a semicolon. + if (AfterTopLevelTokenSeq && S == BeforeGMFIntroducer) + S = MaybeGMF; + else + S = GMFAbsentOrEnded; + } + + /// Saw any other token. + void handleMisc() { + // We saw something other than ; after the 'module' kw, so not a GMF. + if (S == MaybeGMF) + S = GMFAbsentOrEnded; + } + + bool inGMF() { return S == GMFActive; } + + private: + /// Track the transitions into and out of a Global Module Fragment, + /// if one is present. + GMFState S; + }; + + TrackGMF TrackGMFState = TrackGMF::BeforeGMFIntroducer; + /// Whether the module import expects an identifier next. Otherwise, /// it expects a '.' or ';'. bool ModuleImportExpectsIdentifier = false; @@ -2414,6 +2476,7 @@ private: None, ModuleBegin, ModuleImport, + HeaderUnitImport, SkippedModuleImport, Failure, } Kind; diff --git a/contrib/llvm-project/clang/include/clang/Sema/HLSLExternalSemaSource.h b/contrib/llvm-project/clang/include/clang/Sema/HLSLExternalSemaSource.h new file mode 100644 index 000000000000..439fc3d10f33 --- /dev/null +++ b/contrib/llvm-project/clang/include/clang/Sema/HLSLExternalSemaSource.h @@ -0,0 +1,41 @@ +//===--- HLSLExternalSemaSource.h - HLSL Sema Source ------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file defines the HLSLExternalSemaSource interface. +// +//===----------------------------------------------------------------------===// +#ifndef CLANG_SEMA_HLSLEXTERNALSEMASOURCE_H +#define CLANG_SEMA_HLSLEXTERNALSEMASOURCE_H + +#include "clang/Sema/ExternalSemaSource.h" + +namespace clang { +class NamespaceDecl; +class Sema; + +class HLSLExternalSemaSource : public ExternalSemaSource { + Sema *SemaPtr = nullptr; + NamespaceDecl *HLSLNamespace; + + void defineHLSLVectorAlias(); + +public: + ~HLSLExternalSemaSource() override; + + /// Initialize the semantic source with the Sema instance + /// being used to perform semantic analysis on the abstract syntax + /// tree. + void InitializeSema(Sema &S) override; + + /// Inform the semantic consumer that Sema is no longer available. + void ForgetSema() override { SemaPtr = nullptr; } +}; + +} // namespace clang + +#endif // CLANG_SEMA_HLSLEXTERNALSEMASOURCE_H diff --git a/contrib/llvm-project/clang/include/clang/Sema/Sema.h b/contrib/llvm-project/clang/include/clang/Sema/Sema.h index ac241cf0515d..e51b9daef7d3 100644 --- a/contrib/llvm-project/clang/include/clang/Sema/Sema.h +++ b/contrib/llvm-project/clang/include/clang/Sema/Sema.h @@ -2272,6 +2272,9 @@ private: bool isAcceptableSlow(const NamedDecl *D, AcceptableKind Kind); + // Determine whether the module M belongs to the current TU. + bool isModuleUnitOfCurrentTU(const Module *M) const; + public: /// Get the module unit whose scope we are currently within. Module *getCurrentModule() const { @@ -5167,6 +5170,11 @@ public: void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc); + /// Returns a field in a CXXRecordDecl that has the same name as the decl \p + /// SelfAssigned when inside a CXXMethodDecl. + const FieldDecl * + getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned); + /// Warn if we're implicitly casting from a _Nullable pointer type to a /// _Nonnull one. void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, @@ -12997,21 +13005,29 @@ public: SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, unsigned ByteNo) const; -private: - void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, - const ArraySubscriptExpr *ASE=nullptr, - bool AllowOnePastEnd=true, bool IndexNegated=false); - void CheckArrayAccess(const Expr *E); + enum FormatArgumentPassingKind { + FAPK_Fixed, // values to format are fixed (no C-style variadic arguments) + FAPK_Variadic, // values to format are passed as variadic arguments + FAPK_VAList, // values to format are passed in a va_list + }; + // Used to grab the relevant information from a FormatAttr and a // FunctionDeclaration. struct FormatStringInfo { unsigned FormatIdx; unsigned FirstDataArg; - bool HasVAListArg; + FormatArgumentPassingKind ArgPassingKind; }; static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, - FormatStringInfo *FSI); + bool IsVariadic, FormatStringInfo *FSI); + +private: + void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, + const ArraySubscriptExpr *ASE = nullptr, + bool AllowOnePastEnd = true, bool IndexNegated = false); + void CheckArrayAccess(const Expr *E); + bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, const FunctionProtoType *Proto); bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc, @@ -13023,6 +13039,8 @@ private: ArrayRef Args, const FunctionProtoType *Proto, SourceLocation Loc); + void checkAIXMemberAlignment(SourceLocation Loc, const Expr *Arg); + void CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl, StringRef ParamName, QualType ArgTy, QualType ParamTy); @@ -13166,16 +13184,15 @@ public: private: bool CheckFormatArguments(const FormatAttr *Format, - ArrayRef Args, - bool IsCXXMember, - VariadicCallType CallType, - SourceLocation Loc, SourceRange Range, + ArrayRef Args, bool IsCXXMember, + VariadicCallType CallType, SourceLocation Loc, + SourceRange Range, llvm::SmallBitVector &CheckedVarArgs); bool CheckFormatArguments(ArrayRef Args, - bool HasVAListArg, unsigned format_idx, + FormatArgumentPassingKind FAPK, unsigned format_idx, unsigned firstDataArg, FormatStringType Type, - VariadicCallType CallType, - SourceLocation Loc, SourceRange range, + VariadicCallType CallType, SourceLocation Loc, + SourceRange range, llvm::SmallBitVector &CheckedVarArgs); void CheckAbsoluteValueFunction(const CallExpr *Call, diff --git a/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h b/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h index a01b32669ce3..50a27a211ef0 100644 --- a/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h +++ b/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h @@ -414,7 +414,8 @@ public: bool isArgumentConstructedDirectly(unsigned Index) const { // This assumes that the object was not yet removed from the state. return ExprEngine::getObjectUnderConstruction( - getState(), {getOriginExpr(), Index}, getLocationContext()).hasValue(); + getState(), {getOriginExpr(), Index}, getLocationContext()) + .has_value(); } /// Some calls have parameter numbering mismatched from argument numbering. @@ -1018,7 +1019,7 @@ public: SVal getObjectUnderConstruction() const { return ExprEngine::getObjectUnderConstruction(getState(), getOriginExpr(), getLocationContext()) - .getValue(); + .value(); } /// Number of non-placement arguments to the call. It is equal to 2 for diff --git a/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h b/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h index 4b6cbd516628..22b405919bc1 100644 --- a/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h +++ b/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h @@ -53,21 +53,17 @@ public: } /// Return true if the constraint is perfectly constrained to 'true'. - bool isConstrainedTrue() const { return Val && Val.getValue(); } + bool isConstrainedTrue() const { return Val && Val.value(); } /// Return true if the constraint is perfectly constrained to 'false'. - bool isConstrainedFalse() const { return Val && !Val.getValue(); } + bool isConstrainedFalse() const { return Val && !Val.value(); } /// Return true if the constrained is perfectly constrained. - bool isConstrained() const { - return Val.hasValue(); - } + bool isConstrained() const { return Val.has_value(); } /// Return true if the constrained is underconstrained and we do not know /// if the constraint is true of value. - bool isUnderconstrained() const { - return !Val.hasValue(); - } + bool isUnderconstrained() const { return !Val.has_value(); } }; class ConstraintManager { diff --git a/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h b/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h index 61cab28918db..cf515c5a809a 100644 --- a/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h +++ b/contrib/llvm-project/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h @@ -344,7 +344,7 @@ protected: if (!res) Cached[hash] = ConditionTruthVal(); else - Cached[hash] = ConditionTruthVal(res.getValue()); + Cached[hash] = ConditionTruthVal(res.value()); return Cached[hash]; } diff --git a/contrib/llvm-project/clang/include/clang/Support/RISCVVIntrinsicUtils.h b/contrib/llvm-project/clang/include/clang/Support/RISCVVIntrinsicUtils.h index 3b6f205f9f22..a5e7e6d35cc8 100644 --- a/contrib/llvm-project/clang/include/clang/Support/RISCVVIntrinsicUtils.h +++ b/contrib/llvm-project/clang/include/clang/Support/RISCVVIntrinsicUtils.h @@ -209,8 +209,8 @@ public: } bool isValid() const { return Valid; } - bool isScalar() const { return Scale && Scale.getValue() == 0; } - bool isVector() const { return Scale && Scale.getValue() != 0; } + bool isScalar() const { return Scale && Scale.value() == 0; } + bool isVector() const { return Scale && Scale.value() != 0; } bool isVector(unsigned Width) const { return isVector() && ElementBitwidth == Width; } @@ -225,6 +225,8 @@ public: return isFloat() && ElementBitwidth == Width; } + bool isPointer() const { return IsPointer; } + private: // Verify RVV vector type and set Valid. bool verifyType() const; diff --git a/contrib/llvm-project/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h b/contrib/llvm-project/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h index e0d16df92e1a..b3882c227eaf 100644 --- a/contrib/llvm-project/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h +++ b/contrib/llvm-project/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h @@ -94,9 +94,9 @@ public: assert(!isDirectory() && "not a file"); assert(Contents && "contents not initialized"); if (auto *Directives = Contents->DepDirectives.load()) { - if (Directives->hasValue()) + if (Directives->has_value()) return ArrayRef( - Directives->getValue()); + Directives->value()); } return None; } diff --git a/contrib/llvm-project/clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h b/contrib/llvm-project/clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h index 3bb44e44187b..a85d333ba6b1 100644 --- a/contrib/llvm-project/clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h +++ b/contrib/llvm-project/clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h @@ -47,12 +47,12 @@ struct FullDependencies { /// Get the full command line. /// - /// \param LookupPCMPath This function is called to fill in "-fmodule-file=" - /// arguments and the "-o" argument. It needs to return - /// a path for where the PCM for the given module is to - /// be located. - std::vector - getCommandLine(std::function LookupPCMPath) const; + /// \param LookupModuleOutput This function is called to fill in + /// "-fmodule-file=", "-o" and other output + /// arguments for dependencies. + std::vector getCommandLine( + llvm::function_ref + LookupOutput) const; /// Get the full command line, excluding -fmodule-file=" arguments. std::vector getCommandLineWithoutModulePaths() const; diff --git a/contrib/llvm-project/clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h b/contrib/llvm-project/clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h index e0a4d6a554eb..05c9f56b4cf6 100644 --- a/contrib/llvm-project/clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h +++ b/contrib/llvm-project/clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h @@ -65,6 +65,19 @@ struct ModuleIDHasher { } }; +/// An output from a module compilation, such as the path of the module file. +enum class ModuleOutputKind { + /// The module file (.pcm). Required. + ModuleFile, + /// The path of the dependency file (.d), if any. + DependencyFile, + /// The null-separated list of names to use as the targets in the dependency + /// file, if any. Defaults to the value of \c ModuleFile, as in the driver. + DependencyTargets, + /// The path of the serialized diagnostic file (.dia), if any. + DiagnosticSerializationFile, +}; + struct ModuleDeps { /// The identifier of the module. ModuleID ID; @@ -104,17 +117,25 @@ struct ModuleDeps { // the primary TU. bool ImportedByMainFile = false; + /// Whether the TU had a dependency file. The path in \c BuildInvocation is + /// cleared to avoid leaking the specific path from the TU into the module. + bool HadDependencyFile = false; + + /// Whether the TU had serialized diagnostics. The path in \c BuildInvocation + /// is cleared to avoid leaking the specific path from the TU into the module. + bool HadSerializedDiagnostics = false; + /// Compiler invocation that can be used to build this module (without paths). CompilerInvocation BuildInvocation; /// Gets the canonical command line suitable for passing to clang. /// - /// \param LookupPCMPath This function is called to fill in "-fmodule-file=" - /// arguments and the "-o" argument. It needs to return - /// a path for where the PCM for the given module is to - /// be located. + /// \param LookupModuleOutput This function is called to fill in + /// "-fmodule-file=", "-o" and other output + /// arguments. std::vector getCanonicalCommandLine( - std::function LookupPCMPath) const; + llvm::function_ref + LookupModuleOutput) const; /// Gets the canonical command line suitable for passing to clang, excluding /// "-fmodule-file=" and "-o" arguments. diff --git a/contrib/llvm-project/clang/lib/AST/ASTContext.cpp b/contrib/llvm-project/clang/lib/AST/ASTContext.cpp index 682b71a3d686..cfd7bf604542 100644 --- a/contrib/llvm-project/clang/lib/AST/ASTContext.cpp +++ b/contrib/llvm-project/clang/lib/AST/ASTContext.cpp @@ -3166,7 +3166,7 @@ void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD, /// declaration of a function with an exception specification is permitted /// and preserved. Other type sugar (for instance, typedefs) is not. QualType ASTContext::getFunctionTypeWithExceptionSpec( - QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) { + QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const { // Might have some parens. if (const auto *PT = dyn_cast(Orig)) return getParenType( @@ -3194,7 +3194,7 @@ QualType ASTContext::getFunctionTypeWithExceptionSpec( } bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T, - QualType U) { + QualType U) const { return hasSameType(T, U) || (getLangOpts().CPlusPlus17 && hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None), @@ -4703,7 +4703,7 @@ QualType ASTContext::getUnresolvedUsingType( QualType ASTContext::getAttributedType(attr::Kind attrKind, QualType modifiedType, - QualType equivalentType) { + QualType equivalentType) const { llvm::FoldingSetNodeID id; AttributedType::Profile(id, attrKind, modifiedType, equivalentType); @@ -5707,6 +5707,9 @@ QualType ASTContext::getAutoTypeInternal( !TypeConstraintConcept && !IsDependent) return getAutoDeductType(); + if (TypeConstraintConcept) + TypeConstraintConcept = TypeConstraintConcept->getCanonicalDecl(); + // Look in the folding set for an existing type. void *InsertPos = nullptr; llvm::FoldingSetNodeID ID; @@ -6215,8 +6218,59 @@ bool ASTContext::hasSameTemplateName(const TemplateName &X, getCanonicalTemplateName(Y).getAsVoidPointer(); } +bool ASTContext::isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const { + if (!XCE != !YCE) + return false; + + if (!XCE) + return true; + + llvm::FoldingSetNodeID XCEID, YCEID; + XCE->Profile(XCEID, *this, /*Canonical=*/true); + YCE->Profile(YCEID, *this, /*Canonical=*/true); + return XCEID == YCEID; +} + +bool ASTContext::isSameTypeConstraint(const TypeConstraint *XTC, + const TypeConstraint *YTC) const { + if (!XTC != !YTC) + return false; + + if (!XTC) + return true; + + auto *NCX = XTC->getNamedConcept(); + auto *NCY = YTC->getNamedConcept(); + if (!NCX || !NCY || !isSameEntity(NCX, NCY)) + return false; + if (XTC->hasExplicitTemplateArgs() != YTC->hasExplicitTemplateArgs()) + return false; + if (XTC->hasExplicitTemplateArgs()) + if (XTC->getTemplateArgsAsWritten()->NumTemplateArgs != + YTC->getTemplateArgsAsWritten()->NumTemplateArgs) + return false; + + // Compare slowly by profiling. + // + // We couldn't compare the profiling result for the template + // args here. Consider the following example in different modules: + // + // template <__integer_like _Tp, C<_Tp> Sentinel> + // constexpr _Tp operator()(_Tp &&__t, Sentinel &&last) const { + // return __t; + // } + // + // When we compare the profiling result for `C<_Tp>` in different + // modules, it will compare the type of `_Tp` in different modules. + // However, the type of `_Tp` in different modules refer to different + // types here naturally. So we couldn't compare the profiling result + // for the template args directly. + return isSameConstraintExpr(XTC->getImmediatelyDeclaredConstraint(), + YTC->getImmediatelyDeclaredConstraint()); +} + bool ASTContext::isSameTemplateParameter(const NamedDecl *X, - const NamedDecl *Y) { + const NamedDecl *Y) const { if (X->getKind() != Y->getKind()) return false; @@ -6226,32 +6280,8 @@ bool ASTContext::isSameTemplateParameter(const NamedDecl *X, return false; if (TX->hasTypeConstraint() != TY->hasTypeConstraint()) return false; - const TypeConstraint *TXTC = TX->getTypeConstraint(); - const TypeConstraint *TYTC = TY->getTypeConstraint(); - if (!TXTC != !TYTC) - return false; - if (TXTC && TYTC) { - auto *NCX = TXTC->getNamedConcept(); - auto *NCY = TYTC->getNamedConcept(); - if (!NCX || !NCY || !isSameEntity(NCX, NCY)) - return false; - if (TXTC->hasExplicitTemplateArgs() != TYTC->hasExplicitTemplateArgs()) - return false; - if (TXTC->hasExplicitTemplateArgs()) { - auto *TXTCArgs = TXTC->getTemplateArgsAsWritten(); - auto *TYTCArgs = TYTC->getTemplateArgsAsWritten(); - if (TXTCArgs->NumTemplateArgs != TYTCArgs->NumTemplateArgs) - return false; - llvm::FoldingSetNodeID XID, YID; - for (auto &ArgLoc : TXTCArgs->arguments()) - ArgLoc.getArgument().Profile(XID, X->getASTContext()); - for (auto &ArgLoc : TYTCArgs->arguments()) - ArgLoc.getArgument().Profile(YID, Y->getASTContext()); - if (XID != YID) - return false; - } - } - return true; + return isSameTypeConstraint(TX->getTypeConstraint(), + TY->getTypeConstraint()); } if (auto *TX = dyn_cast(X)) { @@ -6267,8 +6297,8 @@ bool ASTContext::isSameTemplateParameter(const NamedDecl *X, TY->getTemplateParameters()); } -bool ASTContext::isSameTemplateParameterList(const TemplateParameterList *X, - const TemplateParameterList *Y) { +bool ASTContext::isSameTemplateParameterList( + const TemplateParameterList *X, const TemplateParameterList *Y) const { if (X->size() != Y->size()) return false; @@ -6276,19 +6306,46 @@ bool ASTContext::isSameTemplateParameterList(const TemplateParameterList *X, if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I))) return false; - const Expr *XRC = X->getRequiresClause(); - const Expr *YRC = Y->getRequiresClause(); - if (!XRC != !YRC) + return isSameConstraintExpr(X->getRequiresClause(), Y->getRequiresClause()); +} + +bool ASTContext::isSameDefaultTemplateArgument(const NamedDecl *X, + const NamedDecl *Y) const { + // If the type parameter isn't the same already, we don't need to check the + // default argument further. + if (!isSameTemplateParameter(X, Y)) return false; - if (XRC) { - llvm::FoldingSetNodeID XRCID, YRCID; - XRC->Profile(XRCID, *this, /*Canonical=*/true); - YRC->Profile(YRCID, *this, /*Canonical=*/true); - if (XRCID != YRCID) + + if (auto *TTPX = dyn_cast(X)) { + auto *TTPY = cast(Y); + if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument()) return false; + + return hasSameType(TTPX->getDefaultArgument(), TTPY->getDefaultArgument()); } - return true; + if (auto *NTTPX = dyn_cast(X)) { + auto *NTTPY = cast(Y); + if (!NTTPX->hasDefaultArgument() || !NTTPY->hasDefaultArgument()) + return false; + + Expr *DefaultArgumentX = NTTPX->getDefaultArgument()->IgnoreImpCasts(); + Expr *DefaultArgumentY = NTTPY->getDefaultArgument()->IgnoreImpCasts(); + llvm::FoldingSetNodeID XID, YID; + DefaultArgumentX->Profile(XID, *this, /*Canonical=*/true); + DefaultArgumentY->Profile(YID, *this, /*Canonical=*/true); + return XID == YID; + } + + auto *TTPX = cast(X); + auto *TTPY = cast(Y); + + if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument()) + return false; + + const TemplateArgument &TAX = TTPX->getDefaultArgument().getArgument(); + const TemplateArgument &TAY = TTPY->getDefaultArgument().getArgument(); + return hasSameTemplateName(TAX.getAsTemplate(), TAY.getAsTemplate()); } static NamespaceDecl *getNamespace(const NestedNameSpecifier *X) { @@ -6371,7 +6428,7 @@ static bool hasSameOverloadableAttrs(const FunctionDecl *A, return true; } -bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) { +bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) const { if (X == Y) return true; @@ -6447,17 +6504,9 @@ bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) { return false; } - const Expr *XRC = FuncX->getTrailingRequiresClause(); - const Expr *YRC = FuncY->getTrailingRequiresClause(); - if (!XRC != !YRC) + if (!isSameConstraintExpr(FuncX->getTrailingRequiresClause(), + FuncY->getTrailingRequiresClause())) return false; - if (XRC) { - llvm::FoldingSetNodeID XRCID, YRCID; - XRC->Profile(XRCID, *this, /*Canonical=*/true); - YRC->Profile(YRCID, *this, /*Canonical=*/true); - if (XRCID != YRCID) - return false; - } auto GetTypeAsWritten = [](const FunctionDecl *FD) { // Map to the first declaration that we've already merged into this one. @@ -6478,8 +6527,6 @@ bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) { if (getLangOpts().CPlusPlus17 && XFPT && YFPT && (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) || isUnresolvedExceptionSpec(YFPT->getExceptionSpecType())) && - // FIXME: We could make isSameEntity const after we make - // hasSameFunctionTypeIgnoringExceptionSpec const. hasSameFunctionTypeIgnoringExceptionSpec(XT, YT)) return true; return false; @@ -6521,6 +6568,20 @@ bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) { // and patterns match. if (const auto *TemplateX = dyn_cast(X)) { const auto *TemplateY = cast(Y); + + // ConceptDecl wouldn't be the same if their constraint expression differs. + if (const auto *ConceptX = dyn_cast(X)) { + const auto *ConceptY = cast(Y); + const Expr *XCE = ConceptX->getConstraintExpr(); + const Expr *YCE = ConceptY->getConstraintExpr(); + assert(XCE && YCE && "ConceptDecl without constraint expression?"); + llvm::FoldingSetNodeID XID, YID; + XCE->Profile(XID, *this, /*Canonical=*/true); + YCE->Profile(YID, *this, /*Canonical=*/true); + if (XID != YID) + return false; + } + return isSameEntity(TemplateX->getTemplatedDecl(), TemplateY->getTemplatedDecl()) && isSameTemplateParameterList(TemplateX->getTemplateParameters(), diff --git a/contrib/llvm-project/clang/lib/AST/ASTImporter.cpp b/contrib/llvm-project/clang/lib/AST/ASTImporter.cpp index e9730112eaa3..73c3f02e67a8 100644 --- a/contrib/llvm-project/clang/lib/AST/ASTImporter.cpp +++ b/contrib/llvm-project/clang/lib/AST/ASTImporter.cpp @@ -5667,11 +5667,6 @@ ExpectedDecl ASTNodeImporter::VisitClassTemplateDecl(ClassTemplateDecl *D) { D2->setPreviousDecl(Recent); } - if (FromTemplated->isCompleteDefinition() && - !ToTemplated->isCompleteDefinition()) { - // FIXME: Import definition! - } - return D2; } @@ -5950,11 +5945,6 @@ ExpectedDecl ASTNodeImporter::VisitVarTemplateDecl(VarTemplateDecl *D) { ToVarTD->setPreviousDecl(Recent); } - if (DTemplated->isThisDeclarationADefinition() && - !ToTemplated->isThisDeclarationADefinition()) { - // FIXME: Import definition! - } - return ToVarTD; } diff --git a/contrib/llvm-project/clang/lib/AST/AttrImpl.cpp b/contrib/llvm-project/clang/lib/AST/AttrImpl.cpp index c1e7435b22da..deb28bee5ed8 100644 --- a/contrib/llvm-project/clang/lib/AST/AttrImpl.cpp +++ b/contrib/llvm-project/clang/lib/AST/AttrImpl.cpp @@ -169,7 +169,7 @@ llvm::Optional OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(const ValueDecl *VD) { llvm::Optional ActiveAttr = getActiveAttr(VD); if (ActiveAttr) - return ActiveAttr.getValue()->getMapType(); + return ActiveAttr.value()->getMapType(); return llvm::None; } @@ -177,7 +177,7 @@ llvm::Optional OMPDeclareTargetDeclAttr::getDeviceType(const ValueDecl *VD) { llvm::Optional ActiveAttr = getActiveAttr(VD); if (ActiveAttr) - return ActiveAttr.getValue()->getDevType(); + return ActiveAttr.value()->getDevType(); return llvm::None; } @@ -185,7 +185,7 @@ llvm::Optional OMPDeclareTargetDeclAttr::getLocation(const ValueDecl *VD) { llvm::Optional ActiveAttr = getActiveAttr(VD); if (ActiveAttr) - return ActiveAttr.getValue()->getRange().getBegin(); + return ActiveAttr.value()->getRange().getBegin(); return llvm::None; } diff --git a/contrib/llvm-project/clang/lib/AST/DeclPrinter.cpp b/contrib/llvm-project/clang/lib/AST/DeclPrinter.cpp index c6a392c9c01b..3f04d9b4073e 100644 --- a/contrib/llvm-project/clang/lib/AST/DeclPrinter.cpp +++ b/contrib/llvm-project/clang/lib/AST/DeclPrinter.cpp @@ -1007,6 +1007,12 @@ void DeclPrinter::VisitCXXRecordDecl(CXXRecordDecl *D) { } } + if (auto *Def = D->getDefinition()) { + if (D->hasAttr()) { + Out << " final"; + } + } + if (D->isCompleteDefinition()) { // Print the base classes if (D->getNumBases()) { diff --git a/contrib/llvm-project/clang/lib/AST/FormatString.cpp b/contrib/llvm-project/clang/lib/AST/FormatString.cpp index 4977aaa51319..c0879704de4d 100644 --- a/contrib/llvm-project/clang/lib/AST/FormatString.cpp +++ b/contrib/llvm-project/clang/lib/AST/FormatString.cpp @@ -321,6 +321,12 @@ bool clang::analyze_format_string::ParseUTF8InvalidSpecifier( clang::analyze_format_string::ArgType::MatchKind ArgType::matchesType(ASTContext &C, QualType argTy) const { + // When using the format attribute in C++, you can receive a function or an + // array that will necessarily decay to a pointer when passed to the final + // format consumer. Apply decay before type comparison. + if (argTy->canDecayToPointerType()) + argTy = C.getDecayedType(argTy); + if (Ptr) { // It has to be a pointer. const PointerType *PT = argTy->getAs(); diff --git a/contrib/llvm-project/clang/lib/AST/Interp/ByteCodeExprGen.cpp b/contrib/llvm-project/clang/lib/AST/Interp/ByteCodeExprGen.cpp index da538aa332ff..9b729e347a24 100644 --- a/contrib/llvm-project/clang/lib/AST/Interp/ByteCodeExprGen.cpp +++ b/contrib/llvm-project/clang/lib/AST/Interp/ByteCodeExprGen.cpp @@ -496,7 +496,7 @@ ByteCodeExprGen::getGlobalIdx(const VarDecl *VD) { template const RecordType *ByteCodeExprGen::getRecordTy(QualType Ty) { - if (auto *PT = dyn_cast(Ty)) + if (const PointerType *PT = dyn_cast(Ty)) return PT->getPointeeType()->getAs(); else return Ty->getAs(); diff --git a/contrib/llvm-project/clang/lib/Analysis/BodyFarm.cpp b/contrib/llvm-project/clang/lib/Analysis/BodyFarm.cpp index 23d37b881069..38f100ae0a4f 100644 --- a/contrib/llvm-project/clang/lib/Analysis/BodyFarm.cpp +++ b/contrib/llvm-project/clang/lib/Analysis/BodyFarm.cpp @@ -699,7 +699,7 @@ static Stmt *create_OSAtomicCompareAndSwap(ASTContext &C, const FunctionDecl *D) Stmt *BodyFarm::getBody(const FunctionDecl *D) { Optional &Val = Bodies[D]; if (Val) - return Val.getValue(); + return Val.value(); Val = nullptr; @@ -874,7 +874,7 @@ Stmt *BodyFarm::getBody(const ObjCMethodDecl *D) { Optional &Val = Bodies[D]; if (Val) - return Val.getValue(); + return Val.value(); Val = nullptr; // For now, we only synthesize getters. diff --git a/contrib/llvm-project/clang/lib/Analysis/FlowSensitive/ControlFlowContext.cpp b/contrib/llvm-project/clang/lib/Analysis/FlowSensitive/ControlFlowContext.cpp index fe9907a7c99b..58708b5b5efb 100644 --- a/contrib/llvm-project/clang/lib/Analysis/FlowSensitive/ControlFlowContext.cpp +++ b/contrib/llvm-project/clang/lib/Analysis/FlowSensitive/ControlFlowContext.cpp @@ -36,7 +36,7 @@ buildStmtToBasicBlockMap(const CFG &Cfg) { if (!Stmt) continue; - StmtToBlock[Stmt.getValue().getStmt()] = Block; + StmtToBlock[Stmt.value().getStmt()] = Block; } if (const Stmt *TerminatorStmt = Block->getTerminatorStmt()) StmtToBlock[TerminatorStmt] = Block; diff --git a/contrib/llvm-project/clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp b/contrib/llvm-project/clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp index e08fc71c51dc..cd87e87a6aca 100644 --- a/contrib/llvm-project/clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp +++ b/contrib/llvm-project/clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp @@ -24,8 +24,8 @@ namespace dataflow { StorageLocation & DataflowAnalysisContext::getStableStorageLocation(QualType Type) { - assert(!Type.isNull()); - if (Type->isStructureOrClassType() || Type->isUnionType()) { + if (!Type.isNull() && + (Type->isStructureOrClassType() || Type->isUnionType())) { // FIXME: Explore options to avoid eager initialization of fields as some of // them might not be needed for a particular analysis. llvm::DenseMap FieldLocs; @@ -57,8 +57,8 @@ DataflowAnalysisContext::getStableStorageLocation(const Expr &E) { PointerValue & DataflowAnalysisContext::getOrCreateNullPointerValue(QualType PointeeType) { - assert(!PointeeType.isNull()); - auto CanonicalPointeeType = PointeeType.getCanonicalType(); + auto CanonicalPointeeType = + PointeeType.isNull() ? PointeeType : PointeeType.getCanonicalType(); auto Res = NullPointerVals.try_emplace(CanonicalPointeeType, nullptr); if (Res.second) { auto &PointeeLoc = getStableStorageLocation(CanonicalPointeeType); diff --git a/contrib/llvm-project/clang/lib/Analysis/FlowSensitive/DebugSupport.cpp b/contrib/llvm-project/clang/lib/Analysis/FlowSensitive/DebugSupport.cpp new file mode 100644 index 000000000000..305d9d346089 --- /dev/null +++ b/contrib/llvm-project/clang/lib/Analysis/FlowSensitive/DebugSupport.cpp @@ -0,0 +1,197 @@ +//===- DebugSupport.cpp -----------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file defines functions which generate more readable forms of data +// structures used in the dataflow analyses, for debugging purposes. +// +//===----------------------------------------------------------------------===// + +#include + +#include "clang/Analysis/FlowSensitive/DebugSupport.h" +#include "clang/Analysis/FlowSensitive/Solver.h" +#include "clang/Analysis/FlowSensitive/Value.h" +#include "llvm/ADT/DenseMap.h" +#include "llvm/ADT/StringSet.h" +#include "llvm/Support/ErrorHandling.h" +#include "llvm/Support/FormatAdapters.h" +#include "llvm/Support/FormatCommon.h" +#include "llvm/Support/FormatVariadic.h" + +namespace clang { +namespace dataflow { + +using llvm::AlignStyle; +using llvm::fmt_pad; +using llvm::formatv; + +namespace { + +class DebugStringGenerator { +public: + explicit DebugStringGenerator( + llvm::DenseMap AtomNamesArg) + : Counter(0), AtomNames(std::move(AtomNamesArg)) { +#ifndef NDEBUG + llvm::StringSet<> Names; + for (auto &N : AtomNames) { + assert(Names.insert(N.second).second && + "The same name must not assigned to different atoms"); + } +#endif + } + + /// Returns a string representation of a boolean value `B`. + std::string debugString(const BoolValue &B, size_t Depth = 0) { + std::string S; + switch (B.getKind()) { + case Value::Kind::AtomicBool: { + S = getAtomName(&cast(B)); + break; + } + case Value::Kind::Conjunction: { + auto &C = cast(B); + auto L = debugString(C.getLeftSubValue(), Depth + 1); + auto R = debugString(C.getRightSubValue(), Depth + 1); + S = formatv("(and\n{0}\n{1})", L, R); + break; + } + case Value::Kind::Disjunction: { + auto &D = cast(B); + auto L = debugString(D.getLeftSubValue(), Depth + 1); + auto R = debugString(D.getRightSubValue(), Depth + 1); + S = formatv("(or\n{0}\n{1})", L, R); + break; + } + case Value::Kind::Negation: { + auto &N = cast(B); + S = formatv("(not\n{0})", debugString(N.getSubVal(), Depth + 1)); + break; + } + default: + llvm_unreachable("Unhandled value kind"); + } + auto Indent = Depth * 4; + return formatv("{0}", fmt_pad(S, Indent, 0)); + } + + /// Returns a string representation of a set of boolean `Constraints` and the + /// `Result` of satisfiability checking on the `Constraints`. + std::string debugString(const std::vector &Constraints, + const Solver::Result &Result) { + auto Template = R"( +Constraints +------------ +{0:$[ + +]} +------------ +{1}. +{2} +)"; + + std::vector ConstraintsStrings; + ConstraintsStrings.reserve(Constraints.size()); + for (auto &Constraint : Constraints) { + ConstraintsStrings.push_back(debugString(*Constraint)); + } + + auto StatusString = debugString(Result.getStatus()); + auto Solution = Result.getSolution(); + auto SolutionString = + Solution.hasValue() ? "\n" + debugString(Solution.value()) : ""; + + return formatv( + Template, + llvm::make_range(ConstraintsStrings.begin(), ConstraintsStrings.end()), + StatusString, SolutionString); + } + +private: + /// Returns a string representation of a truth assignment to atom booleans. + std::string debugString( + const llvm::DenseMap + &AtomAssignments) { + size_t MaxNameLength = 0; + for (auto &AtomName : AtomNames) { + MaxNameLength = std::max(MaxNameLength, AtomName.second.size()); + } + + std::vector Lines; + for (auto &AtomAssignment : AtomAssignments) { + auto Line = formatv("{0} = {1}", + fmt_align(getAtomName(AtomAssignment.first), + AlignStyle::Left, MaxNameLength), + debugString(AtomAssignment.second)); + Lines.push_back(Line); + } + llvm::sort(Lines.begin(), Lines.end()); + + return formatv("{0:$[\n]}", llvm::make_range(Lines.begin(), Lines.end())); + } + + /// Returns a string representation of a boolean assignment to true or false. + std::string debugString(Solver::Result::Assignment Assignment) { + switch (Assignment) { + case Solver::Result::Assignment::AssignedFalse: + return "False"; + case Solver::Result::Assignment::AssignedTrue: + return "True"; + } + llvm_unreachable("Booleans can only be assigned true/false"); + } + + /// Returns a string representation of the result status of a SAT check. + std::string debugString(Solver::Result::Status Status) { + switch (Status) { + case Solver::Result::Status::Satisfiable: + return "Satisfiable"; + case Solver::Result::Status::Unsatisfiable: + return "Unsatisfiable"; + case Solver::Result::Status::TimedOut: + return "TimedOut"; + } + llvm_unreachable("Unhandled SAT check result status"); + } + + /// Returns the name assigned to `Atom`, either user-specified or created by + /// default rules (B0, B1, ...). + std::string getAtomName(const AtomicBoolValue *Atom) { + auto Entry = AtomNames.try_emplace(Atom, formatv("B{0}", Counter)); + if (Entry.second) { + Counter++; + } + return Entry.first->second; + } + + // Keep track of number of atoms without a user-specified name, used to assign + // non-repeating default names to such atoms. + size_t Counter; + + // Keep track of names assigned to atoms. + llvm::DenseMap AtomNames; +}; + +} // namespace + +std::string +debugString(const BoolValue &B, + llvm::DenseMap AtomNames) { + return DebugStringGenerator(std::move(AtomNames)).debugString(B); +} + +std::string +debugString(const std::vector &Constraints, + const Solver::Result &Result, + llvm::DenseMap AtomNames) { + return DebugStringGenerator(std::move(AtomNames)) + .debugString(Constraints, Result); +} + +} // namespace dataflow +} // namespace clang diff --git a/contrib/llvm-project/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp b/contrib/llvm-project/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp index 6443fc1b6422..6ce9dd55914d 100644 --- a/contrib/llvm-project/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp +++ b/contrib/llvm-project/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp @@ -51,7 +51,7 @@ public: assert(BlockIT != CFCtx.getStmtToBlock().end()); const auto &State = BlockToState[BlockIT->getSecond()->getBlockID()]; assert(State); - return &State.getValue().Env; + return &State.value().Env; } private: @@ -212,7 +212,7 @@ static TypeErasedDataflowAnalysisState computeBlockInputState( if (!MaybePredState) continue; - TypeErasedDataflowAnalysisState PredState = MaybePredState.getValue(); + TypeErasedDataflowAnalysisState PredState = MaybePredState.value(); if (ApplyBuiltinTransfer) { if (const Stmt *PredTerminatorStmt = Pred->getTerminatorStmt()) { const StmtToEnvMapImpl StmtToEnv(CFCtx, BlockStates); @@ -370,7 +370,7 @@ runTypeErasedDataflowAnalysis( transferBlock(CFCtx, BlockStates, *Block, InitEnv, Analysis); if (OldBlockState && - Analysis.isEqualTypeErased(OldBlockState.getValue().Lattice, + Analysis.isEqualTypeErased(OldBlockState.value().Lattice, NewBlockState.Lattice) && OldBlockState->Env.equivalentTo(NewBlockState.Env, Analysis)) { // The state of `Block` didn't change after transfer so there's no need to diff --git a/contrib/llvm-project/clang/lib/Analysis/FlowSensitive/WatchedLiteralsSolver.cpp b/contrib/llvm-project/clang/lib/Analysis/FlowSensitive/WatchedLiteralsSolver.cpp index 0e6e70d6d5d4..6a3948bd1fea 100644 --- a/contrib/llvm-project/clang/lib/Analysis/FlowSensitive/WatchedLiteralsSolver.cpp +++ b/contrib/llvm-project/clang/lib/Analysis/FlowSensitive/WatchedLiteralsSolver.cpp @@ -120,7 +120,13 @@ struct BooleanFormula { /// clauses in the formula start from the element at index 1. std::vector NextWatched; - explicit BooleanFormula(Variable LargestVar) : LargestVar(LargestVar) { + /// Stores the variable identifier and value location for atomic booleans in + /// the formula. + llvm::DenseMap Atomics; + + explicit BooleanFormula(Variable LargestVar, + llvm::DenseMap Atomics) + : LargestVar(LargestVar), Atomics(std::move(Atomics)) { Clauses.push_back(0); ClauseStarts.push_back(0); NextWatched.push_back(0); @@ -180,28 +186,47 @@ BooleanFormula buildBooleanFormula(const llvm::DenseSet &Vals) { // Map each sub-value in `Vals` to a unique variable. llvm::DenseMap SubValsToVar; + // Store variable identifiers and value location of atomic booleans. + llvm::DenseMap Atomics; Variable NextVar = 1; { std::queue UnprocessedSubVals; for (BoolValue *Val : Vals) UnprocessedSubVals.push(Val); while (!UnprocessedSubVals.empty()) { + Variable Var = NextVar; BoolValue *Val = UnprocessedSubVals.front(); UnprocessedSubVals.pop(); - if (!SubValsToVar.try_emplace(Val, NextVar).second) + if (!SubValsToVar.try_emplace(Val, Var).second) continue; ++NextVar; // Visit the sub-values of `Val`. - if (auto *C = dyn_cast(Val)) { + switch (Val->getKind()) { + case Value::Kind::Conjunction: { + auto *C = cast(Val); UnprocessedSubVals.push(&C->getLeftSubValue()); UnprocessedSubVals.push(&C->getRightSubValue()); - } else if (auto *D = dyn_cast(Val)) { + break; + } + case Value::Kind::Disjunction: { + auto *D = cast(Val); UnprocessedSubVals.push(&D->getLeftSubValue()); UnprocessedSubVals.push(&D->getRightSubValue()); - } else if (auto *N = dyn_cast(Val)) { + break; + } + case Value::Kind::Negation: { + auto *N = cast(Val); UnprocessedSubVals.push(&N->getSubVal()); + break; + } + case Value::Kind::AtomicBool: { + Atomics[Var] = cast(Val); + break; + } + default: + llvm_unreachable("buildBooleanFormula: unhandled value kind"); } } } @@ -212,7 +237,7 @@ BooleanFormula buildBooleanFormula(const llvm::DenseSet &Vals) { return ValIt->second; }; - BooleanFormula Formula(NextVar - 1); + BooleanFormula Formula(NextVar - 1, std::move(Atomics)); std::vector ProcessedSubVals(NextVar, false); // Add a conjunct for each variable that represents a top-level conjunction @@ -383,7 +408,7 @@ public: // If the root level is reached, then all possible assignments lead to // a conflict. if (Level == 0) - return WatchedLiteralsSolver::Result::Unsatisfiable; + return Solver::Result::Unsatisfiable(); // Otherwise, take the other branch at the most recent level where a // decision was made. @@ -440,12 +465,29 @@ public: ++I; } } - return WatchedLiteralsSolver::Result::Satisfiable; + return Solver::Result::Satisfiable(buildSolution()); } private: - // Reverses forced moves until the most recent level where a decision was made - // on the assignment of a variable. + /// Returns a satisfying truth assignment to the atomic values in the boolean + /// formula. + llvm::DenseMap + buildSolution() { + llvm::DenseMap Solution; + for (auto &Atomic : Formula.Atomics) { + // A variable may have a definite true/false assignment, or it may be + // unassigned indicating its truth value does not affect the result of + // the formula. Unassigned variables are assigned to true as a default. + Solution[Atomic.second] = + VarAssignments[Atomic.first] == Assignment::AssignedFalse + ? Solver::Result::Assignment::AssignedFalse + : Solver::Result::Assignment::AssignedTrue; + } + return Solution; + } + + /// Reverses forced moves until the most recent level where a decision was + /// made on the assignment of a variable. void reverseForcedMoves() { for (; LevelStates[Level] == State::Forced; --Level) { const Variable Var = LevelVars[Level]; @@ -459,7 +501,7 @@ private: } } - // Updates watched literals that are affected by a variable assignment. + /// Updates watched literals that are affected by a variable assignment. void updateWatchedLiterals() { const Variable Var = LevelVars[Level]; @@ -592,7 +634,7 @@ private: }; Solver::Result WatchedLiteralsSolver::solve(llvm::DenseSet Vals) { - return Vals.empty() ? WatchedLiteralsSolver::Result::Satisfiable + return Vals.empty() ? Solver::Result::Satisfiable({{}}) : WatchedLiteralsSolverImpl(Vals).solve(); } diff --git a/contrib/llvm-project/clang/lib/Analysis/PathDiagnostic.cpp b/contrib/llvm-project/clang/lib/Analysis/PathDiagnostic.cpp index 8a7305000746..bb5f116d6940 100644 --- a/contrib/llvm-project/clang/lib/Analysis/PathDiagnostic.cpp +++ b/contrib/llvm-project/clang/lib/Analysis/PathDiagnostic.cpp @@ -320,7 +320,7 @@ static Optional comparePath(const PathPieces &X, const PathPieces &Y) { for ( ; X_I != X_end && Y_I != Y_end; ++X_I, ++Y_I) { Optional b = comparePiece(**X_I, **Y_I); if (b) - return b.getValue(); + return b.value(); } return None; @@ -397,7 +397,7 @@ static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y) { } Optional b = comparePath(X.path, Y.path); assert(b); - return b.getValue(); + return b.value(); } void PathDiagnosticConsumer::FlushDiagnostics( diff --git a/contrib/llvm-project/clang/lib/Analysis/UninitializedValues.cpp b/contrib/llvm-project/clang/lib/Analysis/UninitializedValues.cpp index 800943a99d87..7f44685355e0 100644 --- a/contrib/llvm-project/clang/lib/Analysis/UninitializedValues.cpp +++ b/contrib/llvm-project/clang/lib/Analysis/UninitializedValues.cpp @@ -149,7 +149,7 @@ public: const VarDecl *vd) { const Optional &idx = declToIndex.getValueIndex(vd); assert(idx); - return getValueVector(block)[idx.getValue()]; + return getValueVector(block)[idx.value()]; } }; @@ -210,7 +210,7 @@ void CFGBlockValues::resetScratch() { ValueVector::reference CFGBlockValues::operator[](const VarDecl *vd) { const Optional &idx = declToIndex.getValueIndex(vd); assert(idx); - return scratch[idx.getValue()]; + return scratch[idx.value()]; } //------------------------------------------------------------------------====// diff --git a/contrib/llvm-project/clang/lib/Basic/LangStandards.cpp b/contrib/llvm-project/clang/lib/Basic/LangStandards.cpp index 5bacc3b16496..a21898dd3c62 100644 --- a/contrib/llvm-project/clang/lib/Basic/LangStandards.cpp +++ b/contrib/llvm-project/clang/lib/Basic/LangStandards.cpp @@ -61,8 +61,8 @@ LangStandard::Kind clang::getDefaultLanguageStandard(clang::Language Lang, if (CLANG_DEFAULT_STD_C != LangStandard::lang_unspecified) return CLANG_DEFAULT_STD_C; - // The PS4 and PS5 use C99 as the default C standard. - if (T.isPS()) + // The PS4 uses C99 as the default C standard. + if (T.isPS4()) return LangStandard::lang_gnu99; return LangStandard::lang_gnu17; case Language::ObjC: diff --git a/contrib/llvm-project/clang/lib/Basic/MakeSupport.cpp b/contrib/llvm-project/clang/lib/Basic/MakeSupport.cpp new file mode 100644 index 000000000000..37838f7bbc7b --- /dev/null +++ b/contrib/llvm-project/clang/lib/Basic/MakeSupport.cpp @@ -0,0 +1,35 @@ +//===-- MakeSuport.cpp --------------------------------------------------*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "clang/Basic/MakeSupport.h" + +void clang::quoteMakeTarget(StringRef Target, SmallVectorImpl &Res) { + for (unsigned i = 0, e = Target.size(); i != e; ++i) { + switch (Target[i]) { + case ' ': + case '\t': + // Escape the preceding backslashes + for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j) + Res.push_back('\\'); + + // Escape the space/tab + Res.push_back('\\'); + break; + case '$': + Res.push_back('$'); + break; + case '#': + Res.push_back('\\'); + break; + default: + break; + } + + Res.push_back(Target[i]); + } +} \ No newline at end of file diff --git a/contrib/llvm-project/clang/lib/Basic/TargetInfo.cpp b/contrib/llvm-project/clang/lib/Basic/TargetInfo.cpp index e22ed34e7da4..6685145ea6d2 100644 --- a/contrib/llvm-project/clang/lib/Basic/TargetInfo.cpp +++ b/contrib/llvm-project/clang/lib/Basic/TargetInfo.cpp @@ -503,7 +503,7 @@ bool TargetInfo::initFeatureMap( TargetInfo::CallingConvKind TargetInfo::getCallingConvKind(bool ClangABICompat4) const { if (getCXXABI() != TargetCXXABI::Microsoft && - (ClangABICompat4 || getTriple().getOS() == llvm::Triple::PS4)) + (ClangABICompat4 || getTriple().isPS4())) return CCK_ClangABI4OrPS4; return CCK_Default; } diff --git a/contrib/llvm-project/clang/lib/Basic/Targets/RISCV.cpp b/contrib/llvm-project/clang/lib/Basic/Targets/RISCV.cpp index 32dd2bad2c5c..cb2cdb50e18e 100644 --- a/contrib/llvm-project/clang/lib/Basic/Targets/RISCV.cpp +++ b/contrib/llvm-project/clang/lib/Basic/Targets/RISCV.cpp @@ -252,7 +252,7 @@ bool RISCVTargetInfo::hasFeature(StringRef Feature) const { .Case("64bit", Is64Bit) .Default(None); if (Result) - return Result.getValue(); + return Result.value(); if (ISAInfo->isSupportedExtensionFeature(Feature)) return ISAInfo->hasExtension(Feature); diff --git a/contrib/llvm-project/clang/lib/Basic/Targets/SystemZ.h b/contrib/llvm-project/clang/lib/Basic/Targets/SystemZ.h index d12045c756c1..e4f242e624cb 100644 --- a/contrib/llvm-project/clang/lib/Basic/Targets/SystemZ.h +++ b/contrib/llvm-project/clang/lib/Basic/Targets/SystemZ.h @@ -123,6 +123,14 @@ public: void fillValidCPUList(SmallVectorImpl &Values) const override; + bool isValidTuneCPUName(StringRef Name) const override { + return isValidCPUName(Name); + } + + void fillValidTuneCPUList(SmallVectorImpl &Values) const override { + fillValidCPUList(Values); + } + bool setCPU(const std::string &Name) override { CPU = Name; ISARevision = getISARevision(CPU); diff --git a/contrib/llvm-project/clang/lib/Basic/Targets/X86.cpp b/contrib/llvm-project/clang/lib/Basic/Targets/X86.cpp index 06988830eaed..69afdf8a3584 100644 --- a/contrib/llvm-project/clang/lib/Basic/Targets/X86.cpp +++ b/contrib/llvm-project/clang/lib/Basic/Targets/X86.cpp @@ -297,6 +297,8 @@ bool X86TargetInfo::handleTargetFeatures(std::vector &Features, HasCLDEMOTE = true; } else if (Feature == "+rdpid") { HasRDPID = true; + } else if (Feature == "+rdpru") { + HasRDPRU = true; } else if (Feature == "+kl") { HasKL = true; } else if (Feature == "+widekl") { @@ -743,6 +745,8 @@ void X86TargetInfo::getTargetDefines(const LangOptions &Opts, Builder.defineMacro("__WIDEKL__"); if (HasRDPID) Builder.defineMacro("__RDPID__"); + if (HasRDPRU) + Builder.defineMacro("__RDPRU__"); if (HasCLDEMOTE) Builder.defineMacro("__CLDEMOTE__"); if (HasWAITPKG) @@ -926,6 +930,7 @@ bool X86TargetInfo::isValidFeatureName(StringRef Name) const { .Case("prfchw", true) .Case("ptwrite", true) .Case("rdpid", true) + .Case("rdpru", true) .Case("rdrnd", true) .Case("rdseed", true) .Case("rtm", true) @@ -1021,6 +1026,7 @@ bool X86TargetInfo::hasFeature(StringRef Feature) const { .Case("prfchw", HasPRFCHW) .Case("ptwrite", HasPTWRITE) .Case("rdpid", HasRDPID) + .Case("rdpru", HasRDPRU) .Case("rdrnd", HasRDRND) .Case("rdseed", HasRDSEED) .Case("retpoline-external-thunk", HasRetpolineExternalThunk) diff --git a/contrib/llvm-project/clang/lib/Basic/Targets/X86.h b/contrib/llvm-project/clang/lib/Basic/Targets/X86.h index e582a2932b4f..3caf5256118e 100644 --- a/contrib/llvm-project/clang/lib/Basic/Targets/X86.h +++ b/contrib/llvm-project/clang/lib/Basic/Targets/X86.h @@ -125,6 +125,7 @@ class LLVM_LIBRARY_VISIBILITY X86TargetInfo : public TargetInfo { bool HasMOVBE = false; bool HasPREFETCHWT1 = false; bool HasRDPID = false; + bool HasRDPRU = false; bool HasRetpolineExternalThunk = false; bool HasLAHFSAHF = false; bool HasWBNOINVD = false; @@ -424,8 +425,8 @@ public: // Use fpret for all types. RealTypeUsesObjCFPRetMask = - (int)(FloatModeKind::Float | FloatModeKind::Double | - FloatModeKind::LongDouble); + (unsigned)(FloatModeKind::Float | FloatModeKind::Double | + FloatModeKind::LongDouble); // x86-32 has atomics up to 8 bytes MaxAtomicPromoteWidth = 64; @@ -704,7 +705,7 @@ public: "64-i64:64-f80:128-n8:16:32:64-S128"); // Use fpret only for long double. - RealTypeUsesObjCFPRetMask = (int)FloatModeKind::LongDouble; + RealTypeUsesObjCFPRetMask = (unsigned)FloatModeKind::LongDouble; // Use fp2ret for _Complex long double. ComplexLongDoubleUsesFP2Ret = true; diff --git a/contrib/llvm-project/clang/lib/CodeGen/BackendUtil.cpp b/contrib/llvm-project/clang/lib/CodeGen/BackendUtil.cpp index eb40e446057f..7c4e35634e5d 100644 --- a/contrib/llvm-project/clang/lib/CodeGen/BackendUtil.cpp +++ b/contrib/llvm-project/clang/lib/CodeGen/BackendUtil.cpp @@ -788,6 +788,18 @@ void EmitAssemblyHelper::RunOptimizationPipeline( SI.registerCallbacks(PIC, &FAM); PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC); + // Enable verify-debuginfo-preserve-each for new PM. + DebugifyEachInstrumentation Debugify; + DebugInfoPerPass DebugInfoBeforePass; + if (CodeGenOpts.EnableDIPreservationVerify) { + Debugify.setDebugifyMode(DebugifyMode::OriginalDebugInfo); + Debugify.setDebugInfoBeforePass(DebugInfoBeforePass); + + if (!CodeGenOpts.DIBugsReportFilePath.empty()) + Debugify.setOrigDIVerifyBugsReportFilePath( + CodeGenOpts.DIBugsReportFilePath); + Debugify.registerCallbacks(PIC); + } // Attempt to load pass plugins and register their callbacks with PB. for (auto &PluginFN : CodeGenOpts.PassPlugins) { auto PassPlugin = PassPlugin::Load(PluginFN); diff --git a/contrib/llvm-project/clang/lib/CodeGen/CGCUDANV.cpp b/contrib/llvm-project/clang/lib/CodeGen/CGCUDANV.cpp index 6f2679cb15e4..a8bb0dd65d1a 100644 --- a/contrib/llvm-project/clang/lib/CodeGen/CGCUDANV.cpp +++ b/contrib/llvm-project/clang/lib/CodeGen/CGCUDANV.cpp @@ -212,8 +212,7 @@ static std::unique_ptr InitDeviceMC(CodeGenModule &CGM) { CGNVCUDARuntime::CGNVCUDARuntime(CodeGenModule &CGM) : CGCUDARuntime(CGM), Context(CGM.getLLVMContext()), TheModule(CGM.getModule()), - RelocatableDeviceCode(CGM.getLangOpts().GPURelocatableDeviceCode || - CGM.getLangOpts().OffloadingNewDriver), + RelocatableDeviceCode(CGM.getLangOpts().GPURelocatableDeviceCode), DeviceMC(InitDeviceMC(CGM)) { CodeGen::CodeGenTypes &Types = CGM.getTypes(); ASTContext &Ctx = CGM.getContext(); @@ -1116,7 +1115,8 @@ void CGNVCUDARuntime::createOffloadingEntries() { llvm::OpenMPIRBuilder OMPBuilder(CGM.getModule()); OMPBuilder.initialize(); - StringRef Section = "cuda_offloading_entries"; + StringRef Section = CGM.getLangOpts().HIP ? "hip_offloading_entries" + : "cuda_offloading_entries"; for (KernelInfo &I : EmittedKernels) OMPBuilder.emitOffloadingEntry(KernelHandles[I.Kernel], getDeviceSideName(cast(I.D)), 0, @@ -1171,10 +1171,11 @@ llvm::Function *CGNVCUDARuntime::finalizeModule() { } return nullptr; } - if (!(CGM.getLangOpts().OffloadingNewDriver && RelocatableDeviceCode)) + if (CGM.getLangOpts().OffloadingNewDriver && RelocatableDeviceCode) + createOffloadingEntries(); + else return makeModuleCtorFunction(); - createOffloadingEntries(); return nullptr; } diff --git a/contrib/llvm-project/clang/lib/CodeGen/CGCall.cpp b/contrib/llvm-project/clang/lib/CodeGen/CGCall.cpp index 4e26c35c6342..104a30dd6b25 100644 --- a/contrib/llvm-project/clang/lib/CodeGen/CGCall.cpp +++ b/contrib/llvm-project/clang/lib/CodeGen/CGCall.cpp @@ -1931,6 +1931,9 @@ void CodeGenModule::getDefaultFunctionAttributes(StringRef Name, FuncAttrs.addAttribute(llvm::Attribute::Convergent); } + // TODO: NoUnwind attribute should be added for other GPU modes OpenCL, HIP, + // SYCL, OpenMP offload. AFAIK, none of them support exceptions in device + // code. if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { // Exceptions aren't supported in CUDA device code. FuncAttrs.addAttribute(llvm::Attribute::NoUnwind); diff --git a/contrib/llvm-project/clang/lib/CodeGen/CGClass.cpp b/contrib/llvm-project/clang/lib/CodeGen/CGClass.cpp index 153f299a1c4b..cde31711a7db 100644 --- a/contrib/llvm-project/clang/lib/CodeGen/CGClass.cpp +++ b/contrib/llvm-project/clang/lib/CodeGen/CGClass.cpp @@ -1783,14 +1783,14 @@ namespace { StartIndex = FieldIndex; } else if (StartIndex) { EHStack.pushCleanup( - NormalAndEHCleanup, DD, StartIndex.getValue(), FieldIndex); + NormalAndEHCleanup, DD, StartIndex.value(), FieldIndex); StartIndex = None; } } void End() { if (StartIndex) EHStack.pushCleanup(NormalAndEHCleanup, DD, - StartIndex.getValue(), -1); + StartIndex.value(), -1); } }; } // end anonymous namespace diff --git a/contrib/llvm-project/clang/lib/CodeGen/CGOpenMPRuntime.cpp b/contrib/llvm-project/clang/lib/CodeGen/CGOpenMPRuntime.cpp index 305040b01c08..091eb9da5af4 100644 --- a/contrib/llvm-project/clang/lib/CodeGen/CGOpenMPRuntime.cpp +++ b/contrib/llvm-project/clang/lib/CodeGen/CGOpenMPRuntime.cpp @@ -6717,11 +6717,9 @@ llvm::Value *CGOpenMPRuntime::emitNumTeamsForTargetDirective( default: break; } - } else if (DefaultNT == -1) { - return nullptr; } - return Bld.getInt32(DefaultNT); + return llvm::ConstantInt::get(CGF.Int32Ty, DefaultNT); } static llvm::Value *getNumThreads(CodeGenFunction &CGF, const CapturedStmt *CS, @@ -10189,9 +10187,8 @@ llvm::Function *CGOpenMPRuntime::getOrCreateUserDefinedMapperFunc( return UDMMap.lookup(D); } -void CGOpenMPRuntime::emitTargetNumIterationsCall( +llvm::Value *CGOpenMPRuntime::emitTargetNumIterationsCall( CodeGenFunction &CGF, const OMPExecutableDirective &D, - llvm::Value *DeviceID, llvm::function_ref SizeEmitter) { @@ -10201,20 +10198,12 @@ void CGOpenMPRuntime::emitTargetNumIterationsCall( if (!isOpenMPDistributeDirective(Kind) || !isOpenMPTeamsDirective(Kind)) TD = getNestedDistributeDirective(CGM.getContext(), D); if (!TD) - return; + return llvm::ConstantInt::get(CGF.Int64Ty, 0); + const auto *LD = cast(TD); - auto &&CodeGen = [LD, DeviceID, SizeEmitter, &D, this](CodeGenFunction &CGF, - PrePostActionTy &) { - if (llvm::Value *NumIterations = SizeEmitter(CGF, *LD)) { - llvm::Value *RTLoc = emitUpdateLocation(CGF, D.getBeginLoc()); - llvm::Value *Args[] = {RTLoc, DeviceID, NumIterations}; - CGF.EmitRuntimeCall( - OMPBuilder.getOrCreateRuntimeFunction( - CGM.getModule(), OMPRTL___kmpc_push_target_tripcount_mapper), - Args); - } - }; - emitInlinedDirective(CGF, OMPD_unknown, CodeGen); + if (llvm::Value *NumIterations = SizeEmitter(CGF, *LD)) + return NumIterations; + return llvm::ConstantInt::get(CGF.Int64Ty, 0); } void CGOpenMPRuntime::emitTargetCall( @@ -10308,26 +10297,34 @@ void CGOpenMPRuntime::emitTargetCall( // Source location for the ident struct llvm::Value *RTLoc = emitUpdateLocation(CGF, D.getBeginLoc()); - // Emit tripcount for the target loop-based directive. - emitTargetNumIterationsCall(CGF, D, DeviceID, SizeEmitter); + // Get tripcount for the target loop-based directive. + llvm::Value *NumIterations = + emitTargetNumIterationsCall(CGF, D, SizeEmitter); + + // Arguments for the target kernel. + SmallVector KernelArgs{ + CGF.Builder.getInt32(/* Version */ 1), + PointerNum, + InputInfo.BasePointersArray.getPointer(), + InputInfo.PointersArray.getPointer(), + InputInfo.SizesArray.getPointer(), + MapTypesArray, + MapNamesArray, + InputInfo.MappersArray.getPointer(), + NumIterations}; + + // Arguments passed to the 'nowait' variant. + SmallVector NoWaitKernelArgs{ + CGF.Builder.getInt32(0), + llvm::ConstantPointerNull::get(CGM.VoidPtrTy), + CGF.Builder.getInt32(0), + llvm::ConstantPointerNull::get(CGM.VoidPtrTy), + }; + + bool HasNoWait = D.hasClausesOfKind(); - bool HasNowait = D.hasClausesOfKind(); // The target region is an outlined function launched by the runtime - // via calls __tgt_target() or __tgt_target_teams(). - // - // __tgt_target() launches a target region with one team and one thread, - // executing a serial region. This master thread may in turn launch - // more threads within its team upon encountering a parallel region, - // however, no additional teams can be launched on the device. - // - // __tgt_target_teams() launches a target region with one or more teams, - // each with one or more threads. This call is required for target - // constructs such as: - // 'target teams' - // 'target' / 'teams' - // 'target teams distribute parallel for' - // 'target parallel' - // and so on. + // via calls to __tgt_target_kernel(). // // Note that on the host and CPU targets, the runtime implementation of // these calls simply call the outlined function without forking threads. @@ -10338,70 +10335,15 @@ void CGOpenMPRuntime::emitTargetCall( // In contrast, on the NVPTX target, the implementation of // __tgt_target_teams() launches a GPU kernel with the requested number // of teams and threads so no additional calls to the runtime are required. - if (NumTeams) { - // If we have NumTeams defined this means that we have an enclosed teams - // region. Therefore we also expect to have NumThreads defined. These two - // values should be defined in the presence of a teams directive, - // regardless of having any clauses associated. If the user is using teams - // but no clauses, these two values will be the default that should be - // passed to the runtime library - a 32-bit integer with the value zero. - assert(NumThreads && "Thread limit expression should be available along " - "with number of teams."); - SmallVector OffloadingArgs = { - RTLoc, - DeviceID, - OutlinedFnID, - PointerNum, - InputInfo.BasePointersArray.getPointer(), - InputInfo.PointersArray.getPointer(), - InputInfo.SizesArray.getPointer(), - MapTypesArray, - MapNamesArray, - InputInfo.MappersArray.getPointer(), - NumTeams, - NumThreads}; - if (HasNowait) { - // Add int32_t depNum = 0, void *depList = nullptr, int32_t - // noAliasDepNum = 0, void *noAliasDepList = nullptr. - OffloadingArgs.push_back(CGF.Builder.getInt32(0)); - OffloadingArgs.push_back(llvm::ConstantPointerNull::get(CGM.VoidPtrTy)); - OffloadingArgs.push_back(CGF.Builder.getInt32(0)); - OffloadingArgs.push_back(llvm::ConstantPointerNull::get(CGM.VoidPtrTy)); - } - Return = CGF.EmitRuntimeCall( - OMPBuilder.getOrCreateRuntimeFunction( - CGM.getModule(), HasNowait - ? OMPRTL___tgt_target_teams_nowait_mapper - : OMPRTL___tgt_target_teams_mapper), - OffloadingArgs); - } else { - SmallVector OffloadingArgs = { - RTLoc, - DeviceID, - OutlinedFnID, - PointerNum, - InputInfo.BasePointersArray.getPointer(), - InputInfo.PointersArray.getPointer(), - InputInfo.SizesArray.getPointer(), - MapTypesArray, - MapNamesArray, - InputInfo.MappersArray.getPointer()}; - if (HasNowait) { - // Add int32_t depNum = 0, void *depList = nullptr, int32_t - // noAliasDepNum = 0, void *noAliasDepList = nullptr. - OffloadingArgs.push_back(CGF.Builder.getInt32(0)); - OffloadingArgs.push_back(llvm::ConstantPointerNull::get(CGM.VoidPtrTy)); - OffloadingArgs.push_back(CGF.Builder.getInt32(0)); - OffloadingArgs.push_back(llvm::ConstantPointerNull::get(CGM.VoidPtrTy)); - } - Return = CGF.EmitRuntimeCall( - OMPBuilder.getOrCreateRuntimeFunction( - CGM.getModule(), HasNowait ? OMPRTL___tgt_target_nowait_mapper - : OMPRTL___tgt_target_mapper), - OffloadingArgs); - } - // Check the error code and execute the host version if required. + CGF.Builder.restoreIP( + HasNoWait ? OMPBuilder.emitTargetKernel( + CGF.Builder, Return, RTLoc, DeviceID, NumTeams, + NumThreads, OutlinedFnID, KernelArgs, NoWaitKernelArgs) + : OMPBuilder.emitTargetKernel(CGF.Builder, Return, RTLoc, + DeviceID, NumTeams, NumThreads, + OutlinedFnID, KernelArgs)); + llvm::BasicBlock *OffloadFailedBlock = CGF.createBasicBlock("omp_offload.failed"); llvm::BasicBlock *OffloadContBlock = diff --git a/contrib/llvm-project/clang/lib/CodeGen/CGOpenMPRuntime.h b/contrib/llvm-project/clang/lib/CodeGen/CGOpenMPRuntime.h index 7fc6a7e278e5..b95aef68335e 100644 --- a/contrib/llvm-project/clang/lib/CodeGen/CGOpenMPRuntime.h +++ b/contrib/llvm-project/clang/lib/CodeGen/CGOpenMPRuntime.h @@ -884,13 +884,11 @@ private: llvm::Function *TaskFunction, QualType SharedsTy, Address Shareds, const OMPTaskDataTy &Data); - /// Emit code that pushes the trip count of loops associated with constructs - /// 'target teams distribute' and 'teams distribute parallel for'. - /// \param SizeEmitter Emits the int64 value for the number of iterations of - /// the associated loop. - void emitTargetNumIterationsCall( + /// Return the trip count of loops associated with constructs / 'target teams + /// distribute' and 'teams distribute parallel for'. \param SizeEmitter Emits + /// the int64 value for the number of iterations of the associated loop. + llvm::Value *emitTargetNumIterationsCall( CodeGenFunction &CGF, const OMPExecutableDirective &D, - llvm::Value *DeviceID, llvm::function_ref SizeEmitter); diff --git a/contrib/llvm-project/clang/lib/CodeGen/CGStmtOpenMP.cpp b/contrib/llvm-project/clang/lib/CodeGen/CGStmtOpenMP.cpp index 301f5278df69..db0b2ffd3a4f 100644 --- a/contrib/llvm-project/clang/lib/CodeGen/CGStmtOpenMP.cpp +++ b/contrib/llvm-project/clang/lib/CodeGen/CGStmtOpenMP.cpp @@ -2591,11 +2591,12 @@ static void emitOMPSimdRegion(CodeGenFunction &CGF, const OMPLoopDirective &S, } } -static bool isSupportedByOpenMPIRBuilder(const OMPExecutableDirective &S) { +static bool isSupportedByOpenMPIRBuilder(const OMPSimdDirective &S) { // Check for unsupported clauses - if (!S.clauses().empty()) { - // Currently no clause is supported - return false; + for (OMPClause *C : S.clauses()) { + // Currently only simdlen clause is supported + if (!isa(C)) + return false; } // Check if we have a statement with the ordered directive. @@ -2630,7 +2631,6 @@ void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) { // Use the OpenMPIRBuilder if enabled. if (UseOMPIRBuilder) { // Emit the associated statement and get its loop representation. - llvm::DebugLoc DL = SourceLocToDebugLoc(S.getBeginLoc()); const Stmt *Inner = S.getRawStmt(); llvm::CanonicalLoopInfo *CLI = EmitOMPCollapsedCanonicalLoopNest(Inner, 1); @@ -2638,7 +2638,15 @@ void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) { llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder(); // Add SIMD specific metadata - OMPBuilder.applySimd(DL, CLI); + llvm::ConstantInt *Simdlen = nullptr; + if (const auto *C = S.getSingleClause()) { + RValue Len = + this->EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(), + /*ignoreResult=*/true); + auto *Val = cast(Len.getScalarVal()); + Simdlen = Val; + } + OMPBuilder.applySimd(CLI, Simdlen); return; } }; @@ -5998,18 +6006,26 @@ static std::pair emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X, RMWOp = llvm::AtomicRMWInst::Xor; break; case BO_LT: - RMWOp = X.getType()->hasSignedIntegerRepresentation() - ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min - : llvm::AtomicRMWInst::Max) - : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin - : llvm::AtomicRMWInst::UMax); + if (IsInteger) + RMWOp = X.getType()->hasSignedIntegerRepresentation() + ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min + : llvm::AtomicRMWInst::Max) + : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin + : llvm::AtomicRMWInst::UMax); + else + RMWOp = IsXLHSInRHSPart ? llvm::AtomicRMWInst::FMin + : llvm::AtomicRMWInst::FMax; break; case BO_GT: - RMWOp = X.getType()->hasSignedIntegerRepresentation() - ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max - : llvm::AtomicRMWInst::Min) - : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax - : llvm::AtomicRMWInst::UMin); + if (IsInteger) + RMWOp = X.getType()->hasSignedIntegerRepresentation() + ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max + : llvm::AtomicRMWInst::Min) + : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax + : llvm::AtomicRMWInst::UMin); + else + RMWOp = IsXLHSInRHSPart ? llvm::AtomicRMWInst::FMax + : llvm::AtomicRMWInst::FMin; break; case BO_Assign: RMWOp = llvm::AtomicRMWInst::Xchg; diff --git a/contrib/llvm-project/clang/lib/CodeGen/CodeGenFunction.cpp b/contrib/llvm-project/clang/lib/CodeGen/CodeGenFunction.cpp index 05942f462dd1..17c1c91c7e8f 100644 --- a/contrib/llvm-project/clang/lib/CodeGen/CodeGenFunction.cpp +++ b/contrib/llvm-project/clang/lib/CodeGen/CodeGenFunction.cpp @@ -898,6 +898,20 @@ void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy, if (D && D->hasAttr()) Fn->addFnAttr(llvm::Attribute::NoProfile); + if (D) { + // Function attributes take precedence over command line flags. + if (auto *A = D->getAttr()) { + switch (A->getThunkType()) { + case FunctionReturnThunksAttr::Kind::Keep: + break; + case FunctionReturnThunksAttr::Kind::Extern: + Fn->addFnAttr(llvm::Attribute::FnRetThunkExtern); + break; + } + } else if (CGM.getCodeGenOpts().FunctionReturnThunks) + Fn->addFnAttr(llvm::Attribute::FnRetThunkExtern); + } + if (FD && (getLangOpts().OpenCL || (getLangOpts().HIP && getLangOpts().CUDAIsDevice))) { // Add metadata for a kernel function. diff --git a/contrib/llvm-project/clang/lib/CodeGen/CodeGenModule.cpp b/contrib/llvm-project/clang/lib/CodeGen/CodeGenModule.cpp index 56ed59d1e3f1..c372bab1eccb 100644 --- a/contrib/llvm-project/clang/lib/CodeGen/CodeGenModule.cpp +++ b/contrib/llvm-project/clang/lib/CodeGen/CodeGenModule.cpp @@ -445,6 +445,7 @@ void CodeGenModule::checkAliases() { void CodeGenModule::clear() { DeferredDeclsToEmit.clear(); + EmittedDeferredDecls.clear(); if (OpenMPRuntime) OpenMPRuntime->clear(); } @@ -510,6 +511,9 @@ static void setVisibilityFromDLLStorageClass(const clang::LangOptions &LO, void CodeGenModule::Release() { EmitDeferred(); + DeferredDecls.insert(EmittedDeferredDecls.begin(), + EmittedDeferredDecls.end()); + EmittedDeferredDecls.clear(); EmitVTablesOpportunistically(); applyGlobalValReplacements(); applyReplacements(); @@ -900,6 +904,9 @@ void CodeGenModule::Release() { if (!getCodeGenOpts().StackProtectorGuardReg.empty()) getModule().setStackProtectorGuardReg( getCodeGenOpts().StackProtectorGuardReg); + if (!getCodeGenOpts().StackProtectorGuardSymbol.empty()) + getModule().setStackProtectorGuardSymbol( + getCodeGenOpts().StackProtectorGuardSymbol); if (getCodeGenOpts().StackProtectorGuardOffset != INT_MAX) getModule().setStackProtectorGuardOffset( getCodeGenOpts().StackProtectorGuardOffset); @@ -4286,6 +4293,9 @@ CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty, getCUDARuntime().handleVarRegistration(D, *GV); } + if (D) + SanitizerMD->reportGlobal(GV, *D); + LangAS ExpectedAS = D ? D->getType().getAddressSpace() : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default); diff --git a/contrib/llvm-project/clang/lib/CodeGen/CodeGenModule.h b/contrib/llvm-project/clang/lib/CodeGen/CodeGenModule.h index da43b9616c88..10b49da27dab 100644 --- a/contrib/llvm-project/clang/lib/CodeGen/CodeGenModule.h +++ b/contrib/llvm-project/clang/lib/CodeGen/CodeGenModule.h @@ -344,6 +344,20 @@ private: std::vector DeferredDeclsToEmit; void addDeferredDeclToEmit(GlobalDecl GD) { DeferredDeclsToEmit.emplace_back(GD); + addEmittedDeferredDecl(GD); + } + + /// Decls that were DeferredDecls and have now been emitted. + llvm::DenseMap EmittedDeferredDecls; + + void addEmittedDeferredDecl(GlobalDecl GD) { + if (!llvm::isa(GD.getDecl())) + return; + llvm::GlobalVariable::LinkageTypes L = getFunctionLinkage(GD); + if (llvm::GlobalValue::isLinkOnceLinkage(L) || + llvm::GlobalValue::isWeakLinkage(L)) { + EmittedDeferredDecls[getMangledName(GD)] = GD; + } } /// List of alias we have emitted. Used to make sure that what they point to @@ -1516,6 +1530,11 @@ public: NewBuilder->WeakRefReferences = std::move(WeakRefReferences); NewBuilder->TBAA = std::move(TBAA); + + assert(NewBuilder->EmittedDeferredDecls.empty() && + "Still have (unmerged) EmittedDeferredDecls deferred decls"); + + NewBuilder->EmittedDeferredDecls = std::move(EmittedDeferredDecls); } private: diff --git a/contrib/llvm-project/clang/lib/CodeGen/CodeGenTBAA.cpp b/contrib/llvm-project/clang/lib/CodeGen/CodeGenTBAA.cpp index 95763d8e18b7..0cb63fbbe9e5 100644 --- a/contrib/llvm-project/clang/lib/CodeGen/CodeGenTBAA.cpp +++ b/contrib/llvm-project/clang/lib/CodeGen/CodeGenTBAA.cpp @@ -335,7 +335,42 @@ llvm::MDNode *CodeGenTBAA::getBaseTypeInfoHelper(const Type *Ty) { if (auto *TTy = dyn_cast(Ty)) { const RecordDecl *RD = TTy->getDecl()->getDefinition(); const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); - SmallVector Fields; + using TBAAStructField = llvm::MDBuilder::TBAAStructField; + SmallVector Fields; + if (const CXXRecordDecl *CXXRD = dyn_cast(RD)) { + // Handle C++ base classes. Non-virtual bases can treated a a kind of + // field. Virtual bases are more complex and omitted, but avoid an + // incomplete view for NewStructPathTBAA. + if (CodeGenOpts.NewStructPathTBAA && CXXRD->getNumVBases() != 0) + return BaseTypeMetadataCache[Ty] = nullptr; + for (const CXXBaseSpecifier &B : CXXRD->bases()) { + if (B.isVirtual()) + continue; + QualType BaseQTy = B.getType(); + const CXXRecordDecl *BaseRD = BaseQTy->getAsCXXRecordDecl(); + if (BaseRD->isEmpty()) + continue; + llvm::MDNode *TypeNode = isValidBaseType(BaseQTy) + ? getBaseTypeInfo(BaseQTy) + : getTypeInfo(BaseQTy); + if (!TypeNode) + return BaseTypeMetadataCache[Ty] = nullptr; + uint64_t Offset = Layout.getBaseClassOffset(BaseRD).getQuantity(); + uint64_t Size = + Context.getASTRecordLayout(BaseRD).getDataSize().getQuantity(); + Fields.push_back( + llvm::MDBuilder::TBAAStructField(Offset, Size, TypeNode)); + } + // The order in which base class subobjects are allocated is unspecified, + // so may differ from declaration order. In particular, Itanium ABI will + // allocate a primary base first. + // Since we exclude empty subobjects, the objects are not overlapping and + // their offsets are unique. + llvm::sort(Fields, + [](const TBAAStructField &A, const TBAAStructField &B) { + return A.Offset < B.Offset; + }); + } for (FieldDecl *Field : RD->fields()) { if (Field->isZeroSize(Context) || Field->isUnnamedBitfield()) continue; diff --git a/contrib/llvm-project/clang/lib/CodeGen/SanitizerMetadata.cpp b/contrib/llvm-project/clang/lib/CodeGen/SanitizerMetadata.cpp index 5f4eb9be981f..7848cf012633 100644 --- a/contrib/llvm-project/clang/lib/CodeGen/SanitizerMetadata.cpp +++ b/contrib/llvm-project/clang/lib/CodeGen/SanitizerMetadata.cpp @@ -60,17 +60,17 @@ void SanitizerMetadata::reportGlobal(llvm::GlobalVariable *GV, Meta.NoHWAddress |= CGM.isInNoSanitizeList( FsanitizeArgument.Mask & SanitizerKind::HWAddress, GV, Loc, Ty); - Meta.NoMemtag |= NoSanitizeAttrSet.hasOneOf(SanitizerKind::MemTag); - Meta.NoMemtag |= CGM.isInNoSanitizeList( + Meta.Memtag |= + static_cast(FsanitizeArgument.Mask & SanitizerKind::MemtagGlobals); + Meta.Memtag &= !NoSanitizeAttrSet.hasOneOf(SanitizerKind::MemTag); + Meta.Memtag &= !CGM.isInNoSanitizeList( FsanitizeArgument.Mask & SanitizerKind::MemTag, GV, Loc, Ty); - if (FsanitizeArgument.has(SanitizerKind::Address)) { - // TODO(hctim): Make this conditional when we migrate off llvm.asan.globals. - IsDynInit &= !CGM.isInNoSanitizeList(SanitizerKind::Address | - SanitizerKind::KernelAddress, - GV, Loc, Ty, "init"); - Meta.IsDynInit = IsDynInit; - } + Meta.IsDynInit = IsDynInit && !Meta.NoAddress && + FsanitizeArgument.has(SanitizerKind::Address) && + !CGM.isInNoSanitizeList(SanitizerKind::Address | + SanitizerKind::KernelAddress, + GV, Loc, Ty, "init"); GV->setSanitizerMetadata(Meta); } diff --git a/contrib/llvm-project/clang/lib/Driver/Driver.cpp b/contrib/llvm-project/clang/lib/Driver/Driver.cpp index 0da32dae2ef6..3a8400a55741 100644 --- a/contrib/llvm-project/clang/lib/Driver/Driver.cpp +++ b/contrib/llvm-project/clang/lib/Driver/Driver.cpp @@ -2930,7 +2930,7 @@ class OffloadingActionBuilder final { return false; Relocatable = Args.hasFlag(options::OPT_fgpu_rdc, - options::OPT_fno_gpu_rdc, /*Default=*/false); + options::OPT_fno_gpu_rdc, /*Default=*/false); const ToolChain *HostTC = C.getSingleOffloadToolChain(); assert(HostTC && "No toolchain for host compilation."); @@ -3326,7 +3326,7 @@ class OffloadingActionBuilder final { AssociatedOffloadKind); if (CompileDeviceOnly && CurPhase == FinalPhase && BundleOutput && - BundleOutput.getValue()) { + BundleOutput.value()) { for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) { OffloadAction::DeviceDependences DDep; DDep.add(*CudaDeviceActions[I], *ToolChains.front(), GpuArchList[I], @@ -4355,7 +4355,17 @@ Driver::getOffloadArchs(Compilation &C, const llvm::opt::DerivedArgList &Args, return KnownArchs.lookup(TC); llvm::DenseSet Archs; - for (auto &Arg : Args) { + for (auto *Arg : Args) { + // Extract any '--[no-]offload-arch' arguments intended for this toolchain. + std::unique_ptr ExtractedArg = nullptr; + if (Arg->getOption().matches(options::OPT_Xopenmp_target_EQ) && + ToolChain::getOpenMPTriple(Arg->getValue(0)) == TC->getTriple()) { + Arg->claim(); + unsigned Index = Args.getBaseArgs().MakeIndex(Arg->getValue(1)); + ExtractedArg = getOpts().ParseOneArg(Args, Index); + Arg = ExtractedArg.get(); + } + if (Arg->getOption().matches(options::OPT_offload_arch_EQ)) { for (StringRef Arch : llvm::split(Arg->getValue(), ",")) Archs.insert(getCanonicalArchString(C, Args, Arch, TC->getTriple())); @@ -4425,8 +4435,7 @@ Action *Driver::BuildOffloadingActions(Compilation &C, // Get the product of all bound architectures and toolchains. SmallVector> TCAndArchs; for (const ToolChain *TC : ToolChains) - for (StringRef Arch : getOffloadArchs( - C, C.getArgsForToolChain(TC, "generic", Kind), Kind, TC)) + for (StringRef Arch : getOffloadArchs(C, Args, Kind, TC)) TCAndArchs.push_back(std::make_pair(TC, Arch)); for (unsigned I = 0, E = TCAndArchs.size(); I != E; ++I) @@ -4477,11 +4486,23 @@ Action *Driver::BuildOffloadingActions(Compilation &C, if (offloadDeviceOnly()) return C.MakeAction(DDeps, types::TY_Nothing); - Action *OffloadPackager = - C.MakeAction(OffloadActions, types::TY_Image); OffloadAction::DeviceDependences DDep; - DDep.add(*OffloadPackager, *C.getSingleOffloadToolChain(), - nullptr, Action::OFK_None); + if (C.isOffloadingHostKind(Action::OFK_Cuda) && + !Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false)) { + // If we are not in RDC-mode we just emit the final CUDA fatbinary for each + // translation unit without requiring any linking. + Action *FatbinAction = + C.MakeAction(OffloadActions, types::TY_CUDA_FATBIN); + DDep.add(*FatbinAction, *C.getSingleOffloadToolChain(), + nullptr, Action::OFK_Cuda); + } else { + // Package all the offloading actions into a single output that can be + // embedded in the host and linked. + Action *PackagerAction = + C.MakeAction(OffloadActions, types::TY_Image); + DDep.add(*PackagerAction, *C.getSingleOffloadToolChain(), + nullptr, Action::OFK_None); + } OffloadAction::HostDependence HDep( *HostAction, *C.getSingleOffloadToolChain(), /*BoundArch=*/nullptr, isa(HostAction) ? DDep : DDeps); diff --git a/contrib/llvm-project/clang/lib/Driver/ToolChains/AVR.cpp b/contrib/llvm-project/clang/lib/Driver/ToolChains/AVR.cpp index 1e866553d826..89d408823270 100644 --- a/contrib/llvm-project/clang/lib/Driver/ToolChains/AVR.cpp +++ b/contrib/llvm-project/clang/lib/Driver/ToolChains/AVR.cpp @@ -437,7 +437,6 @@ void AVR::Linker::ConstructJob(Compilation &C, const JobAction &JA, : getToolChain().GetProgramPath(getShortName()); ArgStringList CmdArgs; - AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA); CmdArgs.push_back("-o"); CmdArgs.push_back(Output.getFilename()); @@ -476,8 +475,8 @@ void AVR::Linker::ConstructJob(Compilation &C, const JobAction &JA, } if (SectionAddressData) { - std::string DataSectionArg = std::string("-Tdata=0x") + - llvm::utohexstr(SectionAddressData.getValue()); + std::string DataSectionArg = + std::string("-Tdata=0x") + llvm::utohexstr(SectionAddressData.value()); CmdArgs.push_back(Args.MakeArgString(DataSectionArg)); } else { // We do not have an entry for this CPU in the address mapping table yet. @@ -503,6 +502,7 @@ void AVR::Linker::ConstructJob(Compilation &C, const JobAction &JA, // Add the link library specific to the MCU. CmdArgs.push_back(Args.MakeArgString(std::string("-l") + CPU)); + AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA); CmdArgs.push_back("--end-group"); // Add user specified linker script. @@ -514,6 +514,8 @@ void AVR::Linker::ConstructJob(Compilation &C, const JobAction &JA, // than the bare minimum supports. if (Linker.find("avr-ld") != std::string::npos) CmdArgs.push_back(Args.MakeArgString(std::string("-m") + *FamilyName)); + } else { + AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA); } C.addCommand(std::make_unique( diff --git a/contrib/llvm-project/clang/lib/Driver/ToolChains/Clang.cpp b/contrib/llvm-project/clang/lib/Driver/ToolChains/Clang.cpp index c9bbdb2ac72e..97435f1a73de 100644 --- a/contrib/llvm-project/clang/lib/Driver/ToolChains/Clang.cpp +++ b/contrib/llvm-project/clang/lib/Driver/ToolChains/Clang.cpp @@ -27,6 +27,7 @@ #include "clang/Basic/CharInfo.h" #include "clang/Basic/CodeGenOptions.h" #include "clang/Basic/LangOptions.h" +#include "clang/Basic/MakeSupport.h" #include "clang/Basic/ObjCRuntime.h" #include "clang/Basic/Version.h" #include "clang/Config/config.h" @@ -51,6 +52,7 @@ #include "llvm/Support/Process.h" #include "llvm/Support/TargetParser.h" #include "llvm/Support/YAMLParser.h" +#include using namespace clang::driver; using namespace clang::driver::tools; @@ -97,34 +99,6 @@ static void EscapeSpacesAndBackslashes(const char *Arg, } } -// Quote target names for inclusion in GNU Make dependency files. -// Only the characters '$', '#', ' ', '\t' are quoted. -static void QuoteTarget(StringRef Target, SmallVectorImpl &Res) { - for (unsigned i = 0, e = Target.size(); i != e; ++i) { - switch (Target[i]) { - case ' ': - case '\t': - // Escape the preceding backslashes - for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j) - Res.push_back('\\'); - - // Escape the space/tab - Res.push_back('\\'); - break; - case '$': - Res.push_back('$'); - break; - case '#': - Res.push_back('\\'); - break; - default: - break; - } - - Res.push_back(Target[i]); - } -} - /// Apply \a Work on the current tool chain \a RegularToolChain and any other /// offloading tool chain that is associated with the current action \a JA. static void @@ -567,7 +541,7 @@ static bool useFramePointerForTargetByDefault(const ArgList &Args, break; } - if (Triple.isOSNetBSD()) { + if (Triple.isOSFuchsia() || Triple.isOSNetBSD()) { return !areOptimizationsEnabled(Args); } @@ -1144,7 +1118,7 @@ static void RenderDebugInfoCompressionArgs(const ArgList &Args, if (Value == "none") { CmdArgs.push_back("--compress-debug-sections=none"); } else if (Value == "zlib") { - if (llvm::zlib::isAvailable()) { + if (llvm::compression::zlib::isAvailable()) { CmdArgs.push_back( Args.MakeArgString("--compress-debug-sections=" + Twine(Value))); } else { @@ -1249,7 +1223,7 @@ void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA, } else { CmdArgs.push_back("-MT"); SmallString<128> Quoted; - QuoteTarget(A->getValue(), Quoted); + quoteMakeTarget(A->getValue(), Quoted); CmdArgs.push_back(Args.MakeArgString(Quoted)); } } @@ -1274,7 +1248,7 @@ void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA, CmdArgs.push_back("-MT"); SmallString<128> Quoted; - QuoteTarget(DepTarget, Quoted); + quoteMakeTarget(DepTarget, Quoted); CmdArgs.push_back(Args.MakeArgString(Quoted)); } @@ -2228,8 +2202,23 @@ void Clang::AddSparcTargetArgs(const ArgList &Args, void Clang::AddSystemZTargetArgs(const ArgList &Args, ArgStringList &CmdArgs) const { - bool HasBackchain = Args.hasFlag(options::OPT_mbackchain, - options::OPT_mno_backchain, false); + if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) { + StringRef Name = A->getValue(); + + std::string TuneCPU; + if (Name == "native") + TuneCPU = std::string(llvm::sys::getHostCPUName()); + else + TuneCPU = std::string(Name); + + if (!TuneCPU.empty()) { + CmdArgs.push_back("-tune-cpu"); + CmdArgs.push_back(Args.MakeArgString(TuneCPU)); + } + } + + bool HasBackchain = + Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false); bool HasPackedStack = Args.hasFlag(options::OPT_mpacked_stack, options::OPT_mno_packed_stack, false); systemz::FloatABI FloatABI = @@ -2341,7 +2330,7 @@ void Clang::AddHexagonTargetArgs(const ArgList &Args, if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) { CmdArgs.push_back("-mllvm"); CmdArgs.push_back(Args.MakeArgString("-hexagon-small-data-threshold=" + - Twine(G.getValue()))); + Twine(G.value()))); } if (!Args.hasArg(options::OPT_fno_short_enums)) @@ -3231,6 +3220,16 @@ static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs, Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer); } +static bool isValidSymbolName(StringRef S) { + if (S.empty()) + return false; + + if (std::isdigit(S[0])) + return false; + + return llvm::all_of(S, [](char C) { return std::isalnum(C) || C == '_'; }); +} + static void RenderSSPOptions(const Driver &D, const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs, bool KernelOrKext) { @@ -3362,6 +3361,16 @@ static void RenderSSPOptions(const Driver &D, const ToolChain &TC, } A->render(Args, CmdArgs); } + + if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_symbol_EQ)) { + StringRef Value = A->getValue(); + if (!isValidSymbolName(Value)) { + D.Diag(diag::err_drv_argument_only_allowed_with) + << A->getOption().getName() << "legal symbol name"; + return; + } + A->render(Args, CmdArgs); + } } static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args, @@ -3750,38 +3759,49 @@ static void RenderModulesOptions(Compilation &C, const Driver &D, Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval); Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after); - Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp); + if (HaveClangModules) { + Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp); - if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) { - if (Args.hasArg(options::OPT_fbuild_session_timestamp)) - D.Diag(diag::err_drv_argument_not_allowed_with) - << A->getAsString(Args) << "-fbuild-session-timestamp"; + if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) { + if (Args.hasArg(options::OPT_fbuild_session_timestamp)) + D.Diag(diag::err_drv_argument_not_allowed_with) + << A->getAsString(Args) << "-fbuild-session-timestamp"; - llvm::sys::fs::file_status Status; - if (llvm::sys::fs::status(A->getValue(), Status)) - D.Diag(diag::err_drv_no_such_file) << A->getValue(); - CmdArgs.push_back(Args.MakeArgString( - "-fbuild-session-timestamp=" + - Twine((uint64_t)std::chrono::duration_cast( - Status.getLastModificationTime().time_since_epoch()) - .count()))); - } + llvm::sys::fs::file_status Status; + if (llvm::sys::fs::status(A->getValue(), Status)) + D.Diag(diag::err_drv_no_such_file) << A->getValue(); + CmdArgs.push_back(Args.MakeArgString( + "-fbuild-session-timestamp=" + + Twine((uint64_t)std::chrono::duration_cast( + Status.getLastModificationTime().time_since_epoch()) + .count()))); + } - if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) { - if (!Args.getLastArg(options::OPT_fbuild_session_timestamp, - options::OPT_fbuild_session_file)) - D.Diag(diag::err_drv_modules_validate_once_requires_timestamp); + if (Args.getLastArg( + options::OPT_fmodules_validate_once_per_build_session)) { + if (!Args.getLastArg(options::OPT_fbuild_session_timestamp, + options::OPT_fbuild_session_file)) + D.Diag(diag::err_drv_modules_validate_once_requires_timestamp); - Args.AddLastArg(CmdArgs, - options::OPT_fmodules_validate_once_per_build_session); - } + Args.AddLastArg(CmdArgs, + options::OPT_fmodules_validate_once_per_build_session); + } - if (Args.hasFlag(options::OPT_fmodules_validate_system_headers, - options::OPT_fno_modules_validate_system_headers, - ImplicitModules)) - CmdArgs.push_back("-fmodules-validate-system-headers"); + if (Args.hasFlag(options::OPT_fmodules_validate_system_headers, + options::OPT_fno_modules_validate_system_headers, + ImplicitModules)) + CmdArgs.push_back("-fmodules-validate-system-headers"); - Args.AddLastArg(CmdArgs, options::OPT_fmodules_disable_diagnostic_validation); + Args.AddLastArg(CmdArgs, + options::OPT_fmodules_disable_diagnostic_validation); + } else { + Args.ClaimAllArgs(options::OPT_fbuild_session_timestamp); + Args.ClaimAllArgs(options::OPT_fbuild_session_file); + Args.ClaimAllArgs(options::OPT_fmodules_validate_once_per_build_session); + Args.ClaimAllArgs(options::OPT_fmodules_validate_system_headers); + Args.ClaimAllArgs(options::OPT_fno_modules_validate_system_headers); + Args.ClaimAllArgs(options::OPT_fmodules_disable_diagnostic_validation); + } } static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T, @@ -4422,12 +4442,14 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA, Args.hasFlag(options::OPT_offload_new_driver, options::OPT_no_offload_new_driver, false)); + bool IsRDCMode = + Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false); bool IsUsingLTO = D.isUsingLTO(IsDeviceOffloadAction); auto LTOMode = D.getLTOMode(IsDeviceOffloadAction); // A header module compilation doesn't have a main input file, so invent a // fake one as a placeholder. - const char *ModuleName = [&]{ + const char *ModuleName = [&] { auto *ModuleNameArg = Args.getLastArg(options::OPT_fmodule_name_EQ); return ModuleNameArg ? ModuleNameArg->getValue() : ""; }(); @@ -6285,10 +6307,7 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA, } if (IsCuda || IsHIP) { - if (!Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false) && - Args.hasArg(options::OPT_offload_new_driver)) - D.Diag(diag::err_drv_no_rdc_new_driver); - if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false)) + if (IsRDCMode) CmdArgs.push_back("-fgpu-rdc"); if (Args.hasFlag(options::OPT_fgpu_defer_diag, options::OPT_fno_gpu_defer_diag, false)) @@ -6313,6 +6332,10 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA, if (IsUsingLTO) Args.AddLastArg(CmdArgs, options::OPT_mibt_seal); + if (Arg *A = Args.getLastArg(options::OPT_mfunction_return_EQ)) + CmdArgs.push_back( + Args.MakeArgString(Twine("-mfunction-return=") + A->getValue())); + // Forward -f options with positive and negative forms; we translate these by // hand. Do not propagate PGO options to the GPU-side compilations as the // profile info is for the host-side compilation only. @@ -6956,13 +6979,22 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA, } } - // Host-side cuda compilation receives all device-side outputs in a single - // fatbin as Inputs[1]. Include the binary with -fcuda-include-gpubinary. + // Host-side offloading compilation receives all device-side outputs. Include + // them in the host compilation depending on the target. If the host inputs + // are not empty we use the new-driver scheme, otherwise use the old scheme. if ((IsCuda || IsHIP) && CudaDeviceInput) { + CmdArgs.push_back("-fcuda-include-gpubinary"); + CmdArgs.push_back(CudaDeviceInput->getFilename()); + } else if (!HostOffloadingInputs.empty()) { + if (IsCuda && !IsRDCMode) { + assert(HostOffloadingInputs.size() == 1 && "Only one input expected"); CmdArgs.push_back("-fcuda-include-gpubinary"); - CmdArgs.push_back(CudaDeviceInput->getFilename()); - if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false)) - CmdArgs.push_back("-fgpu-rdc"); + CmdArgs.push_back(HostOffloadingInputs.front().getFilename()); + } else { + for (const InputInfo Input : HostOffloadingInputs) + CmdArgs.push_back(Args.MakeArgString("-fembed-offload-object=" + + TC.getInputFilename(Input))); + } } if (IsCuda) { @@ -7011,12 +7043,6 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA, } } - // Host-side offloading recieves the device object files and embeds it in a - // named section including the associated target triple and architecture. - for (const InputInfo Input : HostOffloadingInputs) - CmdArgs.push_back(Args.MakeArgString("-fembed-offload-object=" + - TC.getInputFilename(Input))); - if (Triple.isAMDGPU()) { handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs); @@ -8314,7 +8340,8 @@ void OffloadPackager::ConstructJob(Compilation &C, const JobAction &JA, ArgStringList Features; SmallVector FeatureArgs; - getTargetFeatures(TC->getDriver(), TC->getTriple(), Args, Features, false); + getTargetFeatures(TC->getDriver(), TC->getTriple(), TCArgs, Features, + false); llvm::copy_if(Features, std::back_inserter(FeatureArgs), [](StringRef Arg) { return !Arg.startswith("-target"); }); @@ -8382,7 +8409,7 @@ void LinkerWrapper::ConstructJob(Compilation &C, const JobAction &JA, for (StringRef LibName : BCLibs) CmdArgs.push_back(Args.MakeArgString( - "-target-library=" + Action::GetOffloadKindName(Action::OFK_OpenMP) + + "--bitcode-library=" + Action::GetOffloadKindName(Action::OFK_OpenMP) + "-" + TC->getTripleString() + "-" + Arch + "=" + LibName)); } @@ -8402,63 +8429,64 @@ void LinkerWrapper::ConstructJob(Compilation &C, const JobAction &JA, } else if (A->getOption().matches(options::OPT_O0)) OOpt = "0"; if (!OOpt.empty()) - CmdArgs.push_back(Args.MakeArgString(Twine("-opt-level=O") + OOpt)); + CmdArgs.push_back(Args.MakeArgString(Twine("--opt-level=O") + OOpt)); } } - CmdArgs.push_back("-host-triple"); - CmdArgs.push_back(Args.MakeArgString(TheTriple.getTriple())); + CmdArgs.push_back( + Args.MakeArgString("--host-triple=" + TheTriple.getTriple())); if (Args.hasArg(options::OPT_v)) - CmdArgs.push_back("-v"); + CmdArgs.push_back("--verbose"); - // Add debug information if present. if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) { - const Option &Opt = A->getOption(); - if (Opt.matches(options::OPT_gN_Group)) { - if (Opt.matches(options::OPT_gline_directives_only) || - Opt.matches(options::OPT_gline_tables_only)) - CmdArgs.push_back("-gline-directives-only"); - } else - CmdArgs.push_back("-g"); + if (!A->getOption().matches(options::OPT_g0)) + CmdArgs.push_back("--device-debug"); } for (const auto &A : Args.getAllArgValues(options::OPT_Xcuda_ptxas)) - CmdArgs.push_back(Args.MakeArgString("-ptxas-args=" + A)); + CmdArgs.push_back(Args.MakeArgString("--ptxas-args=" + A)); // Forward remarks passes to the LLVM backend in the wrapper. if (const Arg *A = Args.getLastArg(options::OPT_Rpass_EQ)) CmdArgs.push_back( - Args.MakeArgString(Twine("-pass-remarks=") + A->getValue())); + Args.MakeArgString(Twine("--pass-remarks=") + A->getValue())); if (const Arg *A = Args.getLastArg(options::OPT_Rpass_missed_EQ)) CmdArgs.push_back( - Args.MakeArgString(Twine("-pass-remarks-missed=") + A->getValue())); + Args.MakeArgString(Twine("--pass-remarks-missed=") + A->getValue())); if (const Arg *A = Args.getLastArg(options::OPT_Rpass_analysis_EQ)) CmdArgs.push_back( - Args.MakeArgString(Twine("-pass-remarks-analysis=") + A->getValue())); + Args.MakeArgString(Twine("--pass-remarks-analysis=") + A->getValue())); if (Args.getLastArg(options::OPT_save_temps_EQ)) - CmdArgs.push_back("-save-temps"); + CmdArgs.push_back("--save-temps"); // Construct the link job so we can wrap around it. Linker->ConstructJob(C, JA, Output, Inputs, Args, LinkingOutput); const auto &LinkCommand = C.getJobs().getJobs().back(); // Forward -Xoffload-linker<-triple> arguments to the device link job. - for (auto *Arg : Args.filtered(options::OPT_Xoffload_linker)) { - StringRef Val = Arg->getValue(0); + for (Arg *A : Args.filtered(options::OPT_Xoffload_linker)) { + StringRef Val = A->getValue(0); if (Val.empty()) CmdArgs.push_back( - Args.MakeArgString(Twine("-device-linker=") + Arg->getValue(1))); + Args.MakeArgString(Twine("--device-linker=") + A->getValue(1))); else CmdArgs.push_back(Args.MakeArgString( - "-device-linker=" + + "--device-linker=" + ToolChain::getOpenMPTriple(Val.drop_front()).getTriple() + "=" + - Arg->getValue(1))); + A->getValue(1))); } Args.ClaimAllArgs(options::OPT_Xoffload_linker); + // Forward `-mllvm` arguments to the LLVM invocations if present. + for (Arg *A : Args.filtered(options::OPT_mllvm)) { + CmdArgs.push_back("-mllvm"); + CmdArgs.push_back(A->getValue()); + A->claim(); + } + // Add the linker arguments to be forwarded by the wrapper. - CmdArgs.push_back("-linker-path"); - CmdArgs.push_back(LinkCommand->getExecutable()); + CmdArgs.push_back(Args.MakeArgString(Twine("--linker-path=") + + LinkCommand->getExecutable())); CmdArgs.push_back("--"); for (const char *LinkArg : LinkCommand->getArguments()) CmdArgs.push_back(LinkArg); diff --git a/contrib/llvm-project/clang/lib/Driver/ToolChains/CommonArgs.cpp b/contrib/llvm-project/clang/lib/Driver/ToolChains/CommonArgs.cpp index 2d53b829b01c..1d2c085d683e 100644 --- a/contrib/llvm-project/clang/lib/Driver/ToolChains/CommonArgs.cpp +++ b/contrib/llvm-project/clang/lib/Driver/ToolChains/CommonArgs.cpp @@ -727,7 +727,8 @@ bool tools::addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC, if (IsOffloadingHost) CmdArgs.push_back("-lomptarget"); - if (IsOffloadingHost && TC.getDriver().isUsingLTO(/* IsOffload */ true)) + if (IsOffloadingHost && TC.getDriver().isUsingLTO(/* IsOffload */ true) && + !Args.hasArg(options::OPT_nogpulib)) CmdArgs.push_back("-lomptarget.devicertl"); addArchSpecificRPath(TC, Args, CmdArgs); diff --git a/contrib/llvm-project/clang/lib/Driver/ToolChains/Darwin.cpp b/contrib/llvm-project/clang/lib/Driver/ToolChains/Darwin.cpp index 0a8a9c6eb6ff..c9e773701ac3 100644 --- a/contrib/llvm-project/clang/lib/Driver/ToolChains/Darwin.cpp +++ b/contrib/llvm-project/clang/lib/Driver/ToolChains/Darwin.cpp @@ -1551,10 +1551,10 @@ struct DarwinPlatform { options::ID Opt; switch (Platform) { case DarwinPlatformKind::MacOS: - Opt = options::OPT_mmacosx_version_min_EQ; + Opt = options::OPT_mmacos_version_min_EQ; break; case DarwinPlatformKind::IPhoneOS: - Opt = options::OPT_miphoneos_version_min_EQ; + Opt = options::OPT_mios_version_min_EQ; break; case DarwinPlatformKind::TvOS: Opt = options::OPT_mtvos_version_min_EQ; @@ -1727,8 +1727,8 @@ private: Optional getDeploymentTargetFromOSVersionArg(DerivedArgList &Args, const Driver &TheDriver) { - Arg *OSXVersion = Args.getLastArg(options::OPT_mmacosx_version_min_EQ); - Arg *iOSVersion = Args.getLastArg(options::OPT_miphoneos_version_min_EQ, + Arg *macOSVersion = Args.getLastArg(options::OPT_mmacos_version_min_EQ); + Arg *iOSVersion = Args.getLastArg(options::OPT_mios_version_min_EQ, options::OPT_mios_simulator_version_min_EQ); Arg *TvOSVersion = Args.getLastArg(options::OPT_mtvos_version_min_EQ, @@ -1736,15 +1736,15 @@ getDeploymentTargetFromOSVersionArg(DerivedArgList &Args, Arg *WatchOSVersion = Args.getLastArg(options::OPT_mwatchos_version_min_EQ, options::OPT_mwatchos_simulator_version_min_EQ); - if (OSXVersion) { + if (macOSVersion) { if (iOSVersion || TvOSVersion || WatchOSVersion) { TheDriver.Diag(diag::err_drv_argument_not_allowed_with) - << OSXVersion->getAsString(Args) + << macOSVersion->getAsString(Args) << (iOSVersion ? iOSVersion : TvOSVersion ? TvOSVersion : WatchOSVersion) ->getAsString(Args); } - return DarwinPlatform::createOSVersionArg(Darwin::MacOS, OSXVersion); + return DarwinPlatform::createOSVersionArg(Darwin::MacOS, macOSVersion); } else if (iOSVersion) { if (TvOSVersion || WatchOSVersion) { TheDriver.Diag(diag::err_drv_argument_not_allowed_with) diff --git a/contrib/llvm-project/clang/lib/Driver/ToolChains/Gnu.cpp b/contrib/llvm-project/clang/lib/Driver/ToolChains/Gnu.cpp index f52bb8af5ec9..34396b0b59c2 100644 --- a/contrib/llvm-project/clang/lib/Driver/ToolChains/Gnu.cpp +++ b/contrib/llvm-project/clang/lib/Driver/ToolChains/Gnu.cpp @@ -2087,7 +2087,7 @@ void Generic_GCC::GCCInstallationDetector::print(raw_ostream &OS) const { bool Generic_GCC::GCCInstallationDetector::getBiarchSibling(Multilib &M) const { if (BiarchSibling) { - M = BiarchSibling.getValue(); + M = BiarchSibling.value(); return true; } return false; diff --git a/contrib/llvm-project/clang/lib/Driver/ToolChains/Hexagon.cpp b/contrib/llvm-project/clang/lib/Driver/ToolChains/Hexagon.cpp index 9142dba81d54..ed07e710fc49 100644 --- a/contrib/llvm-project/clang/lib/Driver/ToolChains/Hexagon.cpp +++ b/contrib/llvm-project/clang/lib/Driver/ToolChains/Hexagon.cpp @@ -340,8 +340,8 @@ constructHexagonLinkArgs(Compilation &C, const JobAction &JA, CmdArgs.push_back("-pie"); if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) { - CmdArgs.push_back(Args.MakeArgString("-G" + Twine(G.getValue()))); - UseG0 = G.getValue() == 0; + CmdArgs.push_back(Args.MakeArgString("-G" + Twine(G.value()))); + UseG0 = G.value() == 0; } CmdArgs.push_back("-o"); diff --git a/contrib/llvm-project/clang/lib/Driver/ToolChains/MinGW.cpp b/contrib/llvm-project/clang/lib/Driver/ToolChains/MinGW.cpp index c4b4f8e9b89b..ae7c4c56bf9e 100644 --- a/contrib/llvm-project/clang/lib/Driver/ToolChains/MinGW.cpp +++ b/contrib/llvm-project/clang/lib/Driver/ToolChains/MinGW.cpp @@ -339,8 +339,9 @@ void tools::MinGW::Linker::ConstructJob(Compilation &C, const JobAction &JA, // Simplified from Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple. static bool findGccVersion(StringRef LibDir, std::string &GccLibDir, - std::string &Ver) { - auto Version = toolchains::Generic_GCC::GCCVersion::Parse("0.0.0"); + std::string &Ver, + toolchains::Generic_GCC::GCCVersion &Version) { + Version = toolchains::Generic_GCC::GCCVersion::Parse("0.0.0"); std::error_code EC; for (llvm::sys::fs::directory_iterator LI(LibDir, EC), LE; !EC && LI != LE; LI = LI.increment(EC)) { @@ -371,7 +372,7 @@ void toolchains::MinGW::findGccLibDir() { for (StringRef CandidateSysroot : SubdirNames) { llvm::SmallString<1024> LibDir(Base); llvm::sys::path::append(LibDir, CandidateLib, "gcc", CandidateSysroot); - if (findGccVersion(LibDir, GccLibDir, Ver)) { + if (findGccVersion(LibDir, GccLibDir, Ver, GccVer)) { SubdirName = std::string(CandidateSysroot); return; } @@ -438,6 +439,11 @@ toolchains::MinGW::MinGW(const Driver &D, const llvm::Triple &Triple, getFilePaths().push_back(GccLibDir); getFilePaths().push_back( (Base + SubdirName + llvm::sys::path::get_separator() + "lib").str()); + + // Gentoo + getFilePaths().push_back( + (Base + SubdirName + llvm::sys::path::get_separator() + "mingw/lib").str()); + getFilePaths().push_back(Base + "lib"); // openSUSE getFilePaths().push_back(Base + SubdirName + "/sys-root/mingw/lib"); @@ -593,6 +599,11 @@ void toolchains::MinGW::AddClangSystemIncludeArgs(const ArgList &DriverArgs, addSystemInclude(DriverArgs, CC1Args, Base + SubdirName + llvm::sys::path::get_separator() + "include"); + + // Gentoo + addSystemInclude(DriverArgs, CC1Args, + Base + SubdirName + llvm::sys::path::get_separator() + "usr/include"); + addSystemInclude(DriverArgs, CC1Args, Base + "include"); } @@ -620,7 +631,7 @@ void toolchains::MinGW::AddClangCXXStdlibIncludeArgs( } case ToolChain::CST_Libstdcxx: - llvm::SmallVector, 4> CppIncludeBases; + llvm::SmallVector, 7> CppIncludeBases; CppIncludeBases.emplace_back(Base); llvm::sys::path::append(CppIncludeBases[0], SubdirName, "include", "c++"); CppIncludeBases.emplace_back(Base); @@ -630,6 +641,15 @@ void toolchains::MinGW::AddClangCXXStdlibIncludeArgs( llvm::sys::path::append(CppIncludeBases[2], "include", "c++", Ver); CppIncludeBases.emplace_back(GccLibDir); llvm::sys::path::append(CppIncludeBases[3], "include", "c++"); + CppIncludeBases.emplace_back(GccLibDir); + llvm::sys::path::append(CppIncludeBases[4], "include", + "g++-v" + GccVer.Text); + CppIncludeBases.emplace_back(GccLibDir); + llvm::sys::path::append(CppIncludeBases[5], "include", + "g++-v" + GccVer.MajorStr + "." + GccVer.MinorStr); + CppIncludeBases.emplace_back(GccLibDir); + llvm::sys::path::append(CppIncludeBases[6], "include", + "g++-v" + GccVer.MajorStr); for (auto &CppIncludeBase : CppIncludeBases) { addSystemInclude(DriverArgs, CC1Args, CppIncludeBase); CppIncludeBase += Slash; diff --git a/contrib/llvm-project/clang/lib/Driver/ToolChains/MinGW.h b/contrib/llvm-project/clang/lib/Driver/ToolChains/MinGW.h index c9553b4f4652..f15f99dc8a8c 100644 --- a/contrib/llvm-project/clang/lib/Driver/ToolChains/MinGW.h +++ b/contrib/llvm-project/clang/lib/Driver/ToolChains/MinGW.h @@ -103,6 +103,7 @@ private: std::string Base; std::string GccLibDir; + clang::driver::toolchains::Generic_GCC::GCCVersion GccVer; std::string Ver; std::string SubdirName; mutable std::unique_ptr Preprocessor; diff --git a/contrib/llvm-project/clang/lib/Driver/ToolChains/RISCVToolchain.cpp b/contrib/llvm-project/clang/lib/Driver/ToolChains/RISCVToolchain.cpp index a048765bc6d3..3491de22d371 100644 --- a/contrib/llvm-project/clang/lib/Driver/ToolChains/RISCVToolchain.cpp +++ b/contrib/llvm-project/clang/lib/Driver/ToolChains/RISCVToolchain.cpp @@ -201,8 +201,11 @@ void RISCV::Linker::ConstructJob(Compilation &C, const JobAction &JA, if (!Args.hasArg(options::OPT_nostdlib) && !Args.hasArg(options::OPT_nodefaultlibs)) { - if (ToolChain.ShouldLinkCXXStdlib(Args)) - ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs); + if (D.CCCIsCXX()) { + if (ToolChain.ShouldLinkCXXStdlib(Args)) + ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs); + CmdArgs.push_back("-lm"); + } CmdArgs.push_back("--start-group"); CmdArgs.push_back("-lc"); CmdArgs.push_back("-lgloss"); diff --git a/contrib/llvm-project/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp b/contrib/llvm-project/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp index c4797cea333f..709b781968bf 100644 --- a/contrib/llvm-project/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp +++ b/contrib/llvm-project/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp @@ -31,14 +31,14 @@ namespace { /// at position \p Key. void serializeObject(Object &Paren, StringRef Key, Optional Obj) { if (Obj) - Paren[Key] = std::move(Obj.getValue()); + Paren[Key] = std::move(Obj.value()); } /// Helper function to inject a JSON array \p Array into object \p Paren at /// position \p Key. void serializeArray(Object &Paren, StringRef Key, Optional Array) { if (Array) - Paren[Key] = std::move(Array.getValue()); + Paren[Key] = std::move(Array.value()); } /// Serialize a \c VersionTuple \p V with the Symbol Graph semantic version diff --git a/contrib/llvm-project/clang/lib/Format/ContinuationIndenter.cpp b/contrib/llvm-project/clang/lib/Format/ContinuationIndenter.cpp index 2cb985cdc4e5..1cd28ab073da 100644 --- a/contrib/llvm-project/clang/lib/Format/ContinuationIndenter.cpp +++ b/contrib/llvm-project/clang/lib/Format/ContinuationIndenter.cpp @@ -37,7 +37,7 @@ static bool shouldIndentWrappedSelectorName(const FormatStyle &Style, // Returns the length of everything up to the first possible line break after // the ), ], } or > matching \c Tok. static unsigned getLengthToMatchingParen(const FormatToken &Tok, - const std::vector &Stack) { + const SmallVector &Stack) { // Normally whether or not a break before T is possible is calculated and // stored in T.CanBreakBefore. Braces, array initializers and text proto // messages like `key: < ... >` are an exception: a break is possible @@ -404,6 +404,7 @@ bool ContinuationIndenter::mustBreak(const LineState &State) { (State.Column + State.Line->Last->TotalLength - Previous.TotalLength > getColumnLimit(State) || CurrentState.BreakBeforeParameter) && + (!Current.isTrailingComment() || Current.NewlinesBefore > 0) && (Style.AllowShortFunctionsOnASingleLine != FormatStyle::SFS_All || Style.BreakConstructorInitializers != FormatStyle::BCIS_BeforeColon || Style.ColumnLimit != 0)) { @@ -793,6 +794,7 @@ void ContinuationIndenter::addTokenOnCurrentLine(LineState &State, bool DryRun, (Previous.is(tok::colon) && Previous.is(TT_ObjCMethodExpr)))) { CurrentState.LastSpace = State.Column; } else if (Previous.is(TT_CtorInitializerColon) && + (!Current.isTrailingComment() || Current.NewlinesBefore > 0) && Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon) { CurrentState.Indent = State.Column; @@ -1032,7 +1034,7 @@ unsigned ContinuationIndenter::addTokenOnNewLine(LineState &State, // be considered bin packing unless the relevant AllowAll option is false or // this is a dict/object literal. bool PreviousIsBreakingCtorInitializerColon = - Previous.is(TT_CtorInitializerColon) && + PreviousNonComment && PreviousNonComment->is(TT_CtorInitializerColon) && Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon; if (!(Previous.isOneOf(tok::l_paren, tok::l_brace, TT_BinaryOperator) || PreviousIsBreakingCtorInitializerColon) || diff --git a/contrib/llvm-project/clang/lib/Format/ContinuationIndenter.h b/contrib/llvm-project/clang/lib/Format/ContinuationIndenter.h index 494a9727d5ed..620060e68861 100644 --- a/contrib/llvm-project/clang/lib/Format/ContinuationIndenter.h +++ b/contrib/llvm-project/clang/lib/Format/ContinuationIndenter.h @@ -434,7 +434,7 @@ struct LineState { /// A stack keeping track of properties applying to parenthesis /// levels. - std::vector Stack; + SmallVector Stack; /// Ignore the stack of \c ParenStates for state comparison. /// diff --git a/contrib/llvm-project/clang/lib/Format/Format.cpp b/contrib/llvm-project/clang/lib/Format/Format.cpp index 51526dc2a681..d13907faca43 100644 --- a/contrib/llvm-project/clang/lib/Format/Format.cpp +++ b/contrib/llvm-project/clang/lib/Format/Format.cpp @@ -2386,7 +2386,7 @@ private: tooling::Replacements generateFixes() { tooling::Replacements Fixes; - std::vector Tokens; + SmallVector Tokens; std::copy(DeletedTokens.begin(), DeletedTokens.end(), std::back_inserter(Tokens)); @@ -2580,7 +2580,7 @@ struct JavaImportDirective { StringRef Identifier; StringRef Text; unsigned Offset; - std::vector AssociatedCommentLines; + SmallVector AssociatedCommentLines; bool IsStatic; }; @@ -2983,7 +2983,7 @@ tooling::Replacements sortJavaImports(const FormatStyle &Style, StringRef Code, llvm::Regex ImportRegex(JavaImportRegexPattern); SmallVector Matches; SmallVector ImportsInBlock; - std::vector AssociatedCommentLines; + SmallVector AssociatedCommentLines; bool FormattingOff = false; @@ -3433,17 +3433,19 @@ LangOptions getFormattingLangOpts(const FormatStyle &Style) { } const char *StyleOptionHelpDescription = - "Coding style, currently supports:\n" - " LLVM, GNU, Google, Chromium, Microsoft, Mozilla, WebKit.\n" - "Use -style=file to load style configuration from\n" - ".clang-format file located in one of the parent\n" - "directories of the source file (or current\n" - "directory for stdin).\n" - "Use -style=file: to explicitly specify\n" - "the configuration file.\n" - "Use -style=\"{key: value, ...}\" to set specific\n" - "parameters, e.g.:\n" - " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\""; + "Set coding style. can be:\n" + "1. A preset: LLVM, GNU, Google, Chromium, Microsoft,\n" + " Mozilla, WebKit.\n" + "2. 'file' to load style configuration from a\n" + " .clang-format file in one of the parent directories\n" + " of the source file (for stdin, see --assume-filename).\n" + " If no .clang-format file is found, falls back to\n" + " --fallback-style.\n" + " --style=file is the default.\n" + "3. 'file:' to explicitly specify\n" + " the configuration file.\n" + "4. \"{key: value, ...}\" to set specific parameters, e.g.:\n" + " --style=\"{BasedOnStyle: llvm, IndentWidth: 8}\""; static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) { if (FileName.endswith(".java")) @@ -3498,6 +3500,7 @@ FormatStyle::LanguageKind guessLanguage(StringRef FileName, StringRef Code) { return GuessedLanguage; } +// Update StyleOptionHelpDescription above when changing this. const char *DefaultFormatStyle = "file"; const char *DefaultFallbackStyle = "LLVM"; diff --git a/contrib/llvm-project/clang/lib/Format/FormatToken.cpp b/contrib/llvm-project/clang/lib/Format/FormatToken.cpp index 2c0fee6975c2..832af463206c 100644 --- a/contrib/llvm-project/clang/lib/Format/FormatToken.cpp +++ b/contrib/llvm-project/clang/lib/Format/FormatToken.cpp @@ -264,7 +264,7 @@ void CommaSeparatedList::precomputeFormattingInfos(const FormatToken *Token) { // We can never place more than ColumnLimit / 3 items in a row (because of the // spaces and the comma). unsigned MaxItems = Style.ColumnLimit / 3; - std::vector MinSizeInColumn; + SmallVector MinSizeInColumn; MinSizeInColumn.reserve(MaxItems); for (unsigned Columns = 1; Columns <= MaxItems; ++Columns) { ColumnFormat Format; diff --git a/contrib/llvm-project/clang/lib/Format/FormatToken.h b/contrib/llvm-project/clang/lib/Format/FormatToken.h index b6cc021affae..73e32979853f 100644 --- a/contrib/llvm-project/clang/lib/Format/FormatToken.h +++ b/contrib/llvm-project/clang/lib/Format/FormatToken.h @@ -497,6 +497,15 @@ public: // in a configured macro expansion. llvm::Optional MacroCtx; + /// When macro expansion introduces nodes with children, those are marked as + /// \c MacroParent. + /// FIXME: The formatting code currently hard-codes the assumption that + /// child nodes are introduced by blocks following an opening brace. + /// This is deeply baked into the code and disentangling this will require + /// signficant refactorings. \c MacroParent allows us to special-case the + /// cases in which we treat parents as block-openers for now. + bool MacroParent = false; + bool is(tok::TokenKind Kind) const { return Tok.is(Kind); } bool is(TokenType TT) const { return getType() == TT; } bool is(const IdentifierInfo *II) const { diff --git a/contrib/llvm-project/clang/lib/Format/MacroCallReconstructor.cpp b/contrib/llvm-project/clang/lib/Format/MacroCallReconstructor.cpp new file mode 100644 index 000000000000..ccff183cf0da --- /dev/null +++ b/contrib/llvm-project/clang/lib/Format/MacroCallReconstructor.cpp @@ -0,0 +1,573 @@ +//===--- MacroCallReconstructor.cpp - Format C++ code -----------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +/// +/// \file +/// This file contains the implementation of MacroCallReconstructor, which fits +/// an reconstructed macro call to a parsed set of UnwrappedLines. +/// +//===----------------------------------------------------------------------===// + +#include "Macros.h" + +#include "UnwrappedLineParser.h" +#include "clang/Basic/TokenKinds.h" +#include "llvm/ADT/DenseSet.h" +#include "llvm/Support/Debug.h" +#include + +#define DEBUG_TYPE "format-reconstruct" + +namespace clang { +namespace format { + +// Call \p Call for each token in the unwrapped line given, passing +// the token, its parent and whether it is the first token in the line. +template +void forEachToken(const UnwrappedLine &Line, const T &Call, + FormatToken *Parent = nullptr) { + bool First = true; + for (const auto &N : Line.Tokens) { + Call(N.Tok, Parent, First); + First = false; + for (const auto &Child : N.Children) { + forEachToken(Child, Call, N.Tok); + } + } +} + +MacroCallReconstructor::MacroCallReconstructor( + unsigned Level, + const llvm::DenseMap> + &ActiveExpansions) + : Level(Level), IdToReconstructed(ActiveExpansions) { + Result.Tokens.push_back(std::make_unique()); + ActiveReconstructedLines.push_back(&Result); +} + +void MacroCallReconstructor::addLine(const UnwrappedLine &Line) { + assert(State != Finalized); + LLVM_DEBUG(llvm::dbgs() << "MCR: new line...\n"); + forEachToken(Line, [&](FormatToken *Token, FormatToken *Parent, bool First) { + add(Token, Parent, First); + }); + assert(InProgress || finished()); +} + +UnwrappedLine MacroCallReconstructor::takeResult() && { + finalize(); + assert(Result.Tokens.size() == 1 && Result.Tokens.front()->Children.size() == 1); + UnwrappedLine Final = + createUnwrappedLine(*Result.Tokens.front()->Children.front(), Level); + assert(!Final.Tokens.empty()); + return Final; +} + +// Reconstruct the position of the next \p Token, given its parent \p +// ExpandedParent in the incoming unwrapped line. \p First specifies whether it +// is the first token in a given unwrapped line. +void MacroCallReconstructor::add(FormatToken *Token, + FormatToken *ExpandedParent, bool First) { + LLVM_DEBUG( + llvm::dbgs() << "MCR: Token: " << Token->TokenText << ", Parent: " + << (ExpandedParent ? ExpandedParent->TokenText : "") + << ", First: " << First << "\n"); + // In order to be able to find the correct parent in the reconstructed token + // stream, we need to continue the last open reconstruction until we find the + // given token if it is part of the reconstructed token stream. + // + // Note that hidden tokens can be part of the reconstructed stream in nested + // macro calls. + // For example, given + // #define C(x, y) x y + // #define B(x) {x} + // And the call: + // C(a, B(b)) + // The outer macro call will be C(a, {b}), and the hidden token '}' can be + // found in the reconstructed token stream of that expansion level. + // In the expanded token stream + // a {b} + // 'b' is a child of '{'. We need to continue the open expansion of the ',' + // in the call of 'C' in order to correctly set the ',' as the parent of '{', + // so we later set the spelled token 'b' as a child of the ','. + if (!ActiveExpansions.empty() && Token->MacroCtx && + (Token->MacroCtx->Role != MR_Hidden || + ActiveExpansions.size() != Token->MacroCtx->ExpandedFrom.size())) { + if (/*PassedMacroComma = */ reconstructActiveCallUntil(Token)) + First = true; + } + + prepareParent(ExpandedParent, First); + + if (Token->MacroCtx) { + // If this token was generated by a macro call, add the reconstructed + // equivalent of the token. + reconstruct(Token); + } else { + // Otherwise, we add it to the current line. + appendToken(Token); + } +} + +// Adjusts the stack of active reconstructed lines so we're ready to push +// tokens. The tokens to be pushed are children of ExpandedParent in the +// expanded code. +// +// This may entail: +// - creating a new line, if the parent is on the active line +// - popping active lines, if the parent is further up the stack +// +// Postcondition: +// ActiveReconstructedLines.back() is the line that has \p ExpandedParent or its +// reconstructed replacement token as a parent (when possible) - that is, the +// last token in \c ActiveReconstructedLines[ActiveReconstructedLines.size()-2] +// is the parent of ActiveReconstructedLines.back() in the reconstructed +// unwrapped line. +void MacroCallReconstructor::prepareParent(FormatToken *ExpandedParent, + bool NewLine) { + LLVM_DEBUG({ + llvm::dbgs() << "ParentMap:\n"; + debugParentMap(); + }); + // We want to find the parent in the new unwrapped line, where the expanded + // parent might have been replaced during reconstruction. + FormatToken *Parent = getParentInResult(ExpandedParent); + LLVM_DEBUG(llvm::dbgs() << "MCR: New parent: " + << (Parent ? Parent->TokenText : "") << "\n"); + + FormatToken *OpenMacroParent = nullptr; + if (!MacroCallStructure.empty()) { + // Inside a macro expansion, it is possible to lose track of the correct + // parent - either because it is already popped, for example because it was + // in a different macro argument (e.g. M({, })), or when we work on invalid + // code. + // Thus, we use the innermost macro call's parent as the parent at which + // we stop; this allows us to stay within the macro expansion and keeps + // any problems confined to the extent of the macro call. + OpenMacroParent = + getParentInResult(MacroCallStructure.back().MacroCallLParen); + LLVM_DEBUG(llvm::dbgs() + << "MacroCallLParen: " + << MacroCallStructure.back().MacroCallLParen->TokenText + << ", OpenMacroParent: " + << (OpenMacroParent ? OpenMacroParent->TokenText : "") + << "\n"); + } + if (NewLine || + (!ActiveReconstructedLines.back()->Tokens.empty() && + Parent == ActiveReconstructedLines.back()->Tokens.back()->Tok)) { + // If we are at the first token in a new line, we want to also + // create a new line in the resulting reconstructed unwrapped line. + while (ActiveReconstructedLines.back()->Tokens.empty() || + (Parent != ActiveReconstructedLines.back()->Tokens.back()->Tok && + ActiveReconstructedLines.back()->Tokens.back()->Tok != + OpenMacroParent)) { + ActiveReconstructedLines.pop_back(); + assert(!ActiveReconstructedLines.empty()); + } + assert(!ActiveReconstructedLines.empty()); + ActiveReconstructedLines.back()->Tokens.back()->Children.push_back( + std::make_unique()); + ActiveReconstructedLines.push_back( + &*ActiveReconstructedLines.back()->Tokens.back()->Children.back()); + } else if (parentLine().Tokens.back()->Tok != Parent) { + // If we're not the first token in a new line, pop lines until we find + // the child of \c Parent in the stack. + while (Parent != parentLine().Tokens.back()->Tok && + parentLine().Tokens.back()->Tok && + parentLine().Tokens.back()->Tok != OpenMacroParent) { + ActiveReconstructedLines.pop_back(); + assert(!ActiveReconstructedLines.empty()); + } + } + assert(!ActiveReconstructedLines.empty()); +} + +// For a given \p Parent in the incoming expanded token stream, find the +// corresponding parent in the output. +FormatToken *MacroCallReconstructor::getParentInResult(FormatToken *Parent) { + FormatToken *Mapped = SpelledParentToReconstructedParent.lookup(Parent); + if (!Mapped) + return Parent; + for (; Mapped; Mapped = SpelledParentToReconstructedParent.lookup(Parent)) { + Parent = Mapped; + } + // If we use a different token than the parent in the expanded token stream + // as parent, mark it as a special parent, so the formatting code knows it + // needs to have its children formatted. + Parent->MacroParent = true; + return Parent; +} + +// Reconstruct a \p Token that was expanded from a macro call. +void MacroCallReconstructor::reconstruct(FormatToken *Token) { + assert(Token->MacroCtx); + // A single token can be the only result of a macro call: + // Given: #define ID(x, y) ; + // And the call: ID(, ) + // ';' in the expanded stream will reconstruct all of ID(, ). + if (Token->MacroCtx->StartOfExpansion) { + startReconstruction(Token); + // If the order of tokens in the expanded token stream is not the + // same as the order of tokens in the reconstructed stream, we need + // to reconstruct tokens that arrive later in the stream. + if (Token->MacroCtx->Role != MR_Hidden) { + reconstructActiveCallUntil(Token); + } + } + assert(!ActiveExpansions.empty()); + if (ActiveExpansions.back().SpelledI != ActiveExpansions.back().SpelledE) { + assert(ActiveExpansions.size() == Token->MacroCtx->ExpandedFrom.size()); + if (Token->MacroCtx->Role != MR_Hidden) { + // The current token in the reconstructed token stream must be the token + // we're looking for - we either arrive here after startReconstruction, + // which initiates the stream to the first token, or after + // continueReconstructionUntil skipped until the expected token in the + // reconstructed stream at the start of add(...). + assert(ActiveExpansions.back().SpelledI->Tok == Token); + processNextReconstructed(); + } else if (!currentLine()->Tokens.empty()) { + // Map all hidden tokens to the last visible token in the output. + // If the hidden token is a parent, we'll use the last visible + // token as the parent of the hidden token's children. + SpelledParentToReconstructedParent[Token] = + currentLine()->Tokens.back()->Tok; + } else { + for (auto I = ActiveReconstructedLines.rbegin(), + E = ActiveReconstructedLines.rend(); + I != E; ++I) { + if (!(*I)->Tokens.empty()) { + SpelledParentToReconstructedParent[Token] = (*I)->Tokens.back()->Tok; + break; + } + } + } + } + if (Token->MacroCtx->EndOfExpansion) + endReconstruction(Token); +} + +// Given a \p Token that starts an expansion, reconstruct the beginning of the +// macro call. +// For example, given: #define ID(x) x +// And the call: ID(int a) +// Reconstructs: ID( +void MacroCallReconstructor::startReconstruction(FormatToken *Token) { + assert(Token->MacroCtx); + assert(!Token->MacroCtx->ExpandedFrom.empty()); + assert(ActiveExpansions.size() <= Token->MacroCtx->ExpandedFrom.size()); +#ifndef NDEBUG + // Check that the token's reconstruction stack matches our current + // reconstruction stack. + for (size_t I = 0; I < ActiveExpansions.size(); ++I) { + assert(ActiveExpansions[I].ID == + Token->MacroCtx + ->ExpandedFrom[Token->MacroCtx->ExpandedFrom.size() - 1 - I]); + } +#endif + // Start reconstruction for all calls for which this token is the first token + // generated by the call. + // Note that the token's expanded from stack is inside-to-outside, and the + // expansions for which this token is not the first are the outermost ones. + ArrayRef StartedMacros = + makeArrayRef(Token->MacroCtx->ExpandedFrom) + .drop_back(ActiveExpansions.size()); + assert(StartedMacros.size() == Token->MacroCtx->StartOfExpansion); + // We reconstruct macro calls outside-to-inside. + for (FormatToken *ID : llvm::reverse(StartedMacros)) { + // We found a macro call to be reconstructed; the next time our + // reconstruction stack is empty we know we finished an reconstruction. +#ifndef NDEBUG + State = InProgress; +#endif + // Put the reconstructed macro call's token into our reconstruction stack. + auto IU = IdToReconstructed.find(ID); + assert(IU != IdToReconstructed.end()); + ActiveExpansions.push_back( + {ID, IU->second->Tokens.begin(), IU->second->Tokens.end()}); + // Process the macro call's identifier. + processNextReconstructed(); + if (ActiveExpansions.back().SpelledI == ActiveExpansions.back().SpelledE) + continue; + if (ActiveExpansions.back().SpelledI->Tok->is(tok::l_paren)) { + // Process the optional opening parenthesis. + processNextReconstructed(); + } + } +} + +// Add all tokens in the reconstruction stream to the output until we find the +// given \p Token. +bool MacroCallReconstructor::reconstructActiveCallUntil(FormatToken *Token) { + assert(!ActiveExpansions.empty()); + bool PassedMacroComma = false; + // FIXME: If Token was already expanded earlier, due to + // a change in order, we will not find it, but need to + // skip it. + while (ActiveExpansions.back().SpelledI != ActiveExpansions.back().SpelledE && + ActiveExpansions.back().SpelledI->Tok != Token) { + PassedMacroComma = processNextReconstructed() || PassedMacroComma; + } + return PassedMacroComma; +} + +// End all reconstructions for which \p Token is the final token. +void MacroCallReconstructor::endReconstruction(FormatToken *Token) { + assert(Token->MacroCtx && + (ActiveExpansions.size() >= Token->MacroCtx->EndOfExpansion)); + for (size_t I = 0; I < Token->MacroCtx->EndOfExpansion; ++I) { +#ifndef NDEBUG + // Check all remaining tokens but the final closing parenthesis and optional + // trailing comment were already reconstructed at an inner expansion level. + for (auto T = ActiveExpansions.back().SpelledI; + T != ActiveExpansions.back().SpelledE; ++T) { + FormatToken *Token = T->Tok; + bool ClosingParen = (std::next(T) == ActiveExpansions.back().SpelledE || + std::next(T)->Tok->isTrailingComment()) && + !Token->MacroCtx && Token->is(tok::r_paren); + bool TrailingComment = Token->isTrailingComment(); + bool PreviousLevel = + Token->MacroCtx && + (ActiveExpansions.size() < Token->MacroCtx->ExpandedFrom.size()); + if (!ClosingParen && !TrailingComment && !PreviousLevel) { + llvm::dbgs() << "At token: " << Token->TokenText << "\n"; + } + // In addition to the following cases, we can also run into this + // when a macro call had more arguments than expected; in that case, + // the comma and the remaining tokens in the macro call will potentially + // end up in the line when we finish the expansion. + // FIXME: Add the information which arguments are unused, and assert + // one of the cases below plus reconstructed macro argument tokens. + // assert(ClosingParen || TrailingComment || PreviousLevel); + } +#endif + // Handle the remaining open tokens: + // - expand the closing parenthesis, if it exists, including an optional + // trailing comment + // - handle tokens that were already reconstructed at an inner expansion + // level + // - handle tokens when a macro call had more than the expected number of + // arguments, i.e. when #define M(x) is called as M(a, b, c) we'll end + // up with the sequence ", b, c)" being open at the end of the + // reconstruction; we want to gracefully handle that case + // + // FIXME: See the above debug-check for what we will need to do to be + // able to assert this. + for (auto T = ActiveExpansions.back().SpelledI; + T != ActiveExpansions.back().SpelledE; ++T) { + processNextReconstructed(); + } + ActiveExpansions.pop_back(); + } +} + +void MacroCallReconstructor::debugParentMap() const { + llvm::DenseSet Values; + for (const auto &P : SpelledParentToReconstructedParent) + Values.insert(P.second); + + for (const auto &P : SpelledParentToReconstructedParent) { + if (Values.contains(P.first)) + continue; + llvm::dbgs() << (P.first ? P.first->TokenText : ""); + for (auto I = SpelledParentToReconstructedParent.find(P.first), + E = SpelledParentToReconstructedParent.end(); + I != E; I = SpelledParentToReconstructedParent.find(I->second)) { + llvm::dbgs() << " -> " << (I->second ? I->second->TokenText : ""); + } + llvm::dbgs() << "\n"; + } +} + +// If visible, add the next token of the reconstructed token sequence to the +// output. Returns whether reconstruction passed a comma that is part of a +// macro call. +bool MacroCallReconstructor::processNextReconstructed() { + FormatToken *Token = ActiveExpansions.back().SpelledI->Tok; + ++ActiveExpansions.back().SpelledI; + if (Token->MacroCtx) { + // Skip tokens that are not part of the macro call. + if (Token->MacroCtx->Role == MR_Hidden) { + return false; + } + // Skip tokens we already expanded during an inner reconstruction. + // For example, given: #define ID(x) {x} + // And the call: ID(ID(f)) + // We get two reconstructions: + // ID(f) -> {f} + // ID({f}) -> {{f}} + // We reconstruct f during the first reconstruction, and skip it during the + // second reconstruction. + if (ActiveExpansions.size() < Token->MacroCtx->ExpandedFrom.size()) { + return false; + } + } + // Tokens that do not have a macro context are tokens in that are part of the + // macro call that have not taken part in expansion. + if (!Token->MacroCtx) { + // Put the parentheses and commas of a macro call into the same line; + // if the arguments produce new unwrapped lines, they will become children + // of the corresponding opening parenthesis or comma tokens in the + // reconstructed call. + if (Token->is(tok::l_paren)) { + MacroCallStructure.push_back(MacroCallState( + currentLine(), parentLine().Tokens.back()->Tok, Token)); + // All tokens that are children of the previous line's last token in the + // reconstructed token stream will now be children of the l_paren token. + // For example, for the line containing the macro calls: + // auto x = ID({ID(2)}); + // We will build up a map -> ( -> ( with the first and second + // l_paren of the macro call respectively. New lines that come in with a + // parent will then become children of the l_paren token of the + // currently innermost macro call. + SpelledParentToReconstructedParent[MacroCallStructure.back() + .ParentLastToken] = Token; + appendToken(Token); + prepareParent(Token, /*NewLine=*/true); + Token->MacroParent = true; + return false; + } + if (!MacroCallStructure.empty()) { + if (Token->is(tok::comma)) { + // Make new lines inside the next argument children of the comma token. + SpelledParentToReconstructedParent + [MacroCallStructure.back().Line->Tokens.back()->Tok] = Token; + Token->MacroParent = true; + appendToken(Token, MacroCallStructure.back().Line); + prepareParent(Token, /*NewLine=*/true); + return true; + } + if (Token->is(tok::r_paren)) { + appendToken(Token, MacroCallStructure.back().Line); + SpelledParentToReconstructedParent.erase( + MacroCallStructure.back().ParentLastToken); + MacroCallStructure.pop_back(); + return false; + } + } + } + // Note that any tokens that are tagged with MR_None have been passed as + // arguments to the macro that have not been expanded, for example: + // Given: #define ID(X) x + // When calling: ID(a, b) + // 'b' will be part of the reconstructed token stream, but tagged MR_None. + // Given that erroring out in this case would be disruptive, we continue + // pushing the (unformatted) token. + // FIXME: This can lead to unfortunate formatting decisions - give the user + // a hint that their macro definition is broken. + appendToken(Token); + return false; +} + +void MacroCallReconstructor::finalize() { +#ifndef NDEBUG + assert(State != Finalized && finished()); + State = Finalized; +#endif + + // We created corresponding unwrapped lines for each incoming line as children + // the the toplevel null token. + assert(Result.Tokens.size() == 1 && !Result.Tokens.front()->Children.empty()); + LLVM_DEBUG({ + llvm::dbgs() << "Finalizing reconstructed lines:\n"; + debug(Result, 0); + }); + + // The first line becomes the top level line in the resulting unwrapped line. + LineNode &Top = *Result.Tokens.front(); + auto *I = Top.Children.begin(); + // Every subsequent line will become a child of the last token in the previous + // line, which is the token prior to the first token in the line. + LineNode *Last = (*I)->Tokens.back().get(); + ++I; + for (auto *E = Top.Children.end(); I != E; ++I) { + assert(Last->Children.empty()); + Last->Children.push_back(std::move(*I)); + + // Mark the previous line's last token as generated by a macro expansion + // so the formatting algorithm can take that into account. + Last->Tok->MacroParent = true; + + Last = Last->Children.back()->Tokens.back().get(); + } + Top.Children.resize(1); +} + +void MacroCallReconstructor::appendToken(FormatToken *Token, + ReconstructedLine *L) { + L = L ? L : currentLine(); + LLVM_DEBUG(llvm::dbgs() << "-> " << Token->TokenText << "\n"); + L->Tokens.push_back(std::make_unique(Token)); +} + +UnwrappedLine +MacroCallReconstructor::createUnwrappedLine(const ReconstructedLine &Line, + int Level) { + UnwrappedLine Result; + Result.Level = Level; + for (const auto &N : Line.Tokens) { + Result.Tokens.push_back(N->Tok); + UnwrappedLineNode &Current = Result.Tokens.back(); + for (const auto &Child : N->Children) { + if (Child->Tokens.empty()) + continue; + Current.Children.push_back(createUnwrappedLine(*Child, Level + 1)); + } + if (Current.Children.size() == 1 && + Current.Tok->isOneOf(tok::l_paren, tok::comma)) { + Result.Tokens.splice(Result.Tokens.end(), + Current.Children.front().Tokens); + Current.Children.clear(); + } + } + return Result; +} + +void MacroCallReconstructor::debug(const ReconstructedLine &Line, int Level) { + for (int i = 0; i < Level; ++i) + llvm::dbgs() << " "; + for (const auto &N : Line.Tokens) { + if (!N) + continue; + if (N->Tok) + llvm::dbgs() << N->Tok->TokenText << " "; + for (const auto &Child : N->Children) { + llvm::dbgs() << "\n"; + debug(*Child, Level + 1); + for (int i = 0; i < Level; ++i) + llvm::dbgs() << " "; + } + } + llvm::dbgs() << "\n"; +} + +MacroCallReconstructor::ReconstructedLine & +MacroCallReconstructor::parentLine() { + return **std::prev(std::prev(ActiveReconstructedLines.end())); +} + +MacroCallReconstructor::ReconstructedLine * +MacroCallReconstructor::currentLine() { + return ActiveReconstructedLines.back(); +} + +MacroCallReconstructor::MacroCallState::MacroCallState( + MacroCallReconstructor::ReconstructedLine *Line, + FormatToken *ParentLastToken, FormatToken *MacroCallLParen) + : Line(Line), ParentLastToken(ParentLastToken), + MacroCallLParen(MacroCallLParen) { + LLVM_DEBUG( + llvm::dbgs() << "ParentLastToken: " + << (ParentLastToken ? ParentLastToken->TokenText : "") + << "\n"); + + assert(MacroCallLParen->is(tok::l_paren)); +} + +} // namespace format +} // namespace clang diff --git a/contrib/llvm-project/clang/lib/Format/Macros.h b/contrib/llvm-project/clang/lib/Format/Macros.h index da03beb09145..b26799c20f8c 100644 --- a/contrib/llvm-project/clang/lib/Format/Macros.h +++ b/contrib/llvm-project/clang/lib/Format/Macros.h @@ -1,4 +1,4 @@ -//===--- MacroExpander.h - Format C++ code ----------------------*- C++ -*-===// +//===--- Macros.h - Format C++ code -----------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. @@ -22,40 +22,38 @@ /// spelled token streams into expanded token streams when it encounters a /// macro call. The UnwrappedLineParser continues to parse UnwrappedLines /// from the expanded token stream. -/// After the expanded unwrapped lines are parsed, the MacroUnexpander matches -/// the spelled token stream into unwrapped lines that best resemble the -/// structure of the expanded unwrapped lines. +/// After the expanded unwrapped lines are parsed, the MacroCallReconstructor +/// matches the spelled token stream into unwrapped lines that best resemble the +/// structure of the expanded unwrapped lines. These reconstructed unwrapped +/// lines are aliasing the tokens in the expanded token stream, so that token +/// annotations will be reused when formatting the spelled macro calls. /// -/// When formatting, clang-format formats the expanded unwrapped lines first, -/// determining the token types. Next, it formats the spelled unwrapped lines, -/// keeping the token types fixed, while allowing other formatting decisions -/// to change. +/// When formatting, clang-format annotates and formats the expanded unwrapped +/// lines first, determining the token types. Next, it formats the spelled +/// unwrapped lines, keeping the token types fixed, while allowing other +/// formatting decisions to change. /// //===----------------------------------------------------------------------===// #ifndef CLANG_LIB_FORMAT_MACROS_H #define CLANG_LIB_FORMAT_MACROS_H +#include +#include #include -#include #include -#include "Encoding.h" #include "FormatToken.h" #include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/DenseMap.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" -namespace llvm { -class MemoryBuffer; -} // namespace llvm - namespace clang { -class IdentifierTable; -class SourceManager; - namespace format { -struct FormatStyle; + +struct UnwrappedLine; +struct UnwrappedLineNode; /// Takes a set of macro definitions as strings and allows expanding calls to /// those macros. @@ -130,10 +128,253 @@ private: const FormatStyle &Style; llvm::SpecificBumpPtrAllocator &Allocator; IdentifierTable &IdentTable; - std::vector> Buffers; + SmallVector> Buffers; llvm::StringMap Definitions; }; +/// Converts a sequence of UnwrappedLines containing expanded macros into a +/// single UnwrappedLine containing the macro calls. This UnwrappedLine may be +/// broken into child lines, in a way that best conveys the structure of the +/// expanded code. +/// +/// In the simplest case, a spelled UnwrappedLine contains one macro, and after +/// expanding it we have one expanded UnwrappedLine. In general, macro +/// expansions can span UnwrappedLines, and multiple macros can contribute +/// tokens to the same line. We keep consuming expanded lines until: +/// * all expansions that started have finished (we're not chopping any macros +/// in half) +/// * *and* we've reached the end of a *spelled* unwrapped line. +/// +/// A single UnwrappedLine represents this chunk of code. +/// +/// After this point, the state of the spelled/expanded stream is "in sync" +/// (both at the start of an UnwrappedLine, with no macros open), so the +/// Unexpander can be thrown away and parsing can continue. +/// +/// Given a mapping from the macro name identifier token in the macro call +/// to the tokens of the macro call, for example: +/// CLASSA -> CLASSA({public: void x();}) +/// +/// When getting the formatted lines of the expansion via the \c addLine method +/// (each '->' specifies a call to \c addLine ): +/// -> class A { +/// -> public: +/// -> void x(); +/// -> }; +/// +/// Creates the tree of unwrapped lines containing the macro call tokens so that +/// the macro call tokens fit the semantic structure of the expanded formatted +/// lines: +/// -> CLASSA({ +/// -> public: +/// -> void x(); +/// -> }) +class MacroCallReconstructor { +public: + /// Create an Reconstructor whose resulting \p UnwrappedLine will start at + /// \p Level, using the map from name identifier token to the corresponding + /// tokens of the spelled macro call. + MacroCallReconstructor( + unsigned Level, + const llvm::DenseMap> + &ActiveExpansions); + + /// For the given \p Line, match all occurences of tokens expanded from a + /// macro to unwrapped lines in the spelled macro call so that the resulting + /// tree of unwrapped lines best resembles the structure of unwrapped lines + /// passed in via \c addLine. + void addLine(const UnwrappedLine &Line); + + /// Check whether at the current state there is no open macro expansion + /// that needs to be processed to finish an macro call. + /// Only when \c finished() is true, \c takeResult() can be called to retrieve + /// the resulting \c UnwrappedLine. + /// If there are multiple subsequent macro calls within an unwrapped line in + /// the spelled token stream, the calling code may also continue to call + /// \c addLine() when \c finished() is true. + bool finished() const { return ActiveExpansions.empty(); } + + /// Retrieve the formatted \c UnwrappedLine containing the orginal + /// macro calls, formatted according to the expanded token stream received + /// via \c addLine(). + /// Generally, this line tries to have the same structure as the expanded, + /// formatted unwrapped lines handed in via \c addLine(), with the exception + /// that for multiple top-level lines, each subsequent line will be the + /// child of the last token in its predecessor. This representation is chosen + /// because it is a precondition to the formatter that we get what looks like + /// a single statement in a single \c UnwrappedLine (i.e. matching parens). + /// + /// If a token in a macro argument is a child of a token in the expansion, + /// the parent will be the corresponding token in the macro call. + /// For example: + /// #define C(a, b) class C { a b + /// C(int x;, int y;) + /// would expand to + /// class C { int x; int y; + /// where in a formatted line "int x;" and "int y;" would both be new separate + /// lines. + /// + /// In the result, "int x;" will be a child of the opening parenthesis in "C(" + /// and "int y;" will be a child of the "," token: + /// C ( + /// \- int x; + /// , + /// \- int y; + /// ) + UnwrappedLine takeResult() &&; + +private: + void add(FormatToken *Token, FormatToken *ExpandedParent, bool First); + void prepareParent(FormatToken *ExpandedParent, bool First); + FormatToken *getParentInResult(FormatToken *Parent); + void reconstruct(FormatToken *Token); + void startReconstruction(FormatToken *Token); + bool reconstructActiveCallUntil(FormatToken *Token); + void endReconstruction(FormatToken *Token); + bool processNextReconstructed(); + void finalize(); + + struct ReconstructedLine; + + void appendToken(FormatToken *Token, ReconstructedLine *L = nullptr); + UnwrappedLine createUnwrappedLine(const ReconstructedLine &Line, int Level); + void debug(const ReconstructedLine &Line, int Level); + ReconstructedLine &parentLine(); + ReconstructedLine *currentLine(); + void debugParentMap() const; + +#ifndef NDEBUG + enum ReconstructorState { + Start, // No macro expansion was found in the input yet. + InProgress, // During a macro reconstruction. + Finalized, // Past macro reconstruction, the result is finalized. + }; + ReconstructorState State = Start; +#endif + + // Node in which we build up the resulting unwrapped line; this type is + // analogous to UnwrappedLineNode. + struct LineNode { + LineNode() = default; + LineNode(FormatToken *Tok) : Tok(Tok) {} + FormatToken *Tok = nullptr; + llvm::SmallVector> Children; + }; + + // Line in which we build up the resulting unwrapped line. + // FIXME: Investigate changing UnwrappedLine to a pointer type and using it + // instead of rolling our own type. + struct ReconstructedLine { + llvm::SmallVector> Tokens; + }; + + // The line in which we collect the resulting reconstructed output. + // To reduce special cases in the algorithm, the first level of the line + // contains a single null token that has the reconstructed incoming + // lines as children. + // In the end, we stich the lines together so that each subsequent line + // is a child of the last token of the previous line. This is necessary + // in order to format the overall expression as a single logical line - + // if we created separate lines, we'd format them with their own top-level + // indent depending on the semantic structure, which is not desired. + ReconstructedLine Result; + + // Stack of currently "open" lines, where each line's predecessor's last + // token is the parent token for that line. + llvm::SmallVector ActiveReconstructedLines; + + // Maps from the expanded token to the token that takes its place in the + // reconstructed token stream in terms of parent-child relationships. + // Note that it might take multiple steps to arrive at the correct + // parent in the output. + // Given: #define C(a, b) []() { a; b; } + // And a call: C(f(), g()) + // The structure in the incoming formatted unwrapped line will be: + // []() { + // |- f(); + // \- g(); + // } + // with f and g being children of the opening brace. + // In the reconstructed call: + // C(f(), g()) + // \- f() + // \- g() + // We want f to be a child of the opening parenthesis and g to be a child + // of the comma token in the macro call. + // Thus, we map + // { -> ( + // and add + // ( -> , + // once we're past the comma in the reconstruction. + llvm::DenseMap + SpelledParentToReconstructedParent; + + // Keeps track of a single expansion while we're reconstructing tokens it + // generated. + struct Expansion { + // The identifier token of the macro call. + FormatToken *ID; + // Our current position in the reconstruction. + std::list::iterator SpelledI; + // The end of the reconstructed token sequence. + std::list::iterator SpelledE; + }; + + // Stack of macro calls for which we're in the middle of an expansion. + llvm::SmallVector ActiveExpansions; + + struct MacroCallState { + MacroCallState(ReconstructedLine *Line, FormatToken *ParentLastToken, + FormatToken *MacroCallLParen); + + ReconstructedLine *Line; + + // The last token in the parent line or expansion, or nullptr if the macro + // expansion is on a top-level line. + // + // For example, in the macro call: + // auto f = []() { ID(1); }; + // The MacroCallState for ID will have '{' as ParentLastToken. + // + // In the macro call: + // ID(ID(void f())); + // The MacroCallState of the outer ID will have nullptr as ParentLastToken, + // while the MacroCallState for the inner ID will have the '(' of the outer + // ID as ParentLastToken. + // + // In the macro call: + // ID2(a, ID(b)); + // The MacroCallState of ID will have ',' as ParentLastToken. + FormatToken *ParentLastToken; + + // The l_paren of this MacroCallState's macro call. + FormatToken *MacroCallLParen; + }; + + // Keeps track of the lines into which the opening brace/parenthesis & + // argument separating commas for each level in the macro call go in order to + // put the corresponding closing brace/parenthesis into the same line in the + // output and keep track of which parents in the expanded token stream map to + // which tokens in the reconstructed stream. + // When an opening brace/parenthesis has children, we want the structure of + // the output line to be: + // |- MACRO + // |- ( + // | \- + // |- , + // | \- + // \- ) + llvm::SmallVector MacroCallStructure; + + // Level the generated UnwrappedLine will be at. + const unsigned Level; + + // Maps from identifier of the macro call to an unwrapped line containing + // all tokens of the macro call. + const llvm::DenseMap> + &IdToReconstructed; +}; + } // namespace format } // namespace clang diff --git a/contrib/llvm-project/clang/lib/Format/TokenAnnotator.cpp b/contrib/llvm-project/clang/lib/Format/TokenAnnotator.cpp index 029cb9097871..98c012994f45 100644 --- a/contrib/llvm-project/clang/lib/Format/TokenAnnotator.cpp +++ b/contrib/llvm-project/clang/lib/Format/TokenAnnotator.cpp @@ -4734,7 +4734,7 @@ bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line, // the first list element. Otherwise, it should be placed outside of the // list. return Left.is(BK_BracedInit) || - (Left.is(TT_CtorInitializerColon) && + (Left.is(TT_CtorInitializerColon) && Right.NewlinesBefore > 0 && Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon); } if (Left.is(tok::question) && Right.is(tok::colon)) @@ -4894,8 +4894,10 @@ bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line, if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral)) return true; - if (Left.is(TT_CtorInitializerColon)) - return Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon; + if (Left.is(TT_CtorInitializerColon)) { + return Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon && + (!Right.isTrailingComment() || Right.NewlinesBefore > 0); + } if (Right.is(TT_CtorInitializerColon)) return Style.BreakConstructorInitializers != FormatStyle::BCIS_AfterColon; if (Left.is(TT_CtorInitializerComma) && diff --git a/contrib/llvm-project/clang/lib/Format/UnwrappedLineFormatter.cpp b/contrib/llvm-project/clang/lib/Format/UnwrappedLineFormatter.cpp index 22509a504246..abeb93d23776 100644 --- a/contrib/llvm-project/clang/lib/Format/UnwrappedLineFormatter.cpp +++ b/contrib/llvm-project/clang/lib/Format/UnwrappedLineFormatter.cpp @@ -59,14 +59,12 @@ public: Offset = getIndentOffset(*Line.First); // Update the indent level cache size so that we can rely on it // having the right size in adjustToUnmodifiedline. - while (IndentForLevel.size() <= Line.Level) - IndentForLevel.push_back(-1); + skipLine(Line, /*UnknownIndent=*/true); if (Line.InPPDirective) { unsigned IndentWidth = (Style.PPIndentWidth >= 0) ? Style.PPIndentWidth : Style.IndentWidth; Indent = Line.Level * IndentWidth + AdditionalIndent; } else { - IndentForLevel.resize(Line.Level + 1); Indent = getIndent(Line.Level); } if (static_cast(Indent) + Offset >= 0) @@ -77,9 +75,9 @@ public: /// Update the indent state given that \p Line indent should be /// skipped. - void skipLine(const AnnotatedLine &Line) { - while (IndentForLevel.size() <= Line.Level) - IndentForLevel.push_back(Indent); + void skipLine(const AnnotatedLine &Line, bool UnknownIndent = false) { + if (Line.Level >= IndentForLevel.size()) + IndentForLevel.resize(Line.Level + 1, UnknownIndent ? -1 : Indent); } /// Update the level indent to adapt to the given \p Line. @@ -91,6 +89,7 @@ public: unsigned LevelIndent = Line.First->OriginalColumn; if (static_cast(LevelIndent) - Offset >= 0) LevelIndent -= Offset; + assert(Line.Level < IndentForLevel.size()); if ((!Line.First->is(tok::comment) || IndentForLevel[Line.Level] == -1) && !Line.InPPDirective) { IndentForLevel[Line.Level] = LevelIndent; @@ -159,7 +158,7 @@ private: const unsigned AdditionalIndent; /// The indent in characters for each level. - std::vector IndentForLevel; + SmallVector IndentForLevel; /// Offset of the current line relative to the indent level. /// @@ -1133,7 +1132,7 @@ private: typedef std::pair QueueItem; /// The BFS queue type. - typedef std::priority_queue, + typedef std::priority_queue, std::greater> QueueType; diff --git a/contrib/llvm-project/clang/lib/Format/UnwrappedLineParser.cpp b/contrib/llvm-project/clang/lib/Format/UnwrappedLineParser.cpp index d3383292f7a3..97c3d86282a0 100644 --- a/contrib/llvm-project/clang/lib/Format/UnwrappedLineParser.cpp +++ b/contrib/llvm-project/clang/lib/Format/UnwrappedLineParser.cpp @@ -15,6 +15,7 @@ #include "UnwrappedLineParser.h" #include "FormatToken.h" #include "TokenAnnotator.h" +#include "clang/Basic/TokenKinds.h" #include "llvm/ADT/STLExtras.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" @@ -1910,15 +1911,12 @@ void UnwrappedLineParser::parseStructuralElement( break; auto OneTokenSoFar = [&]() { - const UnwrappedLineNode *Tok = &Line->Tokens.front(), - *End = Tok + Line->Tokens.size(); - while (Tok != End && Tok->Tok->is(tok::comment)) - ++Tok; - // In Verilog, macro invocations start with a backtick which the code - // treats as a hash. Skip it. - if (Style.isVerilog() && Tok != End && Tok->Tok->is(tok::hash)) - ++Tok; - return End - Tok == 1; + auto I = Line->Tokens.begin(), E = Line->Tokens.end(); + while (I != E && I->Tok->is(tok::comment)) + ++I; + while (I != E && Style.isVerilog() && I->Tok->is(tok::hash)) + ++I; + return I != E && (++I == E); }; if (OneTokenSoFar()) { if (FormatTok->is(tok::colon) && !Line->MustBeDeclaration) { diff --git a/contrib/llvm-project/clang/lib/Format/UnwrappedLineParser.h b/contrib/llvm-project/clang/lib/Format/UnwrappedLineParser.h index 8f63870412d0..3394bfab8b8e 100644 --- a/contrib/llvm-project/clang/lib/Format/UnwrappedLineParser.h +++ b/contrib/llvm-project/clang/lib/Format/UnwrappedLineParser.h @@ -20,6 +20,7 @@ #include "clang/Format/Format.h" #include "llvm/ADT/BitVector.h" #include "llvm/Support/Regex.h" +#include #include #include @@ -38,7 +39,7 @@ struct UnwrappedLine { UnwrappedLine(); /// The \c Tokens comprising this \c UnwrappedLine. - std::vector Tokens; + std::list Tokens; /// The indent level of the \c UnwrappedLine. unsigned Level; diff --git a/contrib/llvm-project/clang/lib/Frontend/CompilerInstance.cpp b/contrib/llvm-project/clang/lib/Frontend/CompilerInstance.cpp index b982ca72c78c..2cd7efd862ec 100644 --- a/contrib/llvm-project/clang/lib/Frontend/CompilerInstance.cpp +++ b/contrib/llvm-project/clang/lib/Frontend/CompilerInstance.cpp @@ -115,9 +115,9 @@ bool CompilerInstance::createTarget() { auto TO = std::make_shared(); TO->Triple = llvm::Triple::normalize(getFrontendOpts().AuxTriple); if (getFrontendOpts().AuxTargetCPU) - TO->CPU = getFrontendOpts().AuxTargetCPU.getValue(); + TO->CPU = getFrontendOpts().AuxTargetCPU.value(); if (getFrontendOpts().AuxTargetFeatures) - TO->FeaturesAsWritten = getFrontendOpts().AuxTargetFeatures.getValue(); + TO->FeaturesAsWritten = getFrontendOpts().AuxTargetFeatures.value(); TO->HostTriple = getTarget().getTriple().str(); setAuxTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), TO)); } @@ -757,6 +757,8 @@ void CompilerInstance::createSema(TranslationUnitKind TUKind, // Output Files void CompilerInstance::clearOutputFiles(bool EraseFiles) { + // The ASTConsumer can own streams that write to the output files. + assert(!hasASTConsumer() && "ASTConsumer should be reset"); // Ignore errors that occur when trying to discard the temp file. for (OutputFile &OF : OutputFiles) { if (EraseFiles) { @@ -1235,8 +1237,7 @@ compileModuleImpl(CompilerInstance &ImportingInstance, SourceLocation ImportLoc, // Execute the action to actually build the module in-place. Use a separate // thread so that we get a stack large enough. - llvm::CrashRecoveryContext CRC; - CRC.RunSafelyOnThread( + bool Crashed = !llvm::CrashRecoveryContext().RunSafelyOnThread( [&]() { GenerateModuleFromModuleMapAction Action; Instance.ExecuteAction(Action); @@ -1249,9 +1250,15 @@ compileModuleImpl(CompilerInstance &ImportingInstance, SourceLocation ImportLoc, diag::remark_module_build_done) << ModuleName; - // Delete any remaining temporary files related to Instance, in case the - // module generation thread crashed. - Instance.clearOutputFiles(/*EraseFiles=*/true); + if (Crashed) { + // Clear the ASTConsumer if it hasn't been already, in case it owns streams + // that must be closed before clearing output files. + Instance.setSema(nullptr); + Instance.setASTConsumer(nullptr); + + // Delete any remaining temporary files related to Instance. + Instance.clearOutputFiles(/*EraseFiles=*/true); + } // If \p AllowPCMWithCompilerErrors is set return 'success' even if errors // occurred. diff --git a/contrib/llvm-project/clang/lib/Frontend/CompilerInvocation.cpp b/contrib/llvm-project/clang/lib/Frontend/CompilerInvocation.cpp index abef4cf65496..48cd6a394107 100644 --- a/contrib/llvm-project/clang/lib/Frontend/CompilerInvocation.cpp +++ b/contrib/llvm-project/clang/lib/Frontend/CompilerInvocation.cpp @@ -1485,6 +1485,9 @@ void CompilerInvocation::GenerateCodeGenArgs( if (Opts.IBTSeal) GenerateArg(Args, OPT_mibt_seal, SA); + if (Opts.FunctionReturnThunks) + GenerateArg(Args, OPT_mfunction_return_EQ, "thunk-extern", SA); + for (const auto &F : Opts.LinkBitcodeFiles) { bool Builtint = F.LinkFlags == llvm::Linker::Flags::LinkOnlyNeeded && F.PropagateAttrs && F.Internalize; @@ -1825,6 +1828,27 @@ bool CompilerInvocation::ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name; } + if (const Arg *A = Args.getLastArg(OPT_mfunction_return_EQ)) { + auto Val = llvm::StringSwitch(A->getValue()) + .Case("keep", llvm::FunctionReturnThunksKind::Keep) + .Case("thunk-extern", llvm::FunctionReturnThunksKind::Extern) + .Default(llvm::FunctionReturnThunksKind::Invalid); + // SystemZ might want to add support for "expolines." + if (!T.isX86()) + Diags.Report(diag::err_drv_argument_not_allowed_with) + << A->getSpelling() << T.getTriple(); + else if (Val == llvm::FunctionReturnThunksKind::Invalid) + Diags.Report(diag::err_drv_invalid_value) + << A->getAsString(Args) << A->getValue(); + else if (Val == llvm::FunctionReturnThunksKind::Extern && + Args.getLastArgValue(OPT_mcmodel_EQ).equals("large")) + Diags.Report(diag::err_drv_argument_not_allowed_with) + << A->getAsString(Args) + << Args.getLastArg(OPT_mcmodel_EQ)->getAsString(Args); + else + Opts.FunctionReturnThunks = static_cast(Val); + } + if (Opts.PrepareForLTO && Args.hasArg(OPT_mibt_seal)) Opts.IBTSeal = 1; @@ -1952,7 +1976,7 @@ bool CompilerInvocation::ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, } else { Opts.DiagnosticsHotnessThreshold = *ResultOrErr; if ((!Opts.DiagnosticsHotnessThreshold || - Opts.DiagnosticsHotnessThreshold.getValue() > 0) && + Opts.DiagnosticsHotnessThreshold.value() > 0) && !UsingProfile) Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo) << "-fdiagnostics-hotness-threshold="; @@ -1969,7 +1993,7 @@ bool CompilerInvocation::ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, } else { Opts.DiagnosticsMisExpectTolerance = *ResultOrErr; if ((!Opts.DiagnosticsMisExpectTolerance || - Opts.DiagnosticsMisExpectTolerance.getValue() > 0) && + Opts.DiagnosticsMisExpectTolerance.value() > 0) && !UsingProfile) Diags.Report(diag::warn_drv_diagnostics_misexpect_requires_pgo) << "-fdiagnostics-misexpect-tolerance="; diff --git a/contrib/llvm-project/clang/lib/Frontend/FrontendAction.cpp b/contrib/llvm-project/clang/lib/Frontend/FrontendAction.cpp index 65160dd7e0b1..ed3e314cc73b 100644 --- a/contrib/llvm-project/clang/lib/Frontend/FrontendAction.cpp +++ b/contrib/llvm-project/clang/lib/Frontend/FrontendAction.cpp @@ -24,6 +24,7 @@ #include "clang/Lex/Preprocessor.h" #include "clang/Lex/PreprocessorOptions.h" #include "clang/Parse/ParseAST.h" +#include "clang/Sema/HLSLExternalSemaSource.h" #include "clang/Serialization/ASTDeserializationListener.h" #include "clang/Serialization/ASTReader.h" #include "clang/Serialization/GlobalModuleIndex.h" @@ -580,6 +581,7 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI, auto FailureCleanup = llvm::make_scope_exit([&]() { if (HasBegunSourceFile) CI.getDiagnosticClient().EndSourceFile(); + CI.setASTConsumer(nullptr); CI.clearOutputFiles(/*EraseFiles=*/true); CI.getLangOpts().setCompilingModule(LangOptions::CMK_None); setCurrentInput(FrontendInputFile()); @@ -1014,6 +1016,13 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI, CI.getASTContext().setExternalSource(Override); } + // Setup HLSL External Sema Source + if (CI.getLangOpts().HLSL && CI.hasASTContext()) { + IntrusiveRefCntPtr HLSLSema( + new HLSLExternalSemaSource()); + CI.getASTContext().setExternalSource(HLSLSema); + } + FailureCleanup.release(); return true; } diff --git a/contrib/llvm-project/clang/lib/Frontend/FrontendActions.cpp b/contrib/llvm-project/clang/lib/Frontend/FrontendActions.cpp index f61c83a2a465..f833541caa25 100644 --- a/contrib/llvm-project/clang/lib/Frontend/FrontendActions.cpp +++ b/contrib/llvm-project/clang/lib/Frontend/FrontendActions.cpp @@ -854,8 +854,9 @@ void DumpModuleInfoAction::ExecuteAction() { std::error_code EC; OutFile.reset(new llvm::raw_fd_ostream(OutputFileName.str(), EC, llvm::sys::fs::OF_TextWithCRLF)); + OutputStream = OutFile.get(); } - llvm::raw_ostream &Out = OutFile.get()? *OutFile.get() : llvm::outs(); + llvm::raw_ostream &Out = OutputStream ? *OutputStream : llvm::outs(); Out << "Information for module file '" << getCurrentFile() << "':\n"; auto &FileMgr = getCompilerInstance().getFileManager(); diff --git a/contrib/llvm-project/clang/lib/Frontend/InitPreprocessor.cpp b/contrib/llvm-project/clang/lib/Frontend/InitPreprocessor.cpp index fe3736c07c3c..d0360696ff9c 100644 --- a/contrib/llvm-project/clang/lib/Frontend/InitPreprocessor.cpp +++ b/contrib/llvm-project/clang/lib/Frontend/InitPreprocessor.cpp @@ -832,11 +832,11 @@ static void InitializePredefinedMacros(const TargetInfo &TI, unsigned minor = 0; if (tuple.getMinor()) - minor = tuple.getMinor().getValue(); + minor = tuple.getMinor().value(); unsigned subminor = 0; if (tuple.getSubminor()) - subminor = tuple.getSubminor().getValue(); + subminor = tuple.getSubminor().value(); Builder.defineMacro("__OBJFW_RUNTIME_ABI__", Twine(tuple.getMajor() * 10000 + minor * 100 + diff --git a/contrib/llvm-project/clang/lib/Headers/hlsl/hlsl_basic_types.h b/contrib/llvm-project/clang/lib/Headers/hlsl/hlsl_basic_types.h index 2069990f5c06..e68715f1a6a4 100644 --- a/contrib/llvm-project/clang/lib/Headers/hlsl/hlsl_basic_types.h +++ b/contrib/llvm-project/clang/lib/Headers/hlsl/hlsl_basic_types.h @@ -27,38 +27,38 @@ typedef long int64_t; // built-in vector data types: #ifdef __HLSL_ENABLE_16_BIT -typedef int16_t int16_t2 __attribute__((ext_vector_type(2))); -typedef int16_t int16_t3 __attribute__((ext_vector_type(3))); -typedef int16_t int16_t4 __attribute__((ext_vector_type(4))); -typedef uint16_t uint16_t2 __attribute__((ext_vector_type(2))); -typedef uint16_t uint16_t3 __attribute__((ext_vector_type(3))); -typedef uint16_t uint16_t4 __attribute__((ext_vector_type(4))); +typedef vector int16_t2; +typedef vector int16_t3; +typedef vector int16_t4; +typedef vector uint16_t2; +typedef vector uint16_t3; +typedef vector uint16_t4; #endif -typedef int int2 __attribute__((ext_vector_type(2))); -typedef int int3 __attribute__((ext_vector_type(3))); -typedef int int4 __attribute__((ext_vector_type(4))); -typedef uint uint2 __attribute__((ext_vector_type(2))); -typedef uint uint3 __attribute__((ext_vector_type(3))); -typedef uint uint4 __attribute__((ext_vector_type(4))); -typedef int64_t int64_t2 __attribute__((ext_vector_type(2))); -typedef int64_t int64_t3 __attribute__((ext_vector_type(3))); -typedef int64_t int64_t4 __attribute__((ext_vector_type(4))); -typedef uint64_t uint64_t2 __attribute__((ext_vector_type(2))); -typedef uint64_t uint64_t3 __attribute__((ext_vector_type(3))); -typedef uint64_t uint64_t4 __attribute__((ext_vector_type(4))); +typedef vector int2; +typedef vector int3; +typedef vector int4; +typedef vector uint2; +typedef vector uint3; +typedef vector uint4; +typedef vector int64_t2; +typedef vector int64_t3; +typedef vector int64_t4; +typedef vector uint64_t2; +typedef vector uint64_t3; +typedef vector uint64_t4; #ifdef __HLSL_ENABLE_16_BIT -typedef half half2 __attribute__((ext_vector_type(2))); -typedef half half3 __attribute__((ext_vector_type(3))); -typedef half half4 __attribute__((ext_vector_type(4))); +typedef vector half2; +typedef vector half3; +typedef vector half4; #endif -typedef float float2 __attribute__((ext_vector_type(2))); -typedef float float3 __attribute__((ext_vector_type(3))); -typedef float float4 __attribute__((ext_vector_type(4))); -typedef double double2 __attribute__((ext_vector_type(2))); -typedef double double3 __attribute__((ext_vector_type(3))); -typedef double double4 __attribute__((ext_vector_type(4))); +typedef vector float2; +typedef vector float3; +typedef vector float4; +typedef vector double2; +typedef vector double3; +typedef vector double4; #endif //_HLSL_HLSL_BASIC_TYPES_H_ diff --git a/contrib/llvm-project/clang/lib/Headers/opencl-c.h b/contrib/llvm-project/clang/lib/Headers/opencl-c.h index ed647d9e9c06..72a6bfeafd6a 100644 --- a/contrib/llvm-project/clang/lib/Headers/opencl-c.h +++ b/contrib/llvm-project/clang/lib/Headers/opencl-c.h @@ -10467,12 +10467,6 @@ float __ovld __cnfn fast_distance(float, float); float __ovld __cnfn fast_distance(float2, float2); float __ovld __cnfn fast_distance(float3, float3); float __ovld __cnfn fast_distance(float4, float4); -#ifdef cl_khr_fp16 -half __ovld __cnfn fast_distance(half, half); -half __ovld __cnfn fast_distance(half2, half2); -half __ovld __cnfn fast_distance(half3, half3); -half __ovld __cnfn fast_distance(half4, half4); -#endif //cl_khr_fp16 /** * Returns the length of vector p computed as: @@ -10482,12 +10476,6 @@ float __ovld __cnfn fast_length(float); float __ovld __cnfn fast_length(float2); float __ovld __cnfn fast_length(float3); float __ovld __cnfn fast_length(float4); -#ifdef cl_khr_fp16 -half __ovld __cnfn fast_length(half); -half __ovld __cnfn fast_length(half2); -half __ovld __cnfn fast_length(half3); -half __ovld __cnfn fast_length(half4); -#endif //cl_khr_fp16 /** * Returns a vector in the same direction as p but with a @@ -10514,12 +10502,6 @@ float __ovld __cnfn fast_normalize(float); float2 __ovld __cnfn fast_normalize(float2); float3 __ovld __cnfn fast_normalize(float3); float4 __ovld __cnfn fast_normalize(float4); -#ifdef cl_khr_fp16 -half __ovld __cnfn fast_normalize(half); -half2 __ovld __cnfn fast_normalize(half2); -half3 __ovld __cnfn fast_normalize(half3); -half4 __ovld __cnfn fast_normalize(half4); -#endif //cl_khr_fp16 // OpenCL v1.1 s6.11.6, v1.2 s6.12.6, v2.0 s6.13.6 - Relational Functions diff --git a/contrib/llvm-project/clang/lib/Headers/rdpruintrin.h b/contrib/llvm-project/clang/lib/Headers/rdpruintrin.h new file mode 100644 index 000000000000..89732bb8b3cf --- /dev/null +++ b/contrib/llvm-project/clang/lib/Headers/rdpruintrin.h @@ -0,0 +1,57 @@ +/*===---- rdpruintrin.h - RDPRU intrinsics ---------------------------------=== + * + * 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 + * + *===-----------------------------------------------------------------------=== + */ + +#if !defined __X86INTRIN_H +#error "Never use directly; include instead." +#endif + +#ifndef __RDPRUINTRIN_H +#define __RDPRUINTRIN_H + +/* Define the default attributes for the functions in this file. */ +#define __DEFAULT_FN_ATTRS \ + __attribute__((__always_inline__, __nodebug__, __target__("rdpru"))) + + +/// Reads the content of a processor register. +/// +/// \headerfile +/// +/// This intrinsic corresponds to the RDPRU instruction. +/// +/// \param reg_id +/// A processor register identifier. +static __inline__ unsigned long long __DEFAULT_FN_ATTRS +__rdpru (int reg_id) +{ + return __builtin_ia32_rdpru(reg_id); +} + +#define __RDPRU_MPERF 0 +#define __RDPRU_APERF 1 + +/// Reads the content of processor register MPERF. +/// +/// \headerfile +/// +/// This intrinsic generates instruction RDPRU to read the value of +/// register MPERF. +#define __mperf() __builtin_ia32_rdpru(__RDPRU_MPERF) + +/// Reads the content of processor register APERF. +/// +/// \headerfile +/// +/// This intrinsic generates instruction RDPRU to read the value of +/// register APERF. +#define __aperf() __builtin_ia32_rdpru(__RDPRU_APERF) + +#undef __DEFAULT_FN_ATTRS + +#endif /* __RDPRUINTRIN_H */ diff --git a/contrib/llvm-project/clang/lib/Headers/stdatomic.h b/contrib/llvm-project/clang/lib/Headers/stdatomic.h index 780bcc2dfea1..3a0b9cc056be 100644 --- a/contrib/llvm-project/clang/lib/Headers/stdatomic.h +++ b/contrib/llvm-project/clang/lib/Headers/stdatomic.h @@ -158,10 +158,6 @@ typedef _Atomic(uintmax_t) atomic_uintmax_t; typedef struct atomic_flag { atomic_bool _Value; } atomic_flag; #define ATOMIC_FLAG_INIT { 0 } -#if __cplusplus >= 202002L && !defined(_CLANG_DISABLE_CRT_DEPRECATION_WARNINGS) -/* ATOMIC_FLAG_INIT was deprecated in C++20 but is not deprecated in C. */ -#pragma clang deprecated(ATOMIC_FLAG_INIT) -#endif /* These should be provided by the libc implementation. */ #ifdef __cplusplus diff --git a/contrib/llvm-project/clang/lib/Headers/x86intrin.h b/contrib/llvm-project/clang/lib/Headers/x86intrin.h index 768d0e56ab05..450fd008dab9 100644 --- a/contrib/llvm-project/clang/lib/Headers/x86intrin.h +++ b/contrib/llvm-project/clang/lib/Headers/x86intrin.h @@ -59,5 +59,9 @@ #include #endif +#if !(defined(_MSC_VER) || defined(__SCE__)) || __has_feature(modules) || \ + defined(__RDPRU__) +#include +#endif #endif /* __X86INTRIN_H */ diff --git a/contrib/llvm-project/clang/lib/Lex/DependencyDirectivesScanner.cpp b/contrib/llvm-project/clang/lib/Lex/DependencyDirectivesScanner.cpp index be7b7d6e17b2..567ca81f6ac2 100644 --- a/contrib/llvm-project/clang/lib/Lex/DependencyDirectivesScanner.cpp +++ b/contrib/llvm-project/clang/lib/Lex/DependencyDirectivesScanner.cpp @@ -550,7 +550,7 @@ Scanner::tryLexIdentifierOrSkipLine(const char *&First, const char *const End) { StringRef Scanner::lexIdentifier(const char *&First, const char *const End) { Optional Id = tryLexIdentifierOrSkipLine(First, End); assert(Id && "expected identifier token"); - return Id.getValue(); + return Id.value(); } bool Scanner::isNextIdentifierOrSkipLine(StringRef Id, const char *&First, diff --git a/contrib/llvm-project/clang/lib/Lex/Lexer.cpp b/contrib/llvm-project/clang/lib/Lex/Lexer.cpp index 6820057642be..b3aac9df6546 100644 --- a/contrib/llvm-project/clang/lib/Lex/Lexer.cpp +++ b/contrib/llvm-project/clang/lib/Lex/Lexer.cpp @@ -2392,13 +2392,37 @@ bool Lexer::SkipLineComment(Token &Result, const char *CurPtr, // // This loop terminates with CurPtr pointing at the newline (or end of buffer) // character that ends the line comment. + + // C++23 [lex.phases] p1 + // Diagnose invalid UTF-8 if the corresponding warning is enabled, emitting a + // diagnostic only once per entire ill-formed subsequence to avoid + // emiting to many diagnostics (see http://unicode.org/review/pr-121.html). + bool UnicodeDecodingAlreadyDiagnosed = false; + char C; while (true) { C = *CurPtr; // Skip over characters in the fast loop. - while (C != 0 && // Potentially EOF. - C != '\n' && C != '\r') // Newline or DOS-style newline. + while (isASCII(C) && C != 0 && // Potentially EOF. + C != '\n' && C != '\r') { // Newline or DOS-style newline. C = *++CurPtr; + UnicodeDecodingAlreadyDiagnosed = false; + } + + if (!isASCII(C)) { + unsigned Length = llvm::getUTF8SequenceSize( + (const llvm::UTF8 *)CurPtr, (const llvm::UTF8 *)BufferEnd); + if (Length == 0) { + if (!UnicodeDecodingAlreadyDiagnosed && !isLexingRawMode()) + Diag(CurPtr, diag::warn_invalid_utf8_in_comment); + UnicodeDecodingAlreadyDiagnosed = true; + ++CurPtr; + } else { + UnicodeDecodingAlreadyDiagnosed = false; + CurPtr += Length; + } + continue; + } const char *NextLine = CurPtr; if (C != 0) { @@ -2665,6 +2689,12 @@ bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr, if (C == '/') C = *CurPtr++; + // C++23 [lex.phases] p1 + // Diagnose invalid UTF-8 if the corresponding warning is enabled, emitting a + // diagnostic only once per entire ill-formed subsequence to avoid + // emiting to many diagnostics (see http://unicode.org/review/pr-121.html). + bool UnicodeDecodingAlreadyDiagnosed = false; + while (true) { // Skip over all non-interesting characters until we find end of buffer or a // (probably ending) '/' character. @@ -2673,14 +2703,21 @@ bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr, // doesn't check for '\0'. !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) { // While not aligned to a 16-byte boundary. - while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0) + while (C != '/' && (intptr_t)CurPtr % 16 != 0) { + if (!isASCII(C)) + goto MultiByteUTF8; C = *CurPtr++; - + } if (C == '/') goto FoundSlash; #ifdef __SSE2__ __m128i Slashes = _mm_set1_epi8('/'); - while (CurPtr+16 <= BufferEnd) { + while (CurPtr + 16 < BufferEnd) { + int Mask = _mm_movemask_epi8(*(const __m128i *)CurPtr); + if (LLVM_UNLIKELY(Mask != 0)) { + goto MultiByteUTF8; + } + // look for slashes int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(const __m128i*)CurPtr, Slashes)); if (cmp != 0) { @@ -2693,21 +2730,38 @@ bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr, CurPtr += 16; } #elif __ALTIVEC__ + __vector unsigned char LongUTF = {0x80, 0x80, 0x80, 0x80, 0x80, 0x80, + 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, + 0x80, 0x80, 0x80, 0x80}; __vector unsigned char Slashes = { '/', '/', '/', '/', '/', '/', '/', '/', '/', '/', '/', '/', '/', '/', '/', '/' }; - while (CurPtr + 16 <= BufferEnd && - !vec_any_eq(*(const __vector unsigned char *)CurPtr, Slashes)) + while (CurPtr + 16 < BufferEnd) { + if (LLVM_UNLIKELY( + vec_any_ge(*(const __vector unsigned char *)CurPtr, LongUTF))) + goto MultiByteUTF8; + if (vec_any_eq(*(const __vector unsigned char *)CurPtr, Slashes)) { + break; + } CurPtr += 16; + } + #else - // Scan for '/' quickly. Many block comments are very large. - while (CurPtr[0] != '/' && - CurPtr[1] != '/' && - CurPtr[2] != '/' && - CurPtr[3] != '/' && - CurPtr+4 < BufferEnd) { - CurPtr += 4; + while (CurPtr + 16 < BufferEnd) { + bool HasNonASCII = false; + for (unsigned I = 0; I < 16; ++I) + HasNonASCII |= !isASCII(CurPtr[I]); + + if (LLVM_UNLIKELY(HasNonASCII)) + goto MultiByteUTF8; + + bool HasSlash = false; + for (unsigned I = 0; I < 16; ++I) + HasSlash |= CurPtr[I] == '/'; + if (HasSlash) + break; + CurPtr += 16; } #endif @@ -2715,9 +2769,30 @@ bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr, C = *CurPtr++; } - // Loop to scan the remainder. - while (C != '/' && C != '\0') + // Loop to scan the remainder, warning on invalid UTF-8 + // if the corresponding warning is enabled, emitting a diagnostic only once + // per sequence that cannot be decoded. + while (C != '/' && C != '\0') { + if (isASCII(C)) { + UnicodeDecodingAlreadyDiagnosed = false; + C = *CurPtr++; + continue; + } + MultiByteUTF8: + // CurPtr is 1 code unit past C, so to decode + // the codepoint, we need to read from the previous position. + unsigned Length = llvm::getUTF8SequenceSize( + (const llvm::UTF8 *)CurPtr - 1, (const llvm::UTF8 *)BufferEnd); + if (Length == 0) { + if (!UnicodeDecodingAlreadyDiagnosed && !isLexingRawMode()) + Diag(CurPtr - 1, diag::warn_invalid_utf8_in_comment); + UnicodeDecodingAlreadyDiagnosed = true; + } else { + UnicodeDecodingAlreadyDiagnosed = false; + CurPtr += Length - 1; + } C = *CurPtr++; + } if (C == '/') { FoundSlash: @@ -3212,7 +3287,10 @@ llvm::Optional Lexer::tryReadNumericUCN(const char *&StartPtr, } if (Delimited && PP) { - Diag(BufferPtr, diag::ext_delimited_escape_sequence) << /*delimited*/ 0; + Diag(BufferPtr, PP->getLangOpts().CPlusPlus2b + ? diag::warn_cxx2b_delimited_escape_sequence + : diag::ext_delimited_escape_sequence) + << /*delimited*/ 0 << (PP->getLangOpts().CPlusPlus ? 1 : 0); } if (Result) { @@ -3296,7 +3374,10 @@ llvm::Optional Lexer::tryReadNamedUCN(const char *&StartPtr, } if (Diagnose && PP && !LooseMatch) - Diag(BufferPtr, diag::ext_delimited_escape_sequence) << /*named*/ 1; + Diag(BufferPtr, PP->getLangOpts().CPlusPlus2b + ? diag::warn_cxx2b_delimited_escape_sequence + : diag::ext_delimited_escape_sequence) + << /*named*/ 1 << (PP->getLangOpts().CPlusPlus ? 1 : 0); if (LooseMatch) Res = LooseMatch->CodePoint; diff --git a/contrib/llvm-project/clang/lib/Lex/LiteralSupport.cpp b/contrib/llvm-project/clang/lib/Lex/LiteralSupport.cpp index ebf30c9f01a9..53635a7385ec 100644 --- a/contrib/llvm-project/clang/lib/Lex/LiteralSupport.cpp +++ b/contrib/llvm-project/clang/lib/Lex/LiteralSupport.cpp @@ -311,8 +311,9 @@ static unsigned ProcessCharEscape(const char *ThisTokBegin, << tok::r_brace; else if (!HadError) { Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf, - diag::ext_delimited_escape_sequence) - << /*delimited*/ 0; + Features.CPlusPlus2b ? diag::warn_cxx2b_delimited_escape_sequence + : diag::ext_delimited_escape_sequence) + << /*delimited*/ 0 << (Features.CPlusPlus ? 1 : 0); } } @@ -641,8 +642,9 @@ static bool ProcessUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf, if ((IsDelimitedEscapeSequence || IsNamedEscapeSequence) && Diags) Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf, - diag::ext_delimited_escape_sequence) - << (IsNamedEscapeSequence ? 1 : 0); + Features.CPlusPlus2b ? diag::warn_cxx2b_delimited_escape_sequence + : diag::ext_delimited_escape_sequence) + << (IsNamedEscapeSequence ? 1 : 0) << (Features.CPlusPlus ? 1 : 0); return true; } diff --git a/contrib/llvm-project/clang/lib/Lex/MacroInfo.cpp b/contrib/llvm-project/clang/lib/Lex/MacroInfo.cpp index 310b95f36771..eae12beb6244 100644 --- a/contrib/llvm-project/clang/lib/Lex/MacroInfo.cpp +++ b/contrib/llvm-project/clang/lib/Lex/MacroInfo.cpp @@ -213,7 +213,7 @@ MacroDirective::DefInfo MacroDirective::getDefinition() { isPublic = VisMD->isPublic(); } - return DefInfo(nullptr, UndefLoc, !isPublic || isPublic.getValue()); + return DefInfo(nullptr, UndefLoc, !isPublic || isPublic.value()); } const MacroDirective::DefInfo diff --git a/contrib/llvm-project/clang/lib/Lex/ModuleMap.cpp b/contrib/llvm-project/clang/lib/Lex/ModuleMap.cpp index c791e3e4e5ca..57e344622f25 100644 --- a/contrib/llvm-project/clang/lib/Lex/ModuleMap.cpp +++ b/contrib/llvm-project/clang/lib/Lex/ModuleMap.cpp @@ -1219,8 +1219,8 @@ void ModuleMap::resolveHeaderDirectives( Module *Mod, llvm::Optional File) const { bool NeedsFramework = false; SmallVector NewHeaders; - const auto Size = File ? File.getValue()->getSize() : 0; - const auto ModTime = File ? File.getValue()->getModificationTime() : 0; + const auto Size = File ? File.value()->getSize() : 0; + const auto ModTime = File ? File.value()->getModificationTime() : 0; for (auto &Header : Mod->UnresolvedHeaders) { if (File && ((Header.ModTime && Header.ModTime != ModTime) || diff --git a/contrib/llvm-project/clang/lib/Lex/PPDirectives.cpp b/contrib/llvm-project/clang/lib/Lex/PPDirectives.cpp index 4dcef01e3e4c..352e1f217819 100644 --- a/contrib/llvm-project/clang/lib/Lex/PPDirectives.cpp +++ b/contrib/llvm-project/clang/lib/Lex/PPDirectives.cpp @@ -1983,6 +1983,10 @@ void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc, EnterAnnotationToken(SourceRange(HashLoc, EndLoc), tok::annot_module_begin, Action.ModuleForHeader); break; + case ImportAction::HeaderUnitImport: + EnterAnnotationToken(SourceRange(HashLoc, EndLoc), tok::annot_header_unit, + Action.ModuleForHeader); + break; case ImportAction::ModuleImport: EnterAnnotationToken(SourceRange(HashLoc, EndLoc), tok::annot_module_include, Action.ModuleForHeader); @@ -2191,6 +2195,17 @@ Preprocessor::ImportAction Preprocessor::HandleHeaderIncludeOrImport( // known to have no effect beyond its effect on module visibility -- that is, // if it's got an include guard that is already defined, set to Import if it // is a modular header we've already built and should import. + + // For C++20 Modules + // [cpp.include]/7 If the header identified by the header-name denotes an + // importable header, it is implementation-defined whether the #include + // preprocessing directive is instead replaced by an import directive. + // For this implementation, the translation is permitted when we are parsing + // the Global Module Fragment, and not otherwise (the cases where it would be + // valid to replace an include with an import are highly constrained once in + // named module purview; this choice avoids considerable complexity in + // determining valid cases). + enum { Enter, Import, Skip, IncludeLimitReached } Action = Enter; if (PPOpts->SingleFileParseMode) @@ -2203,13 +2218,34 @@ Preprocessor::ImportAction Preprocessor::HandleHeaderIncludeOrImport( alreadyIncluded(*File)) Action = IncludeLimitReached; + bool MaybeTranslateInclude = Action == Enter && File && SuggestedModule && + !isForModuleBuilding(SuggestedModule.getModule(), + getLangOpts().CurrentModule, + getLangOpts().ModuleName); + + // FIXME: We do not have a good way to disambiguate C++ clang modules from + // C++ standard modules (other than use/non-use of Header Units). + Module *SM = SuggestedModule.getModule(); + // Maybe a usable Header Unit + bool UsableHeaderUnit = false; + if (getLangOpts().CPlusPlusModules && SM && SM->isHeaderUnit()) { + if (TrackGMFState.inGMF() || IsImportDecl) + UsableHeaderUnit = true; + else if (!IsImportDecl) { + // This is a Header Unit that we do not include-translate + SuggestedModule = ModuleMap::KnownHeader(); + SM = nullptr; + } + } + // Maybe a usable clang header module. + bool UsableHeaderModule = + (getLangOpts().CPlusPlusModules || getLangOpts().Modules) && SM && + !SM->isHeaderUnit(); + // Determine whether we should try to import the module for this #include, if // there is one. Don't do so if precompiled module support is disabled or we // are processing this module textually (because we're building the module). - if (Action == Enter && File && SuggestedModule && getLangOpts().Modules && - !isForModuleBuilding(SuggestedModule.getModule(), - getLangOpts().CurrentModule, - getLangOpts().ModuleName)) { + if (MaybeTranslateInclude && (UsableHeaderUnit || UsableHeaderModule)) { // If this include corresponds to a module but that module is // unavailable, diagnose the situation and bail out. // FIXME: Remove this; loadModule does the same check (but produces @@ -2226,7 +2262,7 @@ Preprocessor::ImportAction Preprocessor::HandleHeaderIncludeOrImport( // FIXME: Should we have a second loadModule() overload to avoid this // extra lookup step? SmallVector, 2> Path; - for (Module *Mod = SuggestedModule.getModule(); Mod; Mod = Mod->Parent) + for (Module *Mod = SM; Mod; Mod = Mod->Parent) Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name), FilenameTok.getLocation())); std::reverse(Path.begin(), Path.end()); @@ -2293,9 +2329,12 @@ Preprocessor::ImportAction Preprocessor::HandleHeaderIncludeOrImport( // Ask HeaderInfo if we should enter this #include file. If not, #including // this file will have no effect. if (Action == Enter && File && - !HeaderInfo.ShouldEnterIncludeFile( - *this, &File->getFileEntry(), EnterOnce, getLangOpts().Modules, - SuggestedModule.getModule(), IsFirstIncludeOfFile)) { + !HeaderInfo.ShouldEnterIncludeFile(*this, &File->getFileEntry(), + EnterOnce, getLangOpts().Modules, SM, + IsFirstIncludeOfFile)) { + // C++ standard modules: + // If we are not in the GMF, then we textually include only + // clang modules: // Even if we've already preprocessed this header once and know that we // don't need to see its contents again, we still need to import it if it's // modular because we might not have imported it from this submodule before. @@ -2303,7 +2342,10 @@ Preprocessor::ImportAction Preprocessor::HandleHeaderIncludeOrImport( // FIXME: We don't do this when compiling a PCH because the AST // serialization layer can't cope with it. This means we get local // submodule visibility semantics wrong in that case. - Action = (SuggestedModule && !getLangOpts().CompilingPCH) ? Import : Skip; + if (UsableHeaderUnit && !getLangOpts().CompilingPCH) + Action = TrackGMFState.inGMF() ? Import : Skip; + else + Action = (SuggestedModule && !getLangOpts().CompilingPCH) ? Import : Skip; } // Check for circular inclusion of the main file. @@ -2440,8 +2482,8 @@ Preprocessor::ImportAction Preprocessor::HandleHeaderIncludeOrImport( switch (Action) { case Skip: // If we don't need to enter the file, stop now. - if (Module *M = SuggestedModule.getModule()) - return {ImportAction::SkippedModuleImport, M}; + if (SM) + return {ImportAction::SkippedModuleImport, SM}; return {ImportAction::None}; case IncludeLimitReached: @@ -2451,16 +2493,15 @@ Preprocessor::ImportAction Preprocessor::HandleHeaderIncludeOrImport( case Import: { // If this is a module import, make it visible if needed. - Module *M = SuggestedModule.getModule(); - assert(M && "no module to import"); + assert(SM && "no module to import"); - makeModuleVisible(M, EndLoc); + makeModuleVisible(SM, EndLoc); if (IncludeTok.getIdentifierInfo()->getPPKeywordID() == tok::pp___include_macros) return {ImportAction::None}; - return {ImportAction::ModuleImport, M}; + return {ImportAction::ModuleImport, SM}; } case Enter: @@ -2492,13 +2533,14 @@ Preprocessor::ImportAction Preprocessor::HandleHeaderIncludeOrImport( return {ImportAction::None}; // Determine if we're switching to building a new submodule, and which one. - if (auto *M = SuggestedModule.getModule()) { - if (M->getTopLevelModule()->ShadowingModule) { + // This does not apply for C++20 modules header units. + if (SM && !SM->isHeaderUnit()) { + if (SM->getTopLevelModule()->ShadowingModule) { // We are building a submodule that belongs to a shadowed module. This // means we find header files in the shadowed module. - Diag(M->DefinitionLoc, diag::err_module_build_shadowed_submodule) - << M->getFullModuleName(); - Diag(M->getTopLevelModule()->ShadowingModule->DefinitionLoc, + Diag(SM->DefinitionLoc, diag::err_module_build_shadowed_submodule) + << SM->getFullModuleName(); + Diag(SM->getTopLevelModule()->ShadowingModule->DefinitionLoc, diag::note_previous_definition); return {ImportAction::None}; } @@ -2511,22 +2553,22 @@ Preprocessor::ImportAction Preprocessor::HandleHeaderIncludeOrImport( // that PCH, which means we should enter the submodule. We need to teach // the AST serialization layer to deal with the resulting AST. if (getLangOpts().CompilingPCH && - isForModuleBuilding(M, getLangOpts().CurrentModule, + isForModuleBuilding(SM, getLangOpts().CurrentModule, getLangOpts().ModuleName)) return {ImportAction::None}; assert(!CurLexerSubmodule && "should not have marked this as a module yet"); - CurLexerSubmodule = M; + CurLexerSubmodule = SM; // Let the macro handling code know that any future macros are within // the new submodule. - EnterSubmodule(M, EndLoc, /*ForPragma*/false); + EnterSubmodule(SM, EndLoc, /*ForPragma*/ false); // Let the parser know that any future declarations are within the new // submodule. // FIXME: There's no point doing this if we're handling a #__include_macros // directive. - return {ImportAction::ModuleBegin, M}; + return {ImportAction::ModuleBegin, SM}; } assert(!IsImportDecl && "failed to diagnose missing module for import decl"); diff --git a/contrib/llvm-project/clang/lib/Lex/PPMacroExpansion.cpp b/contrib/llvm-project/clang/lib/Lex/PPMacroExpansion.cpp index bf46e5422bc8..f3be2107f985 100644 --- a/contrib/llvm-project/clang/lib/Lex/PPMacroExpansion.cpp +++ b/contrib/llvm-project/clang/lib/Lex/PPMacroExpansion.cpp @@ -1326,10 +1326,10 @@ already_lexed: // The last ')' has been reached; return the value if one found or // a diagnostic and a dummy value. if (Result) { - OS << Result.getValue(); + OS << Result.value(); // For strict conformance to __has_cpp_attribute rules, use 'L' // suffix for dated literals. - if (Result.getValue() > 1) + if (Result.value() > 1) OS << 'L'; } else { OS << 0; diff --git a/contrib/llvm-project/clang/lib/Lex/PreprocessingRecord.cpp b/contrib/llvm-project/clang/lib/Lex/PreprocessingRecord.cpp index 673ef637e396..2146a7c04217 100644 --- a/contrib/llvm-project/clang/lib/Lex/PreprocessingRecord.cpp +++ b/contrib/llvm-project/clang/lib/Lex/PreprocessingRecord.cpp @@ -115,7 +115,7 @@ bool PreprocessingRecord::isEntityInFileID(iterator PPEI, FileID FID) { Optional IsInFile = ExternalSource->isPreprocessedEntityInFileID(LoadedIndex, FID); if (IsInFile) - return IsInFile.getValue(); + return IsInFile.value(); // The external source did not provide a definite answer, go and deserialize // the entity to check it. diff --git a/contrib/llvm-project/clang/lib/Lex/Preprocessor.cpp b/contrib/llvm-project/clang/lib/Lex/Preprocessor.cpp index 281f01fb28a4..5310db3c882b 100644 --- a/contrib/llvm-project/clang/lib/Lex/Preprocessor.cpp +++ b/contrib/llvm-project/clang/lib/Lex/Preprocessor.cpp @@ -941,6 +941,9 @@ void Preprocessor::Lex(Token &Result) { // Update ImportSeqState to track our position within a C++20 import-seq // if this token is being produced as a result of phase 4 of translation. + // Update TrackGMFState to decide if we are currently in a Global Module + // Fragment. GMF state updates should precede ImportSeq ones, since GMF state + // depends on the prevailing ImportSeq state in two cases. if (getLangOpts().CPlusPlusModules && LexLevel == 1 && !Result.getFlag(Token::IsReinjected)) { switch (Result.getKind()) { @@ -953,7 +956,11 @@ void Preprocessor::Lex(Token &Result) { case tok::r_brace: ImportSeqState.handleCloseBrace(); break; + // This token is injected to represent the translation of '#include "a.h"' + // into "import a.h;". Mimic the notional ';'. + case tok::annot_module_include: case tok::semi: + TrackGMFState.handleSemi(); ImportSeqState.handleSemi(); break; case tok::header_name: @@ -961,10 +968,12 @@ void Preprocessor::Lex(Token &Result) { ImportSeqState.handleHeaderName(); break; case tok::kw_export: + TrackGMFState.handleExport(); ImportSeqState.handleExport(); break; case tok::identifier: if (Result.getIdentifierInfo()->isModulesImport()) { + TrackGMFState.handleImport(ImportSeqState.afterTopLevelSeq()); ImportSeqState.handleImport(); if (ImportSeqState.afterImportSeq()) { ModuleImportLoc = Result.getLocation(); @@ -973,9 +982,13 @@ void Preprocessor::Lex(Token &Result) { CurLexerKind = CLK_LexAfterModuleImport; } break; + } else if (Result.getIdentifierInfo() == getIdentifierInfo("module")) { + TrackGMFState.handleModule(ImportSeqState.afterTopLevelSeq()); + break; } LLVM_FALLTHROUGH; default: + TrackGMFState.handleMisc(); ImportSeqState.handleMisc(); break; } @@ -1222,6 +1235,7 @@ bool Preprocessor::LexAfterModuleImport(Token &Result) { LLVM_FALLTHROUGH; case ImportAction::ModuleImport: + case ImportAction::HeaderUnitImport: case ImportAction::SkippedModuleImport: // We chose to import (or textually enter) the file. Convert the // header-name token into a header unit annotation token. diff --git a/contrib/llvm-project/clang/lib/Parse/ParseOpenMP.cpp b/contrib/llvm-project/clang/lib/Parse/ParseOpenMP.cpp index 08dccf9e43f7..5f53f9d684e7 100644 --- a/contrib/llvm-project/clang/lib/Parse/ParseOpenMP.cpp +++ b/contrib/llvm-project/clang/lib/Parse/ParseOpenMP.cpp @@ -1884,11 +1884,11 @@ void Parser::ParseOMPDeclareTargetClauses( if (DevTypeData) { if (DeviceTypeLoc.isValid()) { // We already saw another device_type clause, diagnose it. - Diag(DevTypeData.getValue().Loc, + Diag(DevTypeData.value().Loc, diag::warn_omp_more_one_device_type_clause); break; } - switch (static_cast(DevTypeData.getValue().Type)) { + switch (static_cast(DevTypeData.value().Type)) { case OMPC_DEVICE_TYPE_any: DTCI.DT = OMPDeclareTargetDeclAttr::DT_Any; break; @@ -3634,20 +3634,20 @@ OMPClause *Parser::ParseOpenMPSimpleClause(OpenMPClauseKind Kind, if (!Val || ParseOnly) return nullptr; if (getLangOpts().OpenMP < 51 && Kind == OMPC_default && - (static_cast(Val.getValue().Type) == OMP_DEFAULT_private || - static_cast(Val.getValue().Type) == + (static_cast(Val.value().Type) == OMP_DEFAULT_private || + static_cast(Val.value().Type) == OMP_DEFAULT_firstprivate)) { - Diag(Val.getValue().LOpen, diag::err_omp_invalid_dsa) - << getOpenMPClauseName(static_cast(Val.getValue().Type) == + Diag(Val.value().LOpen, diag::err_omp_invalid_dsa) + << getOpenMPClauseName(static_cast(Val.value().Type) == OMP_DEFAULT_private ? OMPC_private : OMPC_firstprivate) << getOpenMPClauseName(OMPC_default) << "5.1"; return nullptr; } - return Actions.ActOnOpenMPSimpleClause( - Kind, Val.getValue().Type, Val.getValue().TypeLoc, Val.getValue().LOpen, - Val.getValue().Loc, Val.getValue().RLoc); + return Actions.ActOnOpenMPSimpleClause(Kind, Val.value().Type, + Val.value().TypeLoc, Val.value().LOpen, + Val.value().Loc, Val.value().RLoc); } /// Parsing of OpenMP clauses like 'ordered'. diff --git a/contrib/llvm-project/clang/lib/Parse/Parser.cpp b/contrib/llvm-project/clang/lib/Parse/Parser.cpp index 6f63d01bc8ad..ab8748c2c63d 100644 --- a/contrib/llvm-project/clang/lib/Parse/Parser.cpp +++ b/contrib/llvm-project/clang/lib/Parse/Parser.cpp @@ -663,12 +663,22 @@ bool Parser::ParseTopLevelDecl(DeclGroupPtrTy &Result, return false; } - case tok::annot_module_include: - Actions.ActOnModuleInclude(Tok.getLocation(), - reinterpret_cast( - Tok.getAnnotationValue())); + case tok::annot_module_include: { + auto Loc = Tok.getLocation(); + Module *Mod = reinterpret_cast(Tok.getAnnotationValue()); + // FIXME: We need a better way to disambiguate C++ clang modules and + // standard C++ modules. + if (!getLangOpts().CPlusPlusModules || !Mod->isHeaderUnit()) + Actions.ActOnModuleInclude(Loc, Mod); + else { + DeclResult Import = + Actions.ActOnModuleImport(Loc, SourceLocation(), Loc, Mod); + Decl *ImportDecl = Import.isInvalid() ? nullptr : Import.get(); + Result = Actions.ConvertDeclToDeclGroup(ImportDecl); + } ConsumeAnnotationToken(); return false; + } case tok::annot_module_begin: Actions.ActOnModuleBegin(Tok.getLocation(), reinterpret_cast( diff --git a/contrib/llvm-project/clang/lib/Sema/HLSLExternalSemaSource.cpp b/contrib/llvm-project/clang/lib/Sema/HLSLExternalSemaSource.cpp new file mode 100644 index 000000000000..56c2dd40bd9a --- /dev/null +++ b/contrib/llvm-project/clang/lib/Sema/HLSLExternalSemaSource.cpp @@ -0,0 +1,96 @@ +//===--- HLSLExternalSemaSource.cpp - HLSL Sema Source --------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// +//===----------------------------------------------------------------------===// + +#include "clang/Sema/HLSLExternalSemaSource.h" +#include "clang/AST/ASTContext.h" +#include "clang/AST/DeclCXX.h" +#include "clang/Basic/AttrKinds.h" +#include "clang/Sema/Sema.h" + +using namespace clang; + +HLSLExternalSemaSource::~HLSLExternalSemaSource() {} + +void HLSLExternalSemaSource::InitializeSema(Sema &S) { + SemaPtr = &S; + ASTContext &AST = SemaPtr->getASTContext(); + IdentifierInfo &HLSL = AST.Idents.get("hlsl", tok::TokenKind::identifier); + HLSLNamespace = + NamespaceDecl::Create(AST, AST.getTranslationUnitDecl(), false, + SourceLocation(), SourceLocation(), &HLSL, nullptr); + HLSLNamespace->setImplicit(true); + AST.getTranslationUnitDecl()->addDecl(HLSLNamespace); + defineHLSLVectorAlias(); + + // This adds a `using namespace hlsl` directive. In DXC, we don't put HLSL's + // built in types inside a namespace, but we are planning to change that in + // the near future. In order to be source compatible older versions of HLSL + // will need to implicitly use the hlsl namespace. For now in clang everything + // will get added to the namespace, and we can remove the using directive for + // future language versions to match HLSL's evolution. + auto *UsingDecl = UsingDirectiveDecl::Create( + AST, AST.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), + NestedNameSpecifierLoc(), SourceLocation(), HLSLNamespace, + AST.getTranslationUnitDecl()); + + AST.getTranslationUnitDecl()->addDecl(UsingDecl); +} + +void HLSLExternalSemaSource::defineHLSLVectorAlias() { + ASTContext &AST = SemaPtr->getASTContext(); + + llvm::SmallVector TemplateParams; + + auto *TypeParam = TemplateTypeParmDecl::Create( + AST, HLSLNamespace, SourceLocation(), SourceLocation(), 0, 0, + &AST.Idents.get("element", tok::TokenKind::identifier), false, false); + TypeParam->setDefaultArgument(AST.getTrivialTypeSourceInfo(AST.FloatTy)); + + TemplateParams.emplace_back(TypeParam); + + auto *SizeParam = NonTypeTemplateParmDecl::Create( + AST, HLSLNamespace, SourceLocation(), SourceLocation(), 0, 1, + &AST.Idents.get("element_count", tok::TokenKind::identifier), AST.IntTy, + false, AST.getTrivialTypeSourceInfo(AST.IntTy)); + Expr *LiteralExpr = + IntegerLiteral::Create(AST, llvm::APInt(AST.getIntWidth(AST.IntTy), 4), + AST.IntTy, SourceLocation()); + SizeParam->setDefaultArgument(LiteralExpr); + TemplateParams.emplace_back(SizeParam); + + auto *ParamList = + TemplateParameterList::Create(AST, SourceLocation(), SourceLocation(), + TemplateParams, SourceLocation(), nullptr); + + IdentifierInfo &II = AST.Idents.get("vector", tok::TokenKind::identifier); + + QualType AliasType = AST.getDependentSizedExtVectorType( + AST.getTemplateTypeParmType(0, 0, false, TypeParam), + DeclRefExpr::Create( + AST, NestedNameSpecifierLoc(), SourceLocation(), SizeParam, false, + DeclarationNameInfo(SizeParam->getDeclName(), SourceLocation()), + AST.IntTy, VK_LValue), + SourceLocation()); + + auto *Record = TypeAliasDecl::Create(AST, HLSLNamespace, SourceLocation(), + SourceLocation(), &II, + AST.getTrivialTypeSourceInfo(AliasType)); + Record->setImplicit(true); + + auto *Template = + TypeAliasTemplateDecl::Create(AST, HLSLNamespace, SourceLocation(), + Record->getIdentifier(), ParamList, Record); + + Record->setDescribedAliasTemplate(Template); + Template->setImplicit(true); + Template->setLexicalDeclContext(Record->getDeclContext()); + HLSLNamespace->addDecl(Template); +} diff --git a/contrib/llvm-project/clang/lib/Sema/SemaCUDA.cpp b/contrib/llvm-project/clang/lib/Sema/SemaCUDA.cpp index 8f8144d658d8..185ccebe2717 100644 --- a/contrib/llvm-project/clang/lib/Sema/SemaCUDA.cpp +++ b/contrib/llvm-project/clang/lib/Sema/SemaCUDA.cpp @@ -381,13 +381,13 @@ bool Sema::inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, InferredTarget = BaseMethodTarget; } else { bool ResolutionError = resolveCalleeCUDATargetConflict( - InferredTarget.getValue(), BaseMethodTarget, + InferredTarget.value(), BaseMethodTarget, InferredTarget.getPointer()); if (ResolutionError) { if (Diagnose) { Diag(ClassDecl->getLocation(), diag::note_implicit_member_target_infer_collision) - << (unsigned)CSM << InferredTarget.getValue() << BaseMethodTarget; + << (unsigned)CSM << InferredTarget.value() << BaseMethodTarget; } MemberDecl->addAttr(CUDAInvalidTargetAttr::CreateImplicit(Context)); return true; @@ -425,14 +425,13 @@ bool Sema::inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, InferredTarget = FieldMethodTarget; } else { bool ResolutionError = resolveCalleeCUDATargetConflict( - InferredTarget.getValue(), FieldMethodTarget, + InferredTarget.value(), FieldMethodTarget, InferredTarget.getPointer()); if (ResolutionError) { if (Diagnose) { Diag(ClassDecl->getLocation(), diag::note_implicit_member_target_infer_collision) - << (unsigned)CSM << InferredTarget.getValue() - << FieldMethodTarget; + << (unsigned)CSM << InferredTarget.value() << FieldMethodTarget; } MemberDecl->addAttr(CUDAInvalidTargetAttr::CreateImplicit(Context)); return true; @@ -445,9 +444,9 @@ bool Sema::inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, // it's the least restrictive option that can be invoked from any target. bool NeedsH = true, NeedsD = true; if (InferredTarget) { - if (InferredTarget.getValue() == CFT_Device) + if (InferredTarget.value() == CFT_Device) NeedsH = false; - else if (InferredTarget.getValue() == CFT_Host) + else if (InferredTarget.value() == CFT_Host) NeedsD = false; } diff --git a/contrib/llvm-project/clang/lib/Sema/SemaChecking.cpp b/contrib/llvm-project/clang/lib/Sema/SemaChecking.cpp index 79420cc27699..aed1d9befe2b 100644 --- a/contrib/llvm-project/clang/lib/Sema/SemaChecking.cpp +++ b/contrib/llvm-project/clang/lib/Sema/SemaChecking.cpp @@ -109,6 +109,11 @@ SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, Context.getTargetInfo()); } +static constexpr unsigned short combineFAPK(Sema::FormatArgumentPassingKind A, + Sema::FormatArgumentPassingKind B) { + return (A << 8) | B; +} + /// Checks that a call expression's argument count is at least the desired /// number. This is useful when doing custom type-checking on a variadic /// function. Returns true on error. @@ -1875,7 +1880,7 @@ static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { }(); if (DiagSelect) { S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) - << DiagSelect.getValue() << TheCall->getSourceRange(); + << DiagSelect.value() << TheCall->getSourceRange(); return ExprError(); } @@ -2408,7 +2413,7 @@ Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, bool ReturnsPointer = BuiltinID == Builtin::BIaddressof || BuiltinID == Builtin::BI__addressof; if (!(Param->isReferenceType() && - (ReturnsPointer ? Result->isPointerType() + (ReturnsPointer ? Result->isAnyPointerType() : Result->isReferenceType()) && Context.hasSameUnqualifiedType(Param->getPointeeType(), Result->getPointeeType()))) { @@ -5403,10 +5408,16 @@ bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, /// Returns true when the format fits the function and the FormatStringInfo has /// been populated. bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, - FormatStringInfo *FSI) { - FSI->HasVAListArg = Format->getFirstArg() == 0; + bool IsVariadic, FormatStringInfo *FSI) { + if (Format->getFirstArg() == 0) + FSI->ArgPassingKind = FAPK_VAList; + else if (IsVariadic) + FSI->ArgPassingKind = FAPK_Variadic; + else + FSI->ArgPassingKind = FAPK_Fixed; FSI->FormatIdx = Format->getFormatIdx() - 1; - FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; + FSI->FirstDataArg = + FSI->ArgPassingKind == FAPK_VAList ? 0 : Format->getFirstArg() - 1; // The way the format attribute works in GCC, the implicit this argument // of member functions is counted. However, it doesn't appear in our own @@ -5461,7 +5472,7 @@ static void CheckNonNullArgument(Sema &S, bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { FormatStringInfo FSI; if ((GetFormatStringType(Format) == FST_NSString) && - getFormatStringInfo(Format, false, &FSI)) { + getFormatStringInfo(Format, false, true, &FSI)) { Idx = FSI.FormatIdx; return true; } @@ -5615,6 +5626,40 @@ static void CheckNonNullArguments(Sema &S, } } +// 16 byte ByVal alignment not due to a vector member is not honoured by XL +// on AIX. Emit a warning here that users are generating binary incompatible +// code to be safe. +// Here we try to get information about the alignment of the struct member +// from the struct passed to the caller function. We only warn when the struct +// is passed byval, hence the series of checks and early returns if we are a not +// passing a struct byval. +void Sema::checkAIXMemberAlignment(SourceLocation Loc, const Expr *Arg) { + const auto *ICE = dyn_cast(Arg->IgnoreParens()); + if (!ICE) + return; + + const auto *DR = dyn_cast(ICE->getSubExpr()); + if (!DR) + return; + + const auto *PD = dyn_cast(DR->getDecl()); + if (!PD || !PD->getType()->isRecordType()) + return; + + QualType ArgType = Arg->getType(); + for (const FieldDecl *FD : + ArgType->castAs()->getDecl()->fields()) { + if (const auto *AA = FD->getAttr()) { + CharUnits Alignment = + Context.toCharUnitsFromBits(AA->getAlignment(Context)); + if (Alignment.getQuantity() == 16) { + Diag(FD->getLocation(), diag::warn_not_xl_compatible) << FD; + Diag(Loc, diag::note_misaligned_member_used_here) << PD; + } + } + } +} + /// Warn if a pointer or reference argument passed to a function points to an /// object that is less aligned than the parameter. This can happen when /// creating a typedef with a lower alignment than the original type and then @@ -5725,6 +5770,12 @@ void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, if (Arg->containsErrors()) continue; + if (Context.getTargetInfo().getTriple().isOSAIX() && FDecl && Arg && + FDecl->hasLinkage() && + FDecl->getFormalLinkage() != InternalLinkage && + CallType == VariadicDoesNotApply) + checkAIXMemberAlignment((Arg->getExprLoc()), Arg); + QualType ParamTy = Proto->getParamType(ArgIdx); QualType ArgTy = Arg->getType(); CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1), @@ -7695,7 +7746,7 @@ bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { llvm::SmallBitVector CheckedVarArgs(NumArgs, false); ArrayRef Args(TheCall->getArgs(), TheCall->getNumArgs()); bool Success = CheckFormatArguments( - Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, + Args, FAPK_Variadic, FormatIdx, FirstDataArg, FST_OSLog, VariadicFunction, TheCall->getBeginLoc(), SourceRange(), CheckedVarArgs); if (!Success) @@ -8412,19 +8463,15 @@ class FormatStringLiteral { SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } }; -} // namespace +} // namespace -static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, - const Expr *OrigFormatExpr, - ArrayRef Args, - bool HasVAListArg, unsigned format_idx, - unsigned firstDataArg, - Sema::FormatStringType Type, - bool inFunctionCall, - Sema::VariadicCallType CallType, - llvm::SmallBitVector &CheckedVarArgs, - UncoveredArgHandler &UncoveredArg, - bool IgnoreStringsWithoutSpecifiers); +static void CheckFormatString( + Sema &S, const FormatStringLiteral *FExpr, const Expr *OrigFormatExpr, + ArrayRef Args, Sema::FormatArgumentPassingKind APK, + unsigned format_idx, unsigned firstDataArg, Sema::FormatStringType Type, + bool inFunctionCall, Sema::VariadicCallType CallType, + llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg, + bool IgnoreStringsWithoutSpecifiers); // Determine if an expression is a string literal or constant string. // If this function returns false on the arguments to a function expecting a @@ -8432,16 +8479,15 @@ static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, // True string literals are then checked by CheckFormatString. static StringLiteralCheckType checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef Args, - bool HasVAListArg, unsigned format_idx, + Sema::FormatArgumentPassingKind APK, unsigned format_idx, unsigned firstDataArg, Sema::FormatStringType Type, Sema::VariadicCallType CallType, bool InFunctionCall, llvm::SmallBitVector &CheckedVarArgs, - UncoveredArgHandler &UncoveredArg, - llvm::APSInt Offset, + UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset, bool IgnoreStringsWithoutSpecifiers = false) { if (S.isConstantEvaluated()) return SLCT_NotALiteral; - tryAgain: +tryAgain: assert(Offset.isSigned() && "invalid offset"); if (E->isTypeDependent() || E->isValueDependent()) @@ -8486,9 +8532,8 @@ checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef Args, if (!CheckLeft) Left = SLCT_UncheckedLiteral; else { - Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, - HasVAListArg, format_idx, firstDataArg, - Type, CallType, InFunctionCall, + Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, APK, format_idx, + firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, IgnoreStringsWithoutSpecifiers); if (Left == SLCT_NotALiteral || !CheckRight) { @@ -8497,8 +8542,8 @@ checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef Args, } StringLiteralCheckType Right = checkFormatStringExpr( - S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, - Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, + S, C->getFalseExpr(), Args, APK, format_idx, firstDataArg, Type, + CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, IgnoreStringsWithoutSpecifiers); return (CheckLeft && Left < Right) ? Left : Right; @@ -8548,42 +8593,85 @@ checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef Args, if (InitList->isStringLiteralInit()) Init = InitList->getInit(0)->IgnoreParenImpCasts(); } - return checkFormatStringExpr(S, Init, Args, - HasVAListArg, format_idx, - firstDataArg, Type, CallType, - /*InFunctionCall*/ false, CheckedVarArgs, - UncoveredArg, Offset); + return checkFormatStringExpr( + S, Init, Args, APK, format_idx, firstDataArg, Type, CallType, + /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg, Offset); } } - // For vprintf* functions (i.e., HasVAListArg==true), we add a - // special check to see if the format string is a function parameter - // of the function calling the printf function. If the function - // has an attribute indicating it is a printf-like function, then we - // should suppress warnings concerning non-literals being used in a call - // to a vprintf function. For example: + // When the format argument is an argument of this function, and this + // function also has the format attribute, there are several interactions + // for which there shouldn't be a warning. For instance, when calling + // v*printf from a function that has the printf format attribute, we + // should not emit a warning about using `fmt`, even though it's not + // constant, because the arguments have already been checked for the + // caller of `logmessage`: // - // void - // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ - // va_list ap; - // va_start(ap, fmt); - // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". - // ... + // __attribute__((format(printf, 1, 2))) + // void logmessage(char const *fmt, ...) { + // va_list ap; + // va_start(ap, fmt); + // vprintf(fmt, ap); /* do not emit a warning about "fmt" */ + // ... // } - if (HasVAListArg) { - if (const ParmVarDecl *PV = dyn_cast(VD)) { - if (const Decl *D = dyn_cast(PV->getDeclContext())) { - int PVIndex = PV->getFunctionScopeIndex() + 1; - for (const auto *PVFormat : D->specific_attrs()) { - // adjust for implicit parameter - if (const CXXMethodDecl *MD = dyn_cast(D)) - if (MD->isInstance()) - ++PVIndex; + // + // Another interaction that we need to support is calling a variadic + // format function from a format function that has fixed arguments. For + // instance: + // + // __attribute__((format(printf, 1, 2))) + // void logstring(char const *fmt, char const *str) { + // printf(fmt, str); /* do not emit a warning about "fmt" */ + // } + // + // Same (and perhaps more relatably) for the variadic template case: + // + // template + // __attribute__((format(printf, 1, 2))) + // void log(const char *fmt, Args&&... args) { + // printf(fmt, forward(args)...); + // /* do not emit a warning about "fmt" */ + // } + // + // Due to implementation difficulty, we only check the format, not the + // format arguments, in all cases. + // + if (const auto *PV = dyn_cast(VD)) { + if (const auto *D = dyn_cast(PV->getDeclContext())) { + for (const auto *PVFormat : D->specific_attrs()) { + bool IsCXXMember = false; + if (const auto *MD = dyn_cast(D)) + IsCXXMember = MD->isInstance(); + + bool IsVariadic = false; + if (const FunctionType *FnTy = D->getFunctionType()) + IsVariadic = cast(FnTy)->isVariadic(); + else if (const auto *BD = dyn_cast(D)) + IsVariadic = BD->isVariadic(); + else if (const auto *OMD = dyn_cast(D)) + IsVariadic = OMD->isVariadic(); + + Sema::FormatStringInfo CallerFSI; + if (Sema::getFormatStringInfo(PVFormat, IsCXXMember, IsVariadic, + &CallerFSI)) { // We also check if the formats are compatible. // We can't pass a 'scanf' string to a 'printf' function. - if (PVIndex == PVFormat->getFormatIdx() && - Type == S.GetFormatStringType(PVFormat)) - return SLCT_UncheckedLiteral; + if (PV->getFunctionScopeIndex() == CallerFSI.FormatIdx && + Type == S.GetFormatStringType(PVFormat)) { + // Lastly, check that argument passing kinds transition in a + // way that makes sense: + // from a caller with FAPK_VAList, allow FAPK_VAList + // from a caller with FAPK_Fixed, allow FAPK_Fixed + // from a caller with FAPK_Fixed, allow FAPK_Variadic + // from a caller with FAPK_Variadic, allow FAPK_VAList + switch (combineFAPK(CallerFSI.ArgPassingKind, APK)) { + case combineFAPK(Sema::FAPK_VAList, Sema::FAPK_VAList): + case combineFAPK(Sema::FAPK_Fixed, Sema::FAPK_Fixed): + case combineFAPK(Sema::FAPK_Fixed, Sema::FAPK_Variadic): + case combineFAPK(Sema::FAPK_Variadic, Sema::FAPK_VAList): + return SLCT_UncheckedLiteral; + } + } } } } @@ -8602,8 +8690,8 @@ checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef Args, for (const auto *FA : ND->specific_attrs()) { const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); StringLiteralCheckType Result = checkFormatStringExpr( - S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, - CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, + S, Arg, Args, APK, format_idx, firstDataArg, Type, CallType, + InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, IgnoreStringsWithoutSpecifiers); if (IsFirst) { CommonResult = Result; @@ -8618,12 +8706,10 @@ checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef Args, if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { const Expr *Arg = CE->getArg(0); - return checkFormatStringExpr(S, Arg, Args, - HasVAListArg, format_idx, - firstDataArg, Type, CallType, - InFunctionCall, CheckedVarArgs, - UncoveredArg, Offset, - IgnoreStringsWithoutSpecifiers); + return checkFormatStringExpr( + S, Arg, Args, APK, format_idx, firstDataArg, Type, CallType, + InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, + IgnoreStringsWithoutSpecifiers); } } } @@ -8651,8 +8737,8 @@ checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef Args, const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); return checkFormatStringExpr( - S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, - CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, + S, Arg, Args, APK, format_idx, firstDataArg, Type, CallType, + InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, IgnoreStringsWithoutSpecifiers); } } @@ -8675,9 +8761,8 @@ checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef Args, return SLCT_NotALiteral; } FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); - CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, - firstDataArg, Type, InFunctionCall, CallType, - CheckedVarArgs, UncoveredArg, + CheckFormatString(S, &FStr, E, Args, APK, format_idx, firstDataArg, Type, + InFunctionCall, CallType, CheckedVarArgs, UncoveredArg, IgnoreStringsWithoutSpecifiers); return SLCT_CheckedLiteral; } @@ -8756,24 +8841,25 @@ Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { /// functions) for correct use of format strings. /// Returns true if a format string has been fully checked. bool Sema::CheckFormatArguments(const FormatAttr *Format, - ArrayRef Args, - bool IsCXXMember, - VariadicCallType CallType, - SourceLocation Loc, SourceRange Range, + ArrayRef Args, bool IsCXXMember, + VariadicCallType CallType, SourceLocation Loc, + SourceRange Range, llvm::SmallBitVector &CheckedVarArgs) { FormatStringInfo FSI; - if (getFormatStringInfo(Format, IsCXXMember, &FSI)) - return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, + if (getFormatStringInfo(Format, IsCXXMember, CallType != VariadicDoesNotApply, + &FSI)) + return CheckFormatArguments(Args, FSI.ArgPassingKind, FSI.FormatIdx, FSI.FirstDataArg, GetFormatStringType(Format), CallType, Loc, Range, CheckedVarArgs); return false; } bool Sema::CheckFormatArguments(ArrayRef Args, - bool HasVAListArg, unsigned format_idx, - unsigned firstDataArg, FormatStringType Type, - VariadicCallType CallType, - SourceLocation Loc, SourceRange Range, + Sema::FormatArgumentPassingKind APK, + unsigned format_idx, unsigned firstDataArg, + FormatStringType Type, + VariadicCallType CallType, SourceLocation Loc, + SourceRange Range, llvm::SmallBitVector &CheckedVarArgs) { // CHECK: printf/scanf-like function is called with no format string. if (format_idx >= Args.size()) { @@ -8796,12 +8882,11 @@ bool Sema::CheckFormatArguments(ArrayRef Args, // ObjC string uses the same format specifiers as C string, so we can use // the same format string checking logic for both ObjC and C strings. UncoveredArgHandler UncoveredArg; - StringLiteralCheckType CT = - checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, - format_idx, firstDataArg, Type, CallType, - /*IsFunctionCall*/ true, CheckedVarArgs, - UncoveredArg, - /*no string offset*/ llvm::APSInt(64, false) = 0); + StringLiteralCheckType CT = checkFormatStringExpr( + *this, OrigFormatExpr, Args, APK, format_idx, firstDataArg, Type, + CallType, + /*IsFunctionCall*/ true, CheckedVarArgs, UncoveredArg, + /*no string offset*/ llvm::APSInt(64, false) = 0); // Generate a diagnostic where an uncovered argument is detected. if (UncoveredArg.hasUncoveredArg()) { @@ -8864,7 +8949,7 @@ protected: const unsigned FirstDataArg; const unsigned NumDataArgs; const char *Beg; // Start of format string. - const bool HasVAListArg; + const Sema::FormatArgumentPassingKind ArgPassingKind; ArrayRef Args; unsigned FormatIdx; llvm::SmallBitVector CoveredArgs; @@ -8879,14 +8964,15 @@ public: CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, const Expr *origFormatExpr, const Sema::FormatStringType type, unsigned firstDataArg, - unsigned numDataArgs, const char *beg, bool hasVAListArg, + unsigned numDataArgs, const char *beg, + Sema::FormatArgumentPassingKind APK, ArrayRef Args, unsigned formatIdx, bool inFunctionCall, Sema::VariadicCallType callType, llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg) : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), - HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), + ArgPassingKind(APK), Args(Args), FormatIdx(formatIdx), inFunctionCall(inFunctionCall), CallType(callType), CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { CoveredArgs.resize(numDataArgs); @@ -9122,8 +9208,8 @@ const Expr *CheckFormatHandler::getDataArg(unsigned i) const { void CheckFormatHandler::DoneProcessing() { // Does the number of data arguments exceed the number of // format conversions in the format string? - if (!HasVAListArg) { - // Find any arguments that weren't covered. + if (ArgPassingKind != Sema::FAPK_VAList) { + // Find any arguments that weren't covered. CoveredArgs.flip(); signed notCoveredArg = CoveredArgs.find_first(); if (notCoveredArg >= 0) { @@ -9318,13 +9404,13 @@ public: const Expr *origFormatExpr, const Sema::FormatStringType type, unsigned firstDataArg, unsigned numDataArgs, bool isObjC, const char *beg, - bool hasVAListArg, ArrayRef Args, - unsigned formatIdx, bool inFunctionCall, - Sema::VariadicCallType CallType, + Sema::FormatArgumentPassingKind APK, + ArrayRef Args, unsigned formatIdx, + bool inFunctionCall, Sema::VariadicCallType CallType, llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg) : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, - numDataArgs, beg, hasVAListArg, Args, formatIdx, + numDataArgs, beg, APK, Args, formatIdx, inFunctionCall, CallType, CheckedVarArgs, UncoveredArg) {} @@ -9399,17 +9485,16 @@ void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { } bool CheckPrintfHandler::HandleAmount( - const analyze_format_string::OptionalAmount &Amt, - unsigned k, const char *startSpecifier, - unsigned specifierLen) { + const analyze_format_string::OptionalAmount &Amt, unsigned k, + const char *startSpecifier, unsigned specifierLen) { if (Amt.hasDataArgument()) { - if (!HasVAListArg) { + if (ArgPassingKind != Sema::FAPK_VAList) { unsigned argIndex = Amt.getArgIndex(); if (argIndex >= NumDataArgs) { EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) - << k, + << k, getLocationOfByte(Amt.getStart()), - /*IsStringLocation*/true, + /*IsStringLocation*/ true, getSpecifierRange(startSpecifier, specifierLen)); // Don't do any more checking. We will just emit // spurious errors. @@ -9805,7 +9890,7 @@ bool CheckPrintfHandler::HandlePrintfSpecifier( HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); // The remaining checks depend on the data arguments. - if (HasVAListArg) + if (ArgPassingKind == Sema::FAPK_VAList) return true; if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) @@ -9953,6 +10038,12 @@ CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, ExprTy = TET->getUnderlyingExpr()->getType(); } + // When using the format attribute in C++, you can receive a function or an + // array that will necessarily decay to a pointer when passed to the final + // format consumer. Apply decay before type comparison. + if (ExprTy->canDecayToPointerType()) + ExprTy = S.Context.getDecayedType(ExprTy); + // Diagnose attempts to print a boolean value as a character. Unlike other // -Wformat diagnostics, this is fine from a type perspective, but it still // doesn't make sense. @@ -10173,6 +10264,7 @@ CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, // Since the warning for passing non-POD types to variadic functions // was deferred until now, we emit a warning for non-POD // arguments here. + bool EmitTypeMismatch = false; switch (S.isValidVarArgType(ExprTy)) { case Sema::VAK_Valid: case Sema::VAK_ValidInCXX11: { @@ -10198,17 +10290,23 @@ CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, } case Sema::VAK_Undefined: case Sema::VAK_MSVCUndefined: - EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) - << S.getLangOpts().CPlusPlus11 << ExprTy - << CallType - << AT.getRepresentativeTypeName(S.Context) << CSR - << E->getSourceRange(), - E->getBeginLoc(), /*IsStringLocation*/ false, CSR); - checkForCStrMembers(AT, E); + if (CallType == Sema::VariadicDoesNotApply) { + EmitTypeMismatch = true; + } else { + EmitFormatDiagnostic( + S.PDiag(diag::warn_non_pod_vararg_with_format_string) + << S.getLangOpts().CPlusPlus11 << ExprTy << CallType + << AT.getRepresentativeTypeName(S.Context) << CSR + << E->getSourceRange(), + E->getBeginLoc(), /*IsStringLocation*/ false, CSR); + checkForCStrMembers(AT, E); + } break; case Sema::VAK_Invalid: - if (ExprTy->isObjCObjectType()) + if (CallType == Sema::VariadicDoesNotApply) + EmitTypeMismatch = true; + else if (ExprTy->isObjCObjectType()) EmitFormatDiagnostic( S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) << S.getLangOpts().CPlusPlus11 << ExprTy << CallType @@ -10224,6 +10322,19 @@ CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, break; } + if (EmitTypeMismatch) { + // The function is not variadic, so we do not generate warnings about + // being allowed to pass that object as a variadic argument. Instead, + // since there are inherently no printf specifiers for types which cannot + // be passed as variadic arguments, emit a plain old specifier mismatch + // argument. + EmitFormatDiagnostic( + S.PDiag(diag::warn_format_conversion_argument_type_mismatch) + << AT.getRepresentativeTypeName(S.Context) << ExprTy << false + << E->getSourceRange(), + E->getBeginLoc(), false, CSR); + } + assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && "format string specifier index out of range"); CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; @@ -10241,13 +10352,13 @@ public: CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, const Expr *origFormatExpr, Sema::FormatStringType type, unsigned firstDataArg, unsigned numDataArgs, - const char *beg, bool hasVAListArg, + const char *beg, Sema::FormatArgumentPassingKind APK, ArrayRef Args, unsigned formatIdx, bool inFunctionCall, Sema::VariadicCallType CallType, llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg) : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, - numDataArgs, beg, hasVAListArg, Args, formatIdx, + numDataArgs, beg, APK, Args, formatIdx, inFunctionCall, CallType, CheckedVarArgs, UncoveredArg) {} @@ -10351,7 +10462,7 @@ bool CheckScanfHandler::HandleScanfSpecifier( HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); // The remaining checks depend on the data arguments. - if (HasVAListArg) + if (ArgPassingKind == Sema::FAPK_VAList) return true; if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) @@ -10408,17 +10519,13 @@ bool CheckScanfHandler::HandleScanfSpecifier( return true; } -static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, - const Expr *OrigFormatExpr, - ArrayRef Args, - bool HasVAListArg, unsigned format_idx, - unsigned firstDataArg, - Sema::FormatStringType Type, - bool inFunctionCall, - Sema::VariadicCallType CallType, - llvm::SmallBitVector &CheckedVarArgs, - UncoveredArgHandler &UncoveredArg, - bool IgnoreStringsWithoutSpecifiers) { +static void CheckFormatString( + Sema &S, const FormatStringLiteral *FExpr, const Expr *OrigFormatExpr, + ArrayRef Args, Sema::FormatArgumentPassingKind APK, + unsigned format_idx, unsigned firstDataArg, Sema::FormatStringType Type, + bool inFunctionCall, Sema::VariadicCallType CallType, + llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg, + bool IgnoreStringsWithoutSpecifiers) { // CHECK: is the format string a wide literal? if (!FExpr->isAscii() && !FExpr->isUTF8()) { CheckFormatHandler::EmitFormatDiagnostic( @@ -10469,23 +10576,21 @@ static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, Type == Sema::FST_OSTrace) { CheckPrintfHandler H( S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, - (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, - HasVAListArg, Args, format_idx, inFunctionCall, CallType, - CheckedVarArgs, UncoveredArg); - - if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, - S.getLangOpts(), - S.Context.getTargetInfo(), - Type == Sema::FST_FreeBSDKPrintf)) + (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, APK, + Args, format_idx, inFunctionCall, CallType, CheckedVarArgs, + UncoveredArg); + + if (!analyze_format_string::ParsePrintfString( + H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo(), + Type == Sema::FST_FreeBSDKPrintf)) H.DoneProcessing(); } else if (Type == Sema::FST_Scanf) { CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, - numDataArgs, Str, HasVAListArg, Args, format_idx, - inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); + numDataArgs, Str, APK, Args, format_idx, inFunctionCall, + CallType, CheckedVarArgs, UncoveredArg); - if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, - S.getLangOpts(), - S.Context.getTargetInfo())) + if (!analyze_format_string::ParseScanfString( + H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) H.DoneProcessing(); } // TODO: handle other formats } @@ -16765,9 +16870,15 @@ void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, RHSDeclRef->getDecl()->getCanonicalDecl()) return; - Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() - << LHSExpr->getSourceRange() - << RHSExpr->getSourceRange(); + auto D = Diag(OpLoc, diag::warn_self_move) + << LHSExpr->getType() << LHSExpr->getSourceRange() + << RHSExpr->getSourceRange(); + if (const FieldDecl *F = + getSelfAssignmentClassMemberCandidate(RHSDeclRef->getDecl())) + D << 1 << F + << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->"); + else + D << 0; return; } @@ -16802,16 +16913,16 @@ void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, RHSDeclRef->getDecl()->getCanonicalDecl()) return; - Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() - << LHSExpr->getSourceRange() - << RHSExpr->getSourceRange(); + Diag(OpLoc, diag::warn_self_move) + << LHSExpr->getType() << 0 << LHSExpr->getSourceRange() + << RHSExpr->getSourceRange(); return; } if (isa(LHSBase) && isa(RHSBase)) - Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() - << LHSExpr->getSourceRange() - << RHSExpr->getSourceRange(); + Diag(OpLoc, diag::warn_self_move) + << LHSExpr->getType() << 0 << LHSExpr->getSourceRange() + << RHSExpr->getSourceRange(); } //===--- Layout compatibility ----------------------------------------------// diff --git a/contrib/llvm-project/clang/lib/Sema/SemaCodeComplete.cpp b/contrib/llvm-project/clang/lib/Sema/SemaCodeComplete.cpp index 8c9ed5389488..86bad736227d 100644 --- a/contrib/llvm-project/clang/lib/Sema/SemaCodeComplete.cpp +++ b/contrib/llvm-project/clang/lib/Sema/SemaCodeComplete.cpp @@ -5362,8 +5362,8 @@ private: // Overwrite existing if the new member has more info. // The preference of . vs :: vs -> is fairly arbitrary. if (/*Inserted*/ R.second || - std::make_tuple(M.ArgTypes.hasValue(), M.ResultType != nullptr, - M.Operator) > std::make_tuple(O.ArgTypes.hasValue(), + std::make_tuple(M.ArgTypes.has_value(), M.ResultType != nullptr, + M.Operator) > std::make_tuple(O.ArgTypes.has_value(), O.ResultType != nullptr, O.Operator)) O = std::move(M); diff --git a/contrib/llvm-project/clang/lib/Sema/SemaDecl.cpp b/contrib/llvm-project/clang/lib/Sema/SemaDecl.cpp index 1139088ecde2..5a546503cced 100644 --- a/contrib/llvm-project/clang/lib/Sema/SemaDecl.cpp +++ b/contrib/llvm-project/clang/lib/Sema/SemaDecl.cpp @@ -1625,22 +1625,20 @@ bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { Module *NewM = New->getOwningModule(); Module *OldM = Old->getOwningModule(); - if (NewM && NewM->Kind == Module::PrivateModuleFragment) + if (NewM && NewM->isPrivateModule()) NewM = NewM->Parent; - if (OldM && OldM->Kind == Module::PrivateModuleFragment) + if (OldM && OldM->isPrivateModule()) OldM = OldM->Parent; - // If we have a decl in a module partition, it is part of the containing - // module (which is the only thing that can be importing it). - if (NewM && OldM && - (OldM->Kind == Module::ModulePartitionInterface || - OldM->Kind == Module::ModulePartitionImplementation)) { - return false; - } - if (NewM == OldM) return false; + // Partitions are part of the module, but a partition could import another + // module, so verify that the PMIs agree. + if (NewM && OldM && (NewM->isModulePartition() || OldM->isModulePartition())) + return NewM->getPrimaryModuleInterfaceName() == + OldM->getPrimaryModuleInterfaceName(); + bool NewIsModuleInterface = NewM && NewM->isModulePurview(); bool OldIsModuleInterface = OldM && OldM->isModulePurview(); if (NewIsModuleInterface || OldIsModuleInterface) { @@ -3209,6 +3207,45 @@ static void mergeParamDeclAttributes(ParmVarDecl *newDecl, if (!foundAny) newDecl->dropAttrs(); } +static bool EquivalentArrayTypes(QualType Old, QualType New, + const ASTContext &Ctx) { + + auto NoSizeInfo = [&Ctx](QualType Ty) { + if (Ty->isIncompleteArrayType() || Ty->isPointerType()) + return true; + if (const auto *VAT = Ctx.getAsVariableArrayType(Ty)) + return VAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star; + return false; + }; + + // `type[]` is equivalent to `type *` and `type[*]`. + if (NoSizeInfo(Old) && NoSizeInfo(New)) + return true; + + // Don't try to compare VLA sizes, unless one of them has the star modifier. + if (Old->isVariableArrayType() && New->isVariableArrayType()) { + const auto *OldVAT = Ctx.getAsVariableArrayType(Old); + const auto *NewVAT = Ctx.getAsVariableArrayType(New); + if ((OldVAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star) ^ + (NewVAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star)) + return false; + return true; + } + + // Only compare size, ignore Size modifiers and CVR. + if (Old->isConstantArrayType() && New->isConstantArrayType()) { + return Ctx.getAsConstantArrayType(Old)->getSize() == + Ctx.getAsConstantArrayType(New)->getSize(); + } + + // Don't try to compare dependent sized array + if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) { + return true; + } + + return Old == New; +} + static void mergeParamDeclTypes(ParmVarDecl *NewParam, const ParmVarDecl *OldParam, Sema &S) { @@ -3234,6 +3271,19 @@ static void mergeParamDeclTypes(ParmVarDecl *NewParam, NewParam->setType(NewT); } } + const auto *OldParamDT = dyn_cast(OldParam->getType()); + const auto *NewParamDT = dyn_cast(NewParam->getType()); + if (OldParamDT && NewParamDT && + OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) { + QualType OldParamOT = OldParamDT->getOriginalType(); + QualType NewParamOT = NewParamDT->getOriginalType(); + if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) { + S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form) + << NewParam << NewParamOT; + S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as) + << OldParamOT; + } + } } namespace { @@ -15464,7 +15514,7 @@ void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( // specified by the value of this argument. if (AlignmentParam && !FD->hasAttr()) { FD->addAttr(AllocAlignAttr::CreateImplicit( - Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation())); + Context, ParamIdx(AlignmentParam.value(), FD), FD->getLocation())); } // FIXME: diff --git a/contrib/llvm-project/clang/lib/Sema/SemaDeclAttr.cpp b/contrib/llvm-project/clang/lib/Sema/SemaDeclAttr.cpp index f79523983ed8..838fd48357fb 100644 --- a/contrib/llvm-project/clang/lib/Sema/SemaDeclAttr.cpp +++ b/contrib/llvm-project/clang/lib/Sema/SemaDeclAttr.cpp @@ -2673,7 +2673,7 @@ static void handleAvailabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (IOSToWatchOSMapping) { if (auto MappedVersion = IOSToWatchOSMapping->map( Version, MinimumWatchOSVersion, None)) { - return MappedVersion.getValue(); + return MappedVersion.value(); } } @@ -2682,10 +2682,10 @@ static void handleAvailabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (NewMajor >= 2) { if (Version.getMinor()) { if (Version.getSubminor()) - return VersionTuple(NewMajor, Version.getMinor().getValue(), - Version.getSubminor().getValue()); + return VersionTuple(NewMajor, Version.getMinor().value(), + Version.getSubminor().value()); else - return VersionTuple(NewMajor, Version.getMinor().getValue()); + return VersionTuple(NewMajor, Version.getMinor().value()); } return VersionTuple(NewMajor); } @@ -3886,12 +3886,10 @@ static void handleFormatAttr(Sema &S, Decl *D, const ParsedAttr &AL) { // check if the function is variadic if the 3rd argument non-zero if (FirstArg != 0) { - if (isFunctionOrMethodVariadic(D)) { + if (isFunctionOrMethodVariadic(D)) ++NumArgs; // +1 for ... - } else { - S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic); - return; - } + else + S.Diag(D->getLocation(), diag::warn_gcc_requires_variadic_function) << AL; } // strftime requires FirstArg to be 0 because it doesn't read from any @@ -4314,13 +4312,6 @@ void Sema::AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, return; uint64_t AlignVal = Alignment.getZExtValue(); - // 16 byte ByVal alignment not due to a vector member is not honoured by XL - // on AIX. Emit a warning here that users are generating binary incompatible - // code to be safe. - if (AlignVal >= 16 && isa(D) && - Context.getTargetInfo().getTriple().isOSAIX()) - Diag(AttrLoc, diag::warn_not_xl_compatible) << E->getSourceRange(); - // C++11 [dcl.align]p2: // -- if the constant expression evaluates to zero, the alignment // specifier shall have no effect @@ -8002,6 +7993,26 @@ static void handleZeroCallUsedRegsAttr(Sema &S, Decl *D, const ParsedAttr &AL) { D->addAttr(ZeroCallUsedRegsAttr::Create(S.Context, Kind, AL)); } +static void handleFunctionReturnThunksAttr(Sema &S, Decl *D, + const ParsedAttr &AL) { + StringRef KindStr; + SourceLocation LiteralLoc; + if (!S.checkStringLiteralArgumentAttr(AL, 0, KindStr, &LiteralLoc)) + return; + + FunctionReturnThunksAttr::Kind Kind; + if (!FunctionReturnThunksAttr::ConvertStrToKind(KindStr, Kind)) { + S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported) + << AL << KindStr; + return; + } + // FIXME: it would be good to better handle attribute merging rather than + // silently replacing the existing attribute, so long as it does not break + // the expected codegen tests. + D->dropAttr(); + D->addAttr(FunctionReturnThunksAttr::Create(S.Context, Kind, AL)); +} + static void handleSYCLKernelAttr(Sema &S, Decl *D, const ParsedAttr &AL) { // The 'sycl_kernel' attribute applies only to function templates. const auto *FD = cast(D); @@ -8868,6 +8879,9 @@ ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D, const ParsedAttr &AL, case ParsedAttr::AT_ZeroCallUsedRegs: handleZeroCallUsedRegsAttr(S, D, AL); break; + case ParsedAttr::AT_FunctionReturnThunks: + handleFunctionReturnThunksAttr(S, D, AL); + break; // Microsoft attributes: case ParsedAttr::AT_LayoutVersion: diff --git a/contrib/llvm-project/clang/lib/Sema/SemaExpr.cpp b/contrib/llvm-project/clang/lib/Sema/SemaExpr.cpp index b9ecde6f20a0..742c4828b8dc 100644 --- a/contrib/llvm-project/clang/lib/Sema/SemaExpr.cpp +++ b/contrib/llvm-project/clang/lib/Sema/SemaExpr.cpp @@ -14600,6 +14600,40 @@ static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( return Opc; } +const FieldDecl * +Sema::getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned) { + // Explore the case for adding 'this->' to the LHS of a self assignment, very + // common for setters. + // struct A { + // int X; + // -void setX(int X) { X = X; } + // +void setX(int X) { this->X = X; } + // }; + + // Only consider parameters for self assignment fixes. + if (!isa(SelfAssigned)) + return nullptr; + const auto *Method = + dyn_cast_or_null(getCurFunctionDecl(true)); + if (!Method) + return nullptr; + + const CXXRecordDecl *Parent = Method->getParent(); + // In theory this is fixable if the lambda explicitly captures this, but + // that's added complexity that's rarely going to be used. + if (Parent->isLambda()) + return nullptr; + + // FIXME: Use an actual Lookup operation instead of just traversing fields + // in order to get base class fields. + auto Field = + llvm::find_if(Parent->fields(), + [Name(SelfAssigned->getDeclName())](const FieldDecl *F) { + return F->getDeclName() == Name; + }); + return (Field != Parent->field_end()) ? *Field : nullptr; +} + /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. /// This warning suppressed in the event of macro expansions. static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, @@ -14630,10 +14664,16 @@ static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, if (RefTy->getPointeeType().isVolatileQualified()) return; - S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin - : diag::warn_self_assignment_overloaded) - << LHSDeclRef->getType() << LHSExpr->getSourceRange() - << RHSExpr->getSourceRange(); + auto Diag = S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin + : diag::warn_self_assignment_overloaded) + << LHSDeclRef->getType() << LHSExpr->getSourceRange() + << RHSExpr->getSourceRange(); + if (const FieldDecl *SelfAssignField = + S.getSelfAssignmentClassMemberCandidate(RHSDecl)) + Diag << 1 << SelfAssignField + << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->"); + else + Diag << 0; } /// Check if a bitwise-& is performed on an Objective-C pointer. This diff --git a/contrib/llvm-project/clang/lib/Sema/SemaExprCXX.cpp b/contrib/llvm-project/clang/lib/Sema/SemaExprCXX.cpp index 0d73fcf8bf4e..11f33c7c6363 100644 --- a/contrib/llvm-project/clang/lib/Sema/SemaExprCXX.cpp +++ b/contrib/llvm-project/clang/lib/Sema/SemaExprCXX.cpp @@ -5394,6 +5394,39 @@ static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc, return false; } +namespace { +void DiagnoseBuiltinDeprecation(Sema& S, TypeTrait Kind, + SourceLocation KWLoc) { + TypeTrait Replacement; + switch (Kind) { + case UTT_HasNothrowAssign: + case UTT_HasNothrowMoveAssign: + Replacement = BTT_IsNothrowAssignable; + break; + case UTT_HasNothrowCopy: + case UTT_HasNothrowConstructor: + Replacement = TT_IsNothrowConstructible; + break; + case UTT_HasTrivialAssign: + case UTT_HasTrivialMoveAssign: + Replacement = BTT_IsTriviallyAssignable; + break; + case UTT_HasTrivialCopy: + case UTT_HasTrivialDefaultConstructor: + case UTT_HasTrivialMoveConstructor: + Replacement = TT_IsTriviallyConstructible; + break; + case UTT_HasTrivialDestructor: + Replacement = UTT_IsTriviallyDestructible; + break; + default: + return; + } + S.Diag(KWLoc, diag::warn_deprecated_builtin) + << getTraitSpelling(Kind) << getTraitSpelling(Replacement); +} +} + ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, ArrayRef Args, SourceLocation RParenLoc) { @@ -5403,6 +5436,8 @@ ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, *this, Kind, KWLoc, Args[0]->getType())) return ExprError(); + DiagnoseBuiltinDeprecation(*this, Kind, KWLoc); + bool Dependent = false; for (unsigned I = 0, N = Args.size(); I != N; ++I) { if (Args[I]->getType()->isDependentType()) { diff --git a/contrib/llvm-project/clang/lib/Sema/SemaModule.cpp b/contrib/llvm-project/clang/lib/Sema/SemaModule.cpp index 3aa124d457b0..e9a1ac17ce86 100644 --- a/contrib/llvm-project/clang/lib/Sema/SemaModule.cpp +++ b/contrib/llvm-project/clang/lib/Sema/SemaModule.cpp @@ -935,3 +935,16 @@ void Sema::PopGlobalModuleFragment() { "left the wrong module scope, which is not global module fragment"); ModuleScopes.pop_back(); } + +bool Sema::isModuleUnitOfCurrentTU(const Module *M) const { + assert(M); + + Module *CurrentModuleUnit = getCurrentModule(); + + // If we are not in a module currently, M must not be the module unit of + // current TU. + if (!CurrentModuleUnit) + return false; + + return M->isSubModuleOf(CurrentModuleUnit->getTopLevelModule()); +} diff --git a/contrib/llvm-project/clang/lib/Sema/SemaOpenMP.cpp b/contrib/llvm-project/clang/lib/Sema/SemaOpenMP.cpp index 6f501965552e..dc1470bf7a9d 100644 --- a/contrib/llvm-project/clang/lib/Sema/SemaOpenMP.cpp +++ b/contrib/llvm-project/clang/lib/Sema/SemaOpenMP.cpp @@ -840,21 +840,21 @@ public: /// false - otherwise. bool isOrderedRegion() const { if (const SharingMapTy *Top = getTopOfStackOrNull()) - return Top->OrderedRegion.hasValue(); + return Top->OrderedRegion.has_value(); return false; } /// Returns optional parameter for the ordered region. std::pair getOrderedRegionParam() const { if (const SharingMapTy *Top = getTopOfStackOrNull()) if (Top->OrderedRegion) - return Top->OrderedRegion.getValue(); + return Top->OrderedRegion.value(); return std::make_pair(nullptr, nullptr); } /// Returns true, if parent region is ordered (has associated /// 'ordered' clause), false - otherwise. bool isParentOrderedRegion() const { if (const SharingMapTy *Parent = getSecondOnStackOrNull()) - return Parent->OrderedRegion.hasValue(); + return Parent->OrderedRegion.has_value(); return false; } /// Returns optional parameter for the ordered region. @@ -862,7 +862,7 @@ public: getParentOrderedRegionParam() const { if (const SharingMapTy *Parent = getSecondOnStackOrNull()) if (Parent->OrderedRegion) - return Parent->OrderedRegion.getValue(); + return Parent->OrderedRegion.value(); return std::make_pair(nullptr, nullptr); } /// Marks current region as nowait (it has a 'nowait' clause). @@ -7831,9 +7831,9 @@ public: /// Return true if any expression is dependent. bool dependent() const; /// Returns true if the initializer forms non-rectangular loop. - bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); } + bool doesInitDependOnLC() const { return InitDependOnLC.has_value(); } /// Returns true if the condition forms non-rectangular loop. - bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); } + bool doesCondDependOnLC() const { return CondDependOnLC.has_value(); } /// Returns index of the loop we depend on (starting from 1), or 0 otherwise. unsigned getLoopDependentIdx() const { return InitDependOnLC.value_or(CondDependOnLC.value_or(0)); @@ -7942,18 +7942,18 @@ bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) { if (!TestIsLessOp) TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract); if (UB && - (IsConstZero || (TestIsLessOp.getValue() - ? (IsConstNeg || (IsUnsigned && Subtract)) - : (IsConstPos || (IsUnsigned && !Subtract))))) { + (IsConstZero || + (TestIsLessOp.value() ? (IsConstNeg || (IsUnsigned && Subtract)) + : (IsConstPos || (IsUnsigned && !Subtract))))) { SemaRef.Diag(NewStep->getExprLoc(), diag::err_omp_loop_incr_not_compatible) - << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange(); + << LCDecl << TestIsLessOp.value() << NewStep->getSourceRange(); SemaRef.Diag(ConditionLoc, diag::note_omp_loop_cond_requres_compatible_incr) - << TestIsLessOp.getValue() << ConditionSrcRange; + << TestIsLessOp.value() << ConditionSrcRange; return true; } - if (TestIsLessOp.getValue() == Subtract) { + if (TestIsLessOp.value() == Subtract) { NewStep = SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep) .get(); @@ -8708,8 +8708,8 @@ Expr *OpenMPIterationSpaceChecker::buildNumIterations( UBVal = MinUB.get(); } } - Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal; - Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal; + Expr *UBExpr = TestIsLessOp.value() ? UBVal : LBVal; + Expr *LBExpr = TestIsLessOp.value() ? LBVal : UBVal; Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get(); Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get(); if (!Upper || !Lower) @@ -8772,12 +8772,12 @@ std::pair OpenMPIterationSpaceChecker::buildMinMaxValues( // init value. Expr *MinExpr = nullptr; Expr *MaxExpr = nullptr; - Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB; - Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB; - bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue() - : CondDependOnLC.hasValue(); - bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue() - : InitDependOnLC.hasValue(); + Expr *LBExpr = TestIsLessOp.value() ? LB : UB; + Expr *UBExpr = TestIsLessOp.value() ? UB : LB; + bool LBNonRect = TestIsLessOp.value() ? InitDependOnLC.has_value() + : CondDependOnLC.has_value(); + bool UBNonRect = TestIsLessOp.value() ? CondDependOnLC.has_value() + : InitDependOnLC.has_value(); Expr *Lower = LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get(); Expr *Upper = @@ -8901,8 +8901,8 @@ Expr *OpenMPIterationSpaceChecker::buildPreCond( ExprResult CondExpr = SemaRef.BuildBinOp( S, DefaultLoc, - TestIsLessOp.getValue() ? (TestIsStrictOp ? BO_LT : BO_LE) - : (TestIsStrictOp ? BO_GT : BO_GE), + TestIsLessOp.value() ? (TestIsStrictOp ? BO_LT : BO_LE) + : (TestIsStrictOp ? BO_GT : BO_GE), NewLB.get(), NewUB.get()); if (CondExpr.isUsable()) { if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(), @@ -8978,12 +8978,10 @@ Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData( !SemaRef.getLangOpts().CPlusPlus) return nullptr; // Upper - Lower - Expr *Upper = TestIsLessOp.getValue() - ? Cnt - : tryBuildCapture(SemaRef, LB, Captures).get(); - Expr *Lower = TestIsLessOp.getValue() - ? tryBuildCapture(SemaRef, LB, Captures).get() - : Cnt; + Expr *Upper = + TestIsLessOp.value() ? Cnt : tryBuildCapture(SemaRef, LB, Captures).get(); + Expr *Lower = + TestIsLessOp.value() ? tryBuildCapture(SemaRef, LB, Captures).get() : Cnt; if (!Upper || !Lower) return nullptr; @@ -11570,7 +11568,7 @@ protected: bool checkType(ErrorInfoTy &ErrorInfo) const; static bool CheckValue(const Expr *E, ErrorInfoTy &ErrorInfo, - bool ShouldBeLValue) { + bool ShouldBeLValue, bool ShouldBeInteger = false) { if (ShouldBeLValue && !E->isLValue()) { ErrorInfo.Error = ErrorTy::XNotLValue; ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = E->getExprLoc(); @@ -11586,8 +11584,7 @@ protected: ErrorInfo.ErrorRange = ErrorInfo.NoteRange = E->getSourceRange(); return false; } - - if (!QTy->isIntegerType()) { + if (ShouldBeInteger && !QTy->isIntegerType()) { ErrorInfo.Error = ErrorTy::NotInteger; ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = E->getExprLoc(); ErrorInfo.ErrorRange = ErrorInfo.NoteRange = E->getSourceRange(); @@ -11890,7 +11887,7 @@ bool OpenMPAtomicCompareCaptureChecker::checkType(ErrorInfoTy &ErrorInfo) { if (V && !CheckValue(V, ErrorInfo, true)) return false; - if (R && !CheckValue(R, ErrorInfo, true)) + if (R && !CheckValue(R, ErrorInfo, true, true)) return false; return true; @@ -22588,27 +22585,27 @@ void Sema::ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc, auto *VD = cast(ND); llvm::Optional ActiveAttr = OMPDeclareTargetDeclAttr::getActiveAttr(VD); - if (ActiveAttr && ActiveAttr.getValue()->getDevType() != DTCI.DT && - ActiveAttr.getValue()->getLevel() == Level) { + if (ActiveAttr && ActiveAttr.value()->getDevType() != DTCI.DT && + ActiveAttr.value()->getLevel() == Level) { Diag(Loc, diag::err_omp_device_type_mismatch) << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DTCI.DT) << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr( - ActiveAttr.getValue()->getDevType()); + ActiveAttr.value()->getDevType()); return; } - if (ActiveAttr && ActiveAttr.getValue()->getMapType() != MT && - ActiveAttr.getValue()->getLevel() == Level) { + if (ActiveAttr && ActiveAttr.value()->getMapType() != MT && + ActiveAttr.value()->getLevel() == Level) { Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND; return; } - if (ActiveAttr && ActiveAttr.getValue()->getLevel() == Level) + if (ActiveAttr && ActiveAttr.value()->getLevel() == Level) return; Expr *IndirectE = nullptr; bool IsIndirect = false; if (DTCI.Indirect) { - IndirectE = DTCI.Indirect.getValue(); + IndirectE = DTCI.Indirect.value(); if (!IndirectE) IsIndirect = true; } @@ -22702,13 +22699,13 @@ void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, llvm::Optional ActiveAttr = OMPDeclareTargetDeclAttr::getActiveAttr(VD); unsigned Level = DeclareTargetNesting.size(); - if (ActiveAttr && ActiveAttr.getValue()->getLevel() >= Level) + if (ActiveAttr && ActiveAttr.value()->getLevel() >= Level) return; DeclareTargetContextInfo &DTCI = DeclareTargetNesting.back(); Expr *IndirectE = nullptr; bool IsIndirect = false; if (DTCI.Indirect) { - IndirectE = DTCI.Indirect.getValue(); + IndirectE = DTCI.Indirect.value(); if (!IndirectE) IsIndirect = true; } diff --git a/contrib/llvm-project/clang/lib/Sema/SemaTemplate.cpp b/contrib/llvm-project/clang/lib/Sema/SemaTemplate.cpp index dbfe6164bda2..67cf8f0371c5 100644 --- a/contrib/llvm-project/clang/lib/Sema/SemaTemplate.cpp +++ b/contrib/llvm-project/clang/lib/Sema/SemaTemplate.cpp @@ -2695,8 +2695,15 @@ bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams, for (TemplateParameterList::iterator NewParam = NewParams->begin(), NewParamEnd = NewParams->end(); NewParam != NewParamEnd; ++NewParam) { - // Variables used to diagnose redundant default arguments + // Whether we've seen a duplicate default argument in the same translation + // unit. bool RedundantDefaultArg = false; + // Whether we've found inconsis inconsitent default arguments in different + // translation unit. + bool InconsistentDefaultArg = false; + // The name of the module which contains the inconsistent default argument. + std::string PrevModuleName; + SourceLocation OldDefaultLoc; SourceLocation NewDefaultLoc; @@ -2729,7 +2736,16 @@ bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams, OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc(); NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc(); SawDefaultArgument = true; - RedundantDefaultArg = true; + + if (!OldTypeParm->getOwningModule() || + isModuleUnitOfCurrentTU(OldTypeParm->getOwningModule())) + RedundantDefaultArg = true; + else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm, + NewTypeParm)) { + InconsistentDefaultArg = true; + PrevModuleName = + OldTypeParm->getImportedOwningModule()->getFullModuleName(); + } PreviousDefaultArgLoc = NewDefaultLoc; } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) { // Merge the default argument from the old declaration to the @@ -2774,7 +2790,15 @@ bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams, OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc(); NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc(); SawDefaultArgument = true; - RedundantDefaultArg = true; + if (!OldNonTypeParm->getOwningModule() || + isModuleUnitOfCurrentTU(OldNonTypeParm->getOwningModule())) + RedundantDefaultArg = true; + else if (!getASTContext().isSameDefaultTemplateArgument( + OldNonTypeParm, NewNonTypeParm)) { + InconsistentDefaultArg = true; + PrevModuleName = + OldNonTypeParm->getImportedOwningModule()->getFullModuleName(); + } PreviousDefaultArgLoc = NewDefaultLoc; } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) { // Merge the default argument from the old declaration to the @@ -2818,7 +2842,15 @@ bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams, OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation(); NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation(); SawDefaultArgument = true; - RedundantDefaultArg = true; + if (!OldTemplateParm->getOwningModule() || + isModuleUnitOfCurrentTU(OldTemplateParm->getOwningModule())) + RedundantDefaultArg = true; + else if (!getASTContext().isSameDefaultTemplateArgument( + OldTemplateParm, NewTemplateParm)) { + InconsistentDefaultArg = true; + PrevModuleName = + OldTemplateParm->getImportedOwningModule()->getFullModuleName(); + } PreviousDefaultArgLoc = NewDefaultLoc; } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) { // Merge the default argument from the old declaration to the @@ -2845,13 +2877,32 @@ bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams, Invalid = true; } + // [basic.def.odr]/13: + // There can be more than one definition of a + // ... + // default template argument + // ... + // in a program provided that each definition appears in a different + // translation unit and the definitions satisfy the [same-meaning + // criteria of the ODR]. + // + // Simply, the design of modules allows the definition of template default + // argument to be repeated across translation unit. Note that the ODR is + // checked elsewhere. But it is still not allowed to repeat template default + // argument in the same translation unit. if (RedundantDefaultArg) { - // C++ [temp.param]p12: - // A template-parameter shall not be given default arguments - // by two different declarations in the same scope. Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition); Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg); Invalid = true; + } else if (InconsistentDefaultArg) { + // We could only diagnose about the case that the OldParam is imported. + // The case NewParam is imported should be handled in ASTReader. + Diag(NewDefaultLoc, + diag::err_template_param_default_arg_inconsistent_redefinition); + Diag(OldDefaultLoc, + diag::note_template_param_prev_default_arg_in_other_module) + << PrevModuleName; + Invalid = true; } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) { // C++ [temp.param]p11: // If a template-parameter of a class template has a default diff --git a/contrib/llvm-project/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp b/contrib/llvm-project/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp index d7558017948a..bd166ff6f594 100644 --- a/contrib/llvm-project/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp +++ b/contrib/llvm-project/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp @@ -469,8 +469,8 @@ static void instantiateOMPDeclareVariantAttr( if (!DeclVarData) return; - E = DeclVarData.getValue().second; - FD = DeclVarData.getValue().first; + E = DeclVarData.value().second; + FD = DeclVarData.value().first; if (auto *VariantDRE = dyn_cast(E->IgnoreParenImpCasts())) { if (auto *VariantFD = dyn_cast(VariantDRE->getDecl())) { @@ -4840,7 +4840,8 @@ void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, /*Complain*/DefinitionRequired)) { if (DefinitionRequired) Function->setInvalidDecl(); - else if (TSK == TSK_ExplicitInstantiationDefinition) { + else if (TSK == TSK_ExplicitInstantiationDefinition || + (Function->isConstexpr() && !Recursive)) { // Try again at the end of the translation unit (at which point a // definition will be required). assert(!Recursive); @@ -4855,7 +4856,7 @@ void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, Diag(PatternDecl->getLocation(), diag::note_forward_template_decl); if (getLangOpts().CPlusPlus11) Diag(PointOfInstantiation, diag::note_inst_declaration_hint) - << Function; + << Function; } } diff --git a/contrib/llvm-project/clang/lib/Serialization/ASTReader.cpp b/contrib/llvm-project/clang/lib/Serialization/ASTReader.cpp index d853805bf97e..04ade0a3b9d0 100644 --- a/contrib/llvm-project/clang/lib/Serialization/ASTReader.cpp +++ b/contrib/llvm-project/clang/lib/Serialization/ASTReader.cpp @@ -1462,18 +1462,19 @@ bool ASTReader::ReadSLocEntry(int ID) { unsigned RecCode = MaybeRecCode.get(); if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) { - if (!llvm::zlib::isAvailable()) { + if (!llvm::compression::zlib::isAvailable()) { Error("zlib is not available"); return nullptr; } - SmallString<0> Uncompressed; - if (llvm::Error E = - llvm::zlib::uncompress(Blob, Uncompressed, Record[0])) { + SmallVector Uncompressed; + if (llvm::Error E = llvm::compression::zlib::uncompress( + llvm::arrayRefFromStringRef(Blob), Uncompressed, Record[0])) { Error("could not decompress embedded file contents: " + llvm::toString(std::move(E))); return nullptr; } - return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name); + return llvm::MemoryBuffer::getMemBufferCopy( + llvm::toStringRef(Uncompressed), Name); } else if (RecCode == SM_SLOC_BUFFER_BLOB) { return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true); } else { @@ -5171,8 +5172,9 @@ namespace { bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool Complain, std::string &SuggestedPredefines) override { - return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr, - SuggestedPredefines, ExistingLangOpts); + return checkPreprocessorOptions(PPOpts, ExistingPPOpts, /*Diags=*/nullptr, + FileMgr, SuggestedPredefines, + ExistingLangOpts); } }; diff --git a/contrib/llvm-project/clang/lib/Serialization/ASTWriter.cpp b/contrib/llvm-project/clang/lib/Serialization/ASTWriter.cpp index 1787909bb6f7..fac8fc141d2c 100644 --- a/contrib/llvm-project/clang/lib/Serialization/ASTWriter.cpp +++ b/contrib/llvm-project/clang/lib/Serialization/ASTWriter.cpp @@ -1888,8 +1888,8 @@ void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS) { // without this file existing on disk. if (!U.Size || (!U.ModTime && IncludeTimestamps)) { PP->Diag(U.FileNameLoc, diag::err_module_no_size_mtime_for_header) - << WritingModule->getFullModuleName() << U.Size.hasValue() - << U.FileName; + << WritingModule->getFullModuleName() << U.Size.has_value() + << U.FileName; continue; } @@ -2000,12 +2000,13 @@ static void emitBlob(llvm::BitstreamWriter &Stream, StringRef Blob, // Compress the buffer if possible. We expect that almost all PCM // consumers will not want its contents. - SmallString<0> CompressedBuffer; - if (llvm::zlib::isAvailable()) { - llvm::zlib::compress(Blob.drop_back(1), CompressedBuffer); + SmallVector CompressedBuffer; + if (llvm::compression::zlib::isAvailable()) { + llvm::compression::zlib::compress( + llvm::arrayRefFromStringRef(Blob.drop_back(1)), CompressedBuffer); RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB_COMPRESSED, Blob.size() - 1}; Stream.EmitRecordWithBlob(SLocBufferBlobCompressedAbbrv, Record, - CompressedBuffer); + llvm::toStringRef(CompressedBuffer)); return; } diff --git a/contrib/llvm-project/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp b/contrib/llvm-project/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp index 330ca90b7659..ca76e2d83381 100644 --- a/contrib/llvm-project/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp +++ b/contrib/llvm-project/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp @@ -769,7 +769,7 @@ void VariadicMethodTypeChecker::checkPreObjCMessage(const ObjCMethodCall &msg, if (!errorNode) errorNode = C.generateNonFatalErrorNode(); - if (!errorNode.getValue()) + if (!errorNode.value()) continue; SmallString<128> sbuf; @@ -787,7 +787,7 @@ void VariadicMethodTypeChecker::checkPreObjCMessage(const ObjCMethodCall &msg, os << "'"; auto R = std::make_unique(*BT, os.str(), - errorNode.getValue()); + errorNode.value()); R->addRange(msg.getArgSourceRange(I)); C.emitReport(std::move(R)); } diff --git a/contrib/llvm-project/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp b/contrib/llvm-project/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp index 2e4c8e643698..987cf65d6fec 100644 --- a/contrib/llvm-project/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp +++ b/contrib/llvm-project/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp @@ -848,7 +848,7 @@ SVal CStringChecker::getCStringLength(CheckerContext &C, ProgramStateRef &state, SValBuilder &svalBuilder = C.getSValBuilder(); QualType sizeTy = svalBuilder.getContext().getSizeType(); const StringLiteral *strLit = cast(MR)->getStringLiteral(); - return svalBuilder.makeIntVal(strLit->getByteLength(), sizeTy); + return svalBuilder.makeIntVal(strLit->getLength(), sizeTy); } case MemRegion::SymbolicRegionKind: case MemRegion::AllocaRegionKind: diff --git a/contrib/llvm-project/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp b/contrib/llvm-project/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp index 92d7cef78b13..36464707d06a 100644 --- a/contrib/llvm-project/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp +++ b/contrib/llvm-project/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp @@ -1189,9 +1189,10 @@ MallocChecker::performKernelMalloc(const CallEvent &Call, CheckerContext &C, } NonLoc Flags = V.castAs(); - NonLoc ZeroFlag = C.getSValBuilder() - .makeIntVal(KernelZeroFlagVal.getValue(), FlagsEx->getType()) - .castAs(); + NonLoc ZeroFlag = + C.getSValBuilder() + .makeIntVal(KernelZeroFlagVal.value(), FlagsEx->getType()) + .castAs(); SVal MaskedFlagsUC = C.getSValBuilder().evalBinOpNN(State, BO_And, Flags, ZeroFlag, FlagsEx->getType()); @@ -1239,7 +1240,7 @@ void MallocChecker::checkKernelMalloc(const CallEvent &Call, llvm::Optional MaybeState = performKernelMalloc(Call, C, State); if (MaybeState) - State = MaybeState.getValue(); + State = MaybeState.value(); else State = MallocMemAux(C, Call, Call.getArgExpr(0), UndefinedVal(), State, AF_Malloc); diff --git a/contrib/llvm-project/clang/lib/StaticAnalyzer/Checkers/NonNullParamChecker.cpp b/contrib/llvm-project/clang/lib/StaticAnalyzer/Checkers/NonNullParamChecker.cpp index 3481936e572b..fb6afd0fdabc 100644 --- a/contrib/llvm-project/clang/lib/StaticAnalyzer/Checkers/NonNullParamChecker.cpp +++ b/contrib/llvm-project/clang/lib/StaticAnalyzer/Checkers/NonNullParamChecker.cpp @@ -136,10 +136,10 @@ void NonNullParamChecker::checkPreCall(const CallEvent &Call, if (!DV) continue; - assert(!HasRefTypeParam || isa(DV.getValue())); + assert(!HasRefTypeParam || isa(DV.value())); // Process the case when the argument is not a location. - if (ExpectedToBeNonNull && !isa(DV.getValue())) { + if (ExpectedToBeNonNull && !isa(DV.value())) { // If the argument is a union type, we want to handle a potential // transparent_union GCC extension. if (!ArgE) diff --git a/contrib/llvm-project/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp b/contrib/llvm-project/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp index 9da44d5c0d39..aa3f4524798a 100644 --- a/contrib/llvm-project/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp +++ b/contrib/llvm-project/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp @@ -234,7 +234,8 @@ void UnixAPIMisuseChecker::CheckOpenVariant(CheckerContext &C, } NonLoc oflags = V.castAs(); NonLoc ocreateFlag = C.getSValBuilder() - .makeIntVal(Val_O_CREAT.getValue(), oflagsEx->getType()).castAs(); + .makeIntVal(Val_O_CREAT.value(), oflagsEx->getType()) + .castAs(); SVal maskedFlagsUC = C.getSValBuilder().evalBinOpNN(state, BO_And, oflags, ocreateFlag, oflagsEx->getType()); diff --git a/contrib/llvm-project/clang/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp b/contrib/llvm-project/clang/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp index 79d19a3b99f2..009cbd4559b5 100644 --- a/contrib/llvm-project/clang/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp +++ b/contrib/llvm-project/clang/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp @@ -78,7 +78,7 @@ AnalyzerOptions::getExplorationStrategy() const { ExplorationStrategyKind::BFSBlockDFSContents) .Default(None); assert(K && "User mode is invalid."); - return K.getValue(); + return K.value(); } CTUPhase1InliningKind AnalyzerOptions::getCTUPhase1Inlining() const { @@ -89,7 +89,7 @@ CTUPhase1InliningKind AnalyzerOptions::getCTUPhase1Inlining() const { .Case("all", CTUPhase1InliningKind::All) .Default(None); assert(K && "CTU inlining mode is invalid."); - return K.getValue(); + return K.value(); } IPAKind AnalyzerOptions::getIPAMode() const { @@ -102,7 +102,7 @@ IPAKind AnalyzerOptions::getIPAMode() const { .Default(None); assert(K && "IPA Mode is invalid."); - return K.getValue(); + return K.value(); } bool diff --git a/contrib/llvm-project/clang/lib/StaticAnalyzer/Core/BugReporter.cpp b/contrib/llvm-project/clang/lib/StaticAnalyzer/Core/BugReporter.cpp index a2efe14f1045..4d6b82e63f6a 100644 --- a/contrib/llvm-project/clang/lib/StaticAnalyzer/Core/BugReporter.cpp +++ b/contrib/llvm-project/clang/lib/StaticAnalyzer/Core/BugReporter.cpp @@ -2363,15 +2363,15 @@ PathSensitiveBugReport::getInterestingnessKind(const MemRegion *R) const { } bool PathSensitiveBugReport::isInteresting(SVal V) const { - return getInterestingnessKind(V).hasValue(); + return getInterestingnessKind(V).has_value(); } bool PathSensitiveBugReport::isInteresting(SymbolRef sym) const { - return getInterestingnessKind(sym).hasValue(); + return getInterestingnessKind(sym).has_value(); } bool PathSensitiveBugReport::isInteresting(const MemRegion *R) const { - return getInterestingnessKind(R).hasValue(); + return getInterestingnessKind(R).has_value(); } bool PathSensitiveBugReport::isInteresting(const LocationContext *LC) const { diff --git a/contrib/llvm-project/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp b/contrib/llvm-project/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp index 5b72c91ccd74..2caa5bbc16df 100644 --- a/contrib/llvm-project/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp +++ b/contrib/llvm-project/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp @@ -2950,7 +2950,7 @@ PathDiagnosticPieceRef ConditionBRVisitor::VisitTrueTest( PathDiagnosticLocation Loc(Cond, SM, LCtx); auto event = std::make_shared(Loc, Message); if (shouldPrune) - event->setPrunable(shouldPrune.getValue()); + event->setPrunable(shouldPrune.value()); return event; } @@ -3084,9 +3084,9 @@ bool ConditionBRVisitor::printValue(const Expr *CondVarExpr, raw_ostream &Out, Out << (TookTrue ? "not equal to 0" : "0"); } else { if (Ty->isBooleanType()) - Out << (IntValue.getValue()->getBoolValue() ? "true" : "false"); + Out << (IntValue.value()->getBoolValue() ? "true" : "false"); else - Out << *IntValue.getValue(); + Out << *IntValue.value(); } return true; @@ -3282,7 +3282,7 @@ void FalsePositiveRefutationBRVisitor::finalizeVisitor( if (!IsSAT) return; - if (!IsSAT.getValue()) + if (!IsSAT.value()) BR.markInvalid("Infeasible constraints", EndPathNode->getLocationContext()); } diff --git a/contrib/llvm-project/clang/lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp b/contrib/llvm-project/clang/lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp index 5f8a84591b2a..e1649f0b3df6 100644 --- a/contrib/llvm-project/clang/lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp +++ b/contrib/llvm-project/clang/lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp @@ -1016,7 +1016,7 @@ bool ExprEngine::shouldInlineCall(const CallEvent &Call, const Decl *D, // Check if this function has been marked as non-inlinable. Optional MayInline = Engine.FunctionSummaries->mayInline(D); if (MayInline) { - if (!MayInline.getValue()) + if (!MayInline.value()) return false; } else { diff --git a/contrib/llvm-project/clang/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp b/contrib/llvm-project/clang/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp index 93c19a688b9a..d35646bfba91 100644 --- a/contrib/llvm-project/clang/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp +++ b/contrib/llvm-project/clang/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp @@ -407,11 +407,11 @@ void PlistPrinter::ReportMacroExpansions(raw_ostream &o, unsigned indent) { // Output the macro name. Indent(o, indent) << "name"; - EmitString(o, MacroName.getValue()) << '\n'; + EmitString(o, MacroName.value()) << '\n'; // Output what it expands into. Indent(o, indent) << "expansion"; - EmitString(o, ExpansionText.getValue()) << '\n'; + EmitString(o, ExpansionText.value()) << '\n'; // Finish up. --indent; diff --git a/contrib/llvm-project/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp b/contrib/llvm-project/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp index 13fac37899cd..cf3d13ffb7ba 100644 --- a/contrib/llvm-project/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp +++ b/contrib/llvm-project/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp @@ -113,6 +113,8 @@ nonloc::SymbolVal SValBuilder::makeNonLoc(const SymExpr *operand, QualType fromTy, QualType toTy) { assert(operand); assert(!Loc::isLocType(toTy)); + if (fromTy == toTy) + return operand; return nonloc::SymbolVal(SymMgr.getCastSymbol(operand, fromTy, toTy)); } @@ -1101,6 +1103,10 @@ nonloc::SymbolVal SValBuilder::simplifySymbolCast(nonloc::SymbolVal V, SymbolRef RootSym = cast(SE)->getOperand(); QualType RT = RootSym->getType().getCanonicalType(); + // FIXME support simplification from non-integers. + if (!RT->isIntegralOrEnumerationType()) + return makeNonLoc(SE, T, CastTy); + BasicValueFactory &BVF = getBasicValueFactory(); APSIntType CTy = BVF.getAPSIntType(CastTy); APSIntType TTy = BVF.getAPSIntType(T); diff --git a/contrib/llvm-project/clang/lib/Support/RISCVVIntrinsicUtils.cpp b/contrib/llvm-project/clang/lib/Support/RISCVVIntrinsicUtils.cpp index d4d3f22c9327..19eb65b39b0a 100644 --- a/contrib/llvm-project/clang/lib/Support/RISCVVIntrinsicUtils.cpp +++ b/contrib/llvm-project/clang/lib/Support/RISCVVIntrinsicUtils.cpp @@ -114,7 +114,7 @@ bool RVVType::verifyType() const { return false; if (isFloat() && ElementBitwidth == 8) return false; - unsigned V = Scale.getValue(); + unsigned V = Scale.value(); switch (ElementBitwidth) { case 1: case 8: @@ -798,7 +798,7 @@ RVVType::computeTypes(BasicType BT, int Log2LMUL, unsigned NF, if (!T) return llvm::None; // Record legal type index - Types.push_back(T.getValue()); + Types.push_back(T.value()); } return Types; } diff --git a/contrib/llvm-project/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp b/contrib/llvm-project/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp index 26c2b2b2f394..43127ea2df98 100644 --- a/contrib/llvm-project/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp +++ b/contrib/llvm-project/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp @@ -9,16 +9,19 @@ #include "clang/Tooling/DependencyScanning/DependencyScanningTool.h" #include "clang/Frontend/Utils.h" -namespace clang { -namespace tooling { -namespace dependencies { +using namespace clang; +using namespace tooling; +using namespace dependencies; std::vector FullDependencies::getCommandLine( - std::function LookupPCMPath) const { + llvm::function_ref + LookupModuleOutput) const { std::vector Ret = getCommandLineWithoutModulePaths(); - for (ModuleID MID : ClangModuleDeps) - Ret.push_back(("-fmodule-file=" + LookupPCMPath(MID)).str()); + for (ModuleID MID : ClangModuleDeps) { + auto PCM = LookupModuleOutput(MID, ModuleOutputKind::ModuleFile); + Ret.push_back("-fmodule-file=" + PCM); + } return Ret; } @@ -192,7 +195,3 @@ DependencyScanningTool::getFullDependencies( return std::move(Result); return Consumer.getFullDependencies(CommandLine); } - -} // end namespace dependencies -} // end namespace tooling -} // end namespace clang diff --git a/contrib/llvm-project/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp b/contrib/llvm-project/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp index f7d96130b971..725bb2c318ac 100644 --- a/contrib/llvm-project/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp +++ b/contrib/llvm-project/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp @@ -8,6 +8,7 @@ #include "clang/Tooling/DependencyScanning/ModuleDepCollector.h" +#include "clang/Basic/MakeSupport.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Lex/Preprocessor.h" #include "clang/Tooling/DependencyScanning/DependencyScanningWorker.h" @@ -56,6 +57,9 @@ CompilerInvocation ModuleDepCollector::makeInvocationForModuleBuildWithoutPaths( CI.getFrontendOpts().OutputFile.clear(); CI.getCodeGenOpts().MainFileName.clear(); CI.getCodeGenOpts().DwarfDebugFlags.clear(); + CI.getDiagnosticOpts().DiagnosticSerializationFile.clear(); + CI.getDependencyOutputOpts().OutputFile.clear(); + CI.getDependencyOutputOpts().Targets.clear(); CI.getFrontendOpts().ProgramAction = frontend::GenerateModule; CI.getLangOpts()->ModuleName = Deps.ID.ModuleName; @@ -107,18 +111,47 @@ serializeCompilerInvocation(const CompilerInvocation &CI) { return std::vector{Args.begin(), Args.end()}; } +static std::vector splitString(std::string S, char Separator) { + SmallVector Segments; + StringRef(S).split(Segments, Separator, /*MaxSplit=*/-1, /*KeepEmpty=*/false); + std::vector Result; + Result.reserve(Segments.size()); + for (StringRef Segment : Segments) + Result.push_back(Segment.str()); + return Result; +} + std::vector ModuleDeps::getCanonicalCommandLine( - std::function LookupPCMPath) const { + llvm::function_ref + LookupModuleOutput) const { CompilerInvocation CI(BuildInvocation); FrontendOptions &FrontendOpts = CI.getFrontendOpts(); InputKind ModuleMapInputKind(FrontendOpts.DashX.getLanguage(), InputKind::Format::ModuleMap); FrontendOpts.Inputs.emplace_back(ClangModuleMapFile, ModuleMapInputKind); - FrontendOpts.OutputFile = std::string(LookupPCMPath(ID)); + FrontendOpts.OutputFile = + LookupModuleOutput(ID, ModuleOutputKind::ModuleFile); + if (HadSerializedDiagnostics) + CI.getDiagnosticOpts().DiagnosticSerializationFile = + LookupModuleOutput(ID, ModuleOutputKind::DiagnosticSerializationFile); + if (HadDependencyFile) { + DependencyOutputOptions &DepOpts = CI.getDependencyOutputOpts(); + DepOpts.OutputFile = + LookupModuleOutput(ID, ModuleOutputKind::DependencyFile); + DepOpts.Targets = splitString( + LookupModuleOutput(ID, ModuleOutputKind::DependencyTargets), '\0'); + if (!DepOpts.OutputFile.empty() && DepOpts.Targets.empty()) { + // Fallback to -o as dependency target, as in the driver. + SmallString<128> Target; + quoteMakeTarget(FrontendOpts.OutputFile, Target); + DepOpts.Targets.push_back(std::string(Target)); + } + } for (ModuleID MID : ClangModuleDeps) - FrontendOpts.ModuleFiles.emplace_back(LookupPCMPath(MID)); + FrontendOpts.ModuleFiles.push_back( + LookupModuleOutput(MID, ModuleOutputKind::ModuleFile)); return serializeCompilerInvocation(CI); } @@ -309,6 +342,12 @@ ModuleID ModuleDepCollectorPP::handleTopLevelModule(const Module *M) { optimizeHeaderSearchOpts(BuildInvocation.getHeaderSearchOpts(), *MDC.ScanInstance.getASTReader(), *MF); }); + MD.HadSerializedDiagnostics = !MDC.OriginalInvocation.getDiagnosticOpts() + .DiagnosticSerializationFile.empty(); + MD.HadDependencyFile = + !MDC.OriginalInvocation.getDependencyOutputOpts().OutputFile.empty(); + // FIXME: HadSerializedDiagnostics and HadDependencyFile should be included in + // the context hash since it can affect the command-line. MD.ID.ContextHash = MD.BuildInvocation.getModuleHash(); llvm::DenseSet AddedModules; diff --git a/contrib/llvm-project/clang/tools/clang-format/ClangFormat.cpp b/contrib/llvm-project/clang/tools/clang-format/ClangFormat.cpp index 07110a0db091..269bc59506b2 100644 --- a/contrib/llvm-project/clang/tools/clang-format/ClangFormat.cpp +++ b/contrib/llvm-project/clang/tools/clang-format/ClangFormat.cpp @@ -70,16 +70,18 @@ static cl::opt cl::desc("The name of the predefined style used as a\n" "fallback in case clang-format is invoked with\n" "-style=file, but can not find the .clang-format\n" - "file to use.\n" + "file to use. Defaults to 'LLVM'.\n" "Use -fallback-style=none to skip formatting."), cl::init(clang::format::DefaultFallbackStyle), cl::cat(ClangFormatCategory)); static cl::opt AssumeFileName( "assume-filename", - cl::desc("Override filename used to determine the language.\n" - "When reading from stdin, clang-format assumes this\n" - "filename to determine the language.\n" + cl::desc("Set filename used to determine the language and to find\n" + ".clang-format file.\n" + "Only used when reading from stdin.\n" + "If this is not passed, the .clang-format file is searched\n" + "relative to the current working directory when reading stdin.\n" "Unrecognized filenames are treated as C++.\n" "supported:\n" " CSharp: .cs\n" @@ -244,8 +246,12 @@ static bool fillRanges(MemoryBuffer *Code, errs() << "error: invalid : pair\n"; return true; } + if (FromLine < 1) { + errs() << "error: start line should be at least 1\n"; + return true; + } if (FromLine > ToLine) { - errs() << "error: start line should be less than end line\n"; + errs() << "error: start line should not exceed end line\n"; return true; } SourceLocation Start = Sources.translateLineCol(ID, FromLine, 1); diff --git a/contrib/llvm-project/clang/tools/driver/driver.cpp b/contrib/llvm-project/clang/tools/driver/driver.cpp index 0e21106535ec..34335a599a00 100644 --- a/contrib/llvm-project/clang/tools/driver/driver.cpp +++ b/contrib/llvm-project/clang/tools/driver/driver.cpp @@ -408,7 +408,7 @@ int clang_main(int Argc, char **Argv) { llvm::Optional OptCL = llvm::sys::Process::GetEnv("CL"); if (OptCL) { SmallVector PrependedOpts; - getCLEnvVarOptions(OptCL.getValue(), Saver, PrependedOpts); + getCLEnvVarOptions(OptCL.value(), Saver, PrependedOpts); // Insert right after the program name to prepend to the argument list. Args.insert(Args.begin() + 1, PrependedOpts.begin(), PrependedOpts.end()); @@ -417,7 +417,7 @@ int clang_main(int Argc, char **Argv) { llvm::Optional Opt_CL_ = llvm::sys::Process::GetEnv("_CL_"); if (Opt_CL_) { SmallVector AppendedOpts; - getCLEnvVarOptions(Opt_CL_.getValue(), Saver, AppendedOpts); + getCLEnvVarOptions(Opt_CL_.value(), Saver, AppendedOpts); // Insert at the end of the argument list to append. Args.append(AppendedOpts.begin(), AppendedOpts.end()); diff --git a/contrib/llvm-project/clang/utils/TableGen/RISCVVEmitter.cpp b/contrib/llvm-project/clang/utils/TableGen/RISCVVEmitter.cpp index 068e6a0c072c..db4cd77d8c53 100644 --- a/contrib/llvm-project/clang/utils/TableGen/RISCVVEmitter.cpp +++ b/contrib/llvm-project/clang/utils/TableGen/RISCVVEmitter.cpp @@ -105,6 +105,16 @@ void emitCodeGenSwitchBody(const RVVIntrinsic *RVVI, raw_ostream &OS) { return; } + // Cast pointer operand of vector load intrinsic. + for (const auto &I : enumerate(RVVI->getInputTypes())) { + if (I.value()->isPointer()) { + assert(RVVI->getIntrinsicTypes().front() == -1 && + "RVVI should be vector load intrinsic."); + OS << " Ops[" << I.index() << "] = Builder.CreateBitCast(Ops["; + OS << I.index() << "], ResultType->getPointerTo());\n"; + } + } + if (RVVI->isMasked()) { if (RVVI->hasVL()) { OS << " std::rotate(Ops.begin(), Ops.begin() + 1, Ops.end() - 1);\n"; @@ -218,7 +228,7 @@ void RVVEmitter::createHeader(raw_ostream &OS) { auto T = RVVType::computeType(BasicType::Int8, Log2LMUL, PrototypeDescriptor::Mask); if (T) - printType(T.getValue()); + printType(T.value()); } // Print RVV int/float types. for (char I : StringRef("csil")) { @@ -226,13 +236,13 @@ void RVVEmitter::createHeader(raw_ostream &OS) { for (int Log2LMUL : Log2LMULs) { auto T = RVVType::computeType(BT, Log2LMUL, PrototypeDescriptor::Vector); if (T) { - printType(T.getValue()); + printType(T.value()); auto UT = RVVType::computeType( BT, Log2LMUL, PrototypeDescriptor(BaseTypeModifier::Vector, VectorTypeModifier::NoModifier, TypeModifier::UnsignedInteger)); - printType(UT.getValue()); + printType(UT.value()); } } } @@ -241,7 +251,7 @@ void RVVEmitter::createHeader(raw_ostream &OS) { auto T = RVVType::computeType(BasicType::Float16, Log2LMUL, PrototypeDescriptor::Vector); if (T) - printType(T.getValue()); + printType(T.value()); } OS << "#endif\n"; @@ -250,7 +260,7 @@ void RVVEmitter::createHeader(raw_ostream &OS) { auto T = RVVType::computeType(BasicType::Float32, Log2LMUL, PrototypeDescriptor::Vector); if (T) - printType(T.getValue()); + printType(T.value()); } OS << "#endif\n"; @@ -259,7 +269,7 @@ void RVVEmitter::createHeader(raw_ostream &OS) { auto T = RVVType::computeType(BasicType::Float64, Log2LMUL, PrototypeDescriptor::Vector); if (T) - printType(T.getValue()); + printType(T.value()); } OS << "#endif\n\n"; diff --git a/contrib/llvm-project/compiler-rt/lib/asan/asan_globals.cpp b/contrib/llvm-project/compiler-rt/lib/asan/asan_globals.cpp index 5206d685e6e8..b780128c9adb 100644 --- a/contrib/llvm-project/compiler-rt/lib/asan/asan_globals.cpp +++ b/contrib/llvm-project/compiler-rt/lib/asan/asan_globals.cpp @@ -90,7 +90,7 @@ static void ReportGlobal(const Global &g, const char *prefix) { DataInfo info; Symbolizer::GetOrInit()->SymbolizeData(g.beg, &info); if (info.line != 0) { - Report(" location: name=%s, %lu\n", info.file, info.line); + Report(" location: name=%s, %d\n", info.file, static_cast(info.line)); } } @@ -301,7 +301,7 @@ void PrintGlobalLocation(InternalScopedString *str, const __asan_global &g) { Symbolizer::GetOrInit()->SymbolizeData(g.beg, &info); if (info.line != 0) { - str->append("%s:%lu", info.file, info.line); + str->append("%s:%d", info.file, static_cast(info.line)); } else { str->append("%s", g.module_name); } diff --git a/contrib/llvm-project/compiler-rt/lib/asan/asan_interceptors.cpp b/contrib/llvm-project/compiler-rt/lib/asan/asan_interceptors.cpp index 37d0fc67cf75..13311b7e409b 100644 --- a/contrib/llvm-project/compiler-rt/lib/asan/asan_interceptors.cpp +++ b/contrib/llvm-project/compiler-rt/lib/asan/asan_interceptors.cpp @@ -248,10 +248,8 @@ static void ClearShadowMemoryForContextStack(uptr stack, uptr ssize) { uptr bottom = stack & ~(PageSize - 1); ssize += stack - bottom; ssize = RoundUpTo(ssize, PageSize); - static const uptr kMaxSaneContextStackSize = 1 << 22; // 4 Mb - if (AddrIsInMem(bottom) && ssize && ssize <= kMaxSaneContextStackSize) { + if (AddrIsInMem(bottom) && ssize) PoisonShadow(bottom, ssize, 0); - } } INTERCEPTOR(int, swapcontext, struct ucontext_t *oucp, diff --git a/contrib/llvm-project/compiler-rt/lib/asan/asan_rtl.cpp b/contrib/llvm-project/compiler-rt/lib/asan/asan_rtl.cpp index 29cf526d9eb0..2bbf0ac5240a 100644 --- a/contrib/llvm-project/compiler-rt/lib/asan/asan_rtl.cpp +++ b/contrib/llvm-project/compiler-rt/lib/asan/asan_rtl.cpp @@ -421,9 +421,6 @@ static void AsanInitInternal() { __sanitizer::InitializePlatformEarly(); - // Re-exec ourselves if we need to set additional env or command line args. - MaybeReexec(); - // Setup internal allocator callback. SetLowLevelAllocateMinAlignment(ASAN_SHADOW_GRANULARITY); SetLowLevelAllocateCallback(OnLowLevelAllocate); diff --git a/contrib/llvm-project/compiler-rt/lib/hwasan/hwasan.cpp b/contrib/llvm-project/compiler-rt/lib/hwasan/hwasan.cpp index f8725a173432..b771025cb93d 100644 --- a/contrib/llvm-project/compiler-rt/lib/hwasan/hwasan.cpp +++ b/contrib/llvm-project/compiler-rt/lib/hwasan/hwasan.cpp @@ -576,6 +576,12 @@ u8 __hwasan_generate_tag() { return t->GenerateRandomTag(); } +void __hwasan_add_frame_record(u64 frame_record_info) { + Thread *t = GetCurrentThread(); + if (t) + t->stack_allocations()->push(frame_record_info); +} + #if !SANITIZER_SUPPORTS_WEAK_HOOKS extern "C" { SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE diff --git a/contrib/llvm-project/compiler-rt/lib/hwasan/hwasan_fuchsia.cpp b/contrib/llvm-project/compiler-rt/lib/hwasan/hwasan_fuchsia.cpp index b066d4fdd114..967c796c339d 100644 --- a/contrib/llvm-project/compiler-rt/lib/hwasan/hwasan_fuchsia.cpp +++ b/contrib/llvm-project/compiler-rt/lib/hwasan/hwasan_fuchsia.cpp @@ -190,11 +190,11 @@ void InitializeOsSupport() { uint32_t features = 0; CHECK_EQ(zx_system_get_features(ZX_FEATURE_KIND_ADDRESS_TAGGING, &features), ZX_OK); - if (features != ZX_ARM64_FEATURE_ADDRESS_TAGGING_TBI && + if (!(features & ZX_ARM64_FEATURE_ADDRESS_TAGGING_TBI) && flags()->fail_without_syscall_abi) { Printf( - "FATAL: HWAddressSanitizer requires a kernel with tagged address " - "ABI.\n"); + "FATAL: HWAddressSanitizer requires " + "ZX_ARM64_FEATURE_ADDRESS_TAGGING_TBI.\n"); Die(); } #endif diff --git a/contrib/llvm-project/compiler-rt/lib/hwasan/hwasan_interface_internal.h b/contrib/llvm-project/compiler-rt/lib/hwasan/hwasan_interface_internal.h index ef771add411c..d1ecbb592a21 100644 --- a/contrib/llvm-project/compiler-rt/lib/hwasan/hwasan_interface_internal.h +++ b/contrib/llvm-project/compiler-rt/lib/hwasan/hwasan_interface_internal.h @@ -168,6 +168,14 @@ void __hwasan_thread_exit(); SANITIZER_INTERFACE_ATTRIBUTE void __hwasan_print_memory_usage(); +// The compiler will generate this when +// `-hwasan-record-stack-history-with-calls` is added as a flag, which will add +// frame record information to the stack ring buffer. This is an alternative to +// the compiler emitting instructions in the prologue for doing the same thing +// by accessing the ring buffer directly. +SANITIZER_INTERFACE_ATTRIBUTE +void __hwasan_add_frame_record(u64 frame_record_info); + SANITIZER_INTERFACE_ATTRIBUTE void *__hwasan_memcpy(void *dst, const void *src, uptr size); SANITIZER_INTERFACE_ATTRIBUTE diff --git a/contrib/llvm-project/compiler-rt/lib/hwasan/hwasan_linux.cpp b/contrib/llvm-project/compiler-rt/lib/hwasan/hwasan_linux.cpp index ba9e23621cc2..dcab473d8ad1 100644 --- a/contrib/llvm-project/compiler-rt/lib/hwasan/hwasan_linux.cpp +++ b/contrib/llvm-project/compiler-rt/lib/hwasan/hwasan_linux.cpp @@ -114,11 +114,21 @@ void InitializeOsSupport() { # define PR_SET_TAGGED_ADDR_CTRL 55 # define PR_GET_TAGGED_ADDR_CTRL 56 # define PR_TAGGED_ADDR_ENABLE (1UL << 0) +# define ARCH_GET_UNTAG_MASK 0x4001 +# define ARCH_ENABLE_TAGGED_ADDR 0x4002 // Check we're running on a kernel that can use the tagged address ABI. int local_errno = 0; - if (internal_iserror(internal_prctl(PR_GET_TAGGED_ADDR_CTRL, 0, 0, 0, 0), + bool has_abi; +# if defined(__x86_64__) + has_abi = (internal_iserror(internal_arch_prctl(ARCH_GET_UNTAG_MASK, 0), &local_errno) && - local_errno == EINVAL) { + local_errno == EINVAL); +# else + has_abi = (internal_iserror(internal_prctl(PR_GET_TAGGED_ADDR_CTRL, 0, 0, 0, 0), + &local_errno) && + local_errno == EINVAL); +# endif + if (has_abi) { # if SANITIZER_ANDROID || defined(HWASAN_ALIASING_MODE) // Some older Android kernels have the tagged pointer ABI on // unconditionally, and hence don't have the tagged-addr prctl while still @@ -142,17 +152,11 @@ void InitializeOsSupport() { !internal_prctl(PR_GET_TAGGED_ADDR_CTRL, 0, 0, 0, 0))) { # if defined(__x86_64__) && !defined(HWASAN_ALIASING_MODE) // Try the new prctl API for Intel LAM. The API is based on a currently - // unsubmitted patch to the Linux kernel (as of May 2021) and is thus + // unsubmitted patch to the Linux kernel (as of July 2022) and is thus // subject to change. Patch is here: - // https://lore.kernel.org/linux-mm/20210205151631.43511-12-kirill.shutemov@linux.intel.com/ - int tag_bits = kTagBits; - int tag_shift = kAddressTagShift; + // https://lore.kernel.org/linux-mm/20220712231328.5294-1-kirill.shutemov@linux.intel.com/ if (!internal_iserror( - internal_prctl(PR_SET_TAGGED_ADDR_CTRL, PR_TAGGED_ADDR_ENABLE, - reinterpret_cast(&tag_bits), - reinterpret_cast(&tag_shift), 0))) { - CHECK_EQ(tag_bits, kTagBits); - CHECK_EQ(tag_shift, kAddressTagShift); + internal_arch_prctl(ARCH_ENABLE_TAGGED_ADDR, kTagBits))) { return; } # endif // defined(__x86_64__) && !defined(HWASAN_ALIASING_MODE) diff --git a/contrib/llvm-project/compiler-rt/lib/memprof/memprof_rtl.cpp b/contrib/llvm-project/compiler-rt/lib/memprof/memprof_rtl.cpp index 21424fb4f072..d568a075c3e1 100644 --- a/contrib/llvm-project/compiler-rt/lib/memprof/memprof_rtl.cpp +++ b/contrib/llvm-project/compiler-rt/lib/memprof/memprof_rtl.cpp @@ -170,9 +170,6 @@ static void MemprofInitInternal() { __sanitizer::InitializePlatformEarly(); - // Re-exec ourselves if we need to set additional env or command line args. - MaybeReexec(); - // Setup internal allocator callback. SetLowLevelAllocateMinAlignment(SHADOW_GRANULARITY); diff --git a/contrib/llvm-project/compiler-rt/lib/orc/elfnix_platform.cpp b/contrib/llvm-project/compiler-rt/lib/orc/elfnix_platform.cpp index 6f502b20f8ca..260731ed2732 100644 --- a/contrib/llvm-project/compiler-rt/lib/orc/elfnix_platform.cpp +++ b/contrib/llvm-project/compiler-rt/lib/orc/elfnix_platform.cpp @@ -63,11 +63,17 @@ Error runInitArray(const std::vector &InitArraySections, return Error::success(); } + struct TLSInfoEntry { unsigned long Key = 0; unsigned long DataAddress = 0; }; +struct TLSDescriptor { + void (*Resolver)(void *); + TLSInfoEntry *InfoEntry; +}; + class ELFNixPlatformRuntimeState { private: struct AtExitEntry { @@ -501,6 +507,13 @@ ORC_RT_INTERFACE void *__orc_rt_elfnix_tls_get_addr_impl(TLSInfoEntry *D) { reinterpret_cast(static_cast(D->DataAddress))); } +ORC_RT_INTERFACE ptrdiff_t ___orc_rt_elfnix_tlsdesc_resolver_impl( + TLSDescriptor *D, const char *ThreadPointer) { + const char *TLVPtr = reinterpret_cast( + __orc_rt_elfnix_tls_get_addr_impl(D->InfoEntry)); + return TLVPtr - ThreadPointer; +} + ORC_RT_INTERFACE __orc_rt_CWrapperFunctionResult __orc_rt_elfnix_create_pthread_key(char *ArgData, size_t ArgSize) { return WrapperFunction(void)>::handle( diff --git a/contrib/llvm-project/compiler-rt/lib/orc/elfnix_tls.aarch64.S b/contrib/llvm-project/compiler-rt/lib/orc/elfnix_tls.aarch64.S new file mode 100644 index 000000000000..8dcdd535be8a --- /dev/null +++ b/contrib/llvm-project/compiler-rt/lib/orc/elfnix_tls.aarch64.S @@ -0,0 +1,94 @@ +//===-- elfnix_tlv.aarch64.s ---------------------------------------*- ASM -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file is a part of the ORC runtime support library. +// +//===----------------------------------------------------------------------===// + +// The content of this file is aarch64-only +#if defined(__arm64__) || defined(__aarch64__) + +#define REGISTER_SAVE_SPACE_SIZE 32 * 24 + + .text + + // returns address of TLV in x0, all other registers preserved + // TODO: add fast-path for repeat access + .globl ___orc_rt_elfnix_tlsdesc_resolver +___orc_rt_elfnix_tlsdesc_resolver: + sub sp, sp, #REGISTER_SAVE_SPACE_SIZE + stp x29, x30, [sp, #16 * 1] + stp x27, x28, [sp, #16 * 2] + stp x25, x26, [sp, #16 * 3] + stp x23, x24, [sp, #16 * 4] + stp x21, x22, [sp, #16 * 5] + stp x19, x20, [sp, #16 * 6] + stp x17, x18, [sp, #16 * 7] + stp x15, x16, [sp, #16 * 8] + stp x13, x14, [sp, #16 * 9] + stp x11, x12, [sp, #16 * 10] + stp x9, x10, [sp, #16 * 11] + stp x7, x8, [sp, #16 * 12] + stp x5, x6, [sp, #16 * 13] + stp x3, x4, [sp, #16 * 14] + stp x1, x2, [sp, #16 * 15] + stp q30, q31, [sp, #32 * 8] + stp q28, q29, [sp, #32 * 9] + stp q26, q27, [sp, #32 * 10] + stp q24, q25, [sp, #32 * 11] + stp q22, q23, [sp, #32 * 12] + stp q20, q21, [sp, #32 * 13] + stp q18, q19, [sp, #32 * 14] + stp q16, q17, [sp, #32 * 15] + stp q14, q15, [sp, #32 * 16] + stp q12, q13, [sp, #32 * 17] + stp q10, q11, [sp, #32 * 18] + stp q8, q9, [sp, #32 * 19] + stp q6, q7, [sp, #32 * 20] + stp q4, q5, [sp, #32 * 21] + stp q2, q3, [sp, #32 * 22] + stp q0, q1, [sp, #32 * 23] + + mrs x1, TPIDR_EL0 // get thread pointer + bl ___orc_rt_elfnix_tlsdesc_resolver_impl + + ldp q0, q1, [sp, #32 * 23] + ldp q2, q3, [sp, #32 * 22] + ldp q4, q5, [sp, #32 * 21] + ldp q6, q7, [sp, #32 * 20] + ldp q8, q9, [sp, #32 * 19] + ldp q10, q11, [sp, #32 * 18] + ldp q12, q13, [sp, #32 * 17] + ldp q14, q15, [sp, #32 * 16] + ldp q16, q17, [sp, #32 * 15] + ldp q18, q19, [sp, #32 * 14] + ldp q20, q21, [sp, #32 * 13] + ldp q22, q23, [sp, #32 * 12] + ldp q24, q25, [sp, #32 * 11] + ldp q26, q27, [sp, #32 * 10] + ldp q28, q29, [sp, #32 * 9] + ldp q30, q31, [sp, #32 * 8] + ldp x1, x2, [sp, #16 * 15] + ldp x3, x4, [sp, #16 * 14] + ldp x5, x6, [sp, #16 * 13] + ldp x7, x8, [sp, #16 * 12] + ldp x9, x10, [sp, #16 * 11] + ldp x11, x12, [sp, #16 * 10] + ldp x13, x14, [sp, #16 * 9] + ldp x15, x16, [sp, #16 * 8] + ldp x17, x18, [sp, #16 * 7] + ldp x19, x20, [sp, #16 * 6] + ldp x21, x22, [sp, #16 * 5] + ldp x23, x24, [sp, #16 * 4] + ldp x25, x26, [sp, #16 * 3] + ldp x27, x28, [sp, #16 * 2] + ldp x29, x30, [sp, #16 * 1] + add sp, sp, #REGISTER_SAVE_SPACE_SIZE + ret + +#endif // defined(__arm64__) || defined(__aarch64__) diff --git a/contrib/llvm-project/compiler-rt/lib/profile/GCDAProfiling.c b/contrib/llvm-project/compiler-rt/lib/profile/GCDAProfiling.c index 4aa15e9e9590..4f46fd2839b9 100644 --- a/contrib/llvm-project/compiler-rt/lib/profile/GCDAProfiling.c +++ b/contrib/llvm-project/compiler-rt/lib/profile/GCDAProfiling.c @@ -3,9 +3,9 @@ |* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |* See https://llvm.org/LICENSE.txt for license information. |* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -|* +|* |*===----------------------------------------------------------------------===*| -|* +|* |* This file implements the call back routines for the gcov profiling |* instrumentation pass. Link against this library when running code through |* the -insert-gcov-profiling LLVM pass. @@ -65,7 +65,7 @@ static char *filename = NULL; /* * The current file we're outputting. - */ + */ static FILE *output_file = NULL; /* @@ -264,11 +264,6 @@ static int map_file(void) { static void unmap_file(void) { #if defined(_WIN32) - if (!FlushViewOfFile(write_buffer, file_size)) { - fprintf(stderr, "profiling: %s: cannot flush mapped view: %lu\n", filename, - GetLastError()); - } - if (!UnmapViewOfFile(write_buffer)) { fprintf(stderr, "profiling: %s: cannot unmap mapped view: %lu\n", filename, GetLastError()); diff --git a/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_common.h b/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_common.h index 345c262af972..517f776baf6e 100644 --- a/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_common.h +++ b/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_common.h @@ -1016,7 +1016,6 @@ struct SignalContext { }; void InitializePlatformEarly(); -void MaybeReexec(); template class RunOnDestruction { diff --git a/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_common_interceptors.inc b/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_common_interceptors.inc index 60537018b889..9af296b1853a 100644 --- a/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_common_interceptors.inc +++ b/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_common_interceptors.inc @@ -2531,30 +2531,30 @@ INTERCEPTOR(int, __b64_pton, char const *src, char *target, SIZE_T targsize) { #endif // SANITIZER_INTERCEPT___B64_TO #if SANITIZER_INTERCEPT___DN_EXPAND -#if __GLIBC_PREREQ(2, 34) +# if __GLIBC_PREREQ(2, 34) // Changed with https://sourceware.org/git/?p=glibc.git;h=640bbdf -#define DN_EXPAND_INTERCEPTOR_NAME dn_expand -#else -#define DN_EXPAND_INTERCEPTOR_NAME __dn_expand -#endif - INTERCEPTOR(int, DN_EXPAND_INTERCEPTOR_NAME, unsigned char const *base, - unsigned char const *end, unsigned char const *src, char *dest, - int space) { - void *ctx; - COMMON_INTERCEPTOR_ENTER(ctx, DN_EXPAND_INTERCEPTOR_NAME, base, end, src, dest, space); +# define DN_EXPAND_INTERCEPTOR_NAME dn_expand +# else +# define DN_EXPAND_INTERCEPTOR_NAME __dn_expand +# endif +INTERCEPTOR(int, DN_EXPAND_INTERCEPTOR_NAME, unsigned char const *base, + unsigned char const *end, unsigned char const *src, char *dest, + int space) { + void *ctx; + COMMON_INTERCEPTOR_ENTER(ctx, DN_EXPAND_INTERCEPTOR_NAME, base, end, src, + dest, space); // TODO: add read check if __dn_comp intercept added int res = REAL(DN_EXPAND_INTERCEPTOR_NAME)(base, end, src, dest, space); if (res >= 0) - COMMON_INTERCEPTOR_WRITE_RANGE(ctx, dest, res + 1); + COMMON_INTERCEPTOR_WRITE_RANGE(ctx, dest, internal_strlen(dest) + 1); return res; } -#define INIT___DN_EXPAND \ +# define INIT___DN_EXPAND \ COMMON_INTERCEPT_FUNCTION(DN_EXPAND_INTERCEPTOR_NAME); #else // SANITIZER_INTERCEPT___DN_EXPAND -#define INIT___DN_EXPAND +# define INIT___DN_EXPAND #endif // SANITIZER_INTERCEPT___DN_EXPAND - #if SANITIZER_INTERCEPT_POSIX_SPAWN template diff --git a/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_flags.inc b/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_flags.inc index 8627ffd0d01c..6148ae56067c 100644 --- a/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_flags.inc +++ b/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_flags.inc @@ -68,9 +68,12 @@ COMMON_FLAG( COMMON_FLAG( int, verbosity, 0, "Verbosity level (0 - silent, 1 - a bit of output, 2+ - more output).") -COMMON_FLAG(bool, strip_env, 1, +COMMON_FLAG(bool, strip_env, true, "Whether to remove the sanitizer from DYLD_INSERT_LIBRARIES to " - "avoid passing it to children. Default is true.") + "avoid passing it to children on Apple platforms. Default is true.") +COMMON_FLAG(bool, verify_interceptors, true, + "Verify that interceptors are working on Apple platforms. Default " + "is true.") COMMON_FLAG(bool, detect_leaks, !SANITIZER_APPLE, "Enable memory leak detection.") COMMON_FLAG( bool, leak_check_at_exit, true, diff --git a/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_fuchsia.cpp b/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_fuchsia.cpp index e253b67fc484..a92e84cb8ecf 100644 --- a/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_fuchsia.cpp +++ b/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_fuchsia.cpp @@ -87,7 +87,6 @@ void GetThreadStackTopAndBottom(bool, uptr *stack_top, uptr *stack_bottom) { } void InitializePlatformEarly() {} -void MaybeReexec() {} void CheckASLR() {} void CheckMPROTECT() {} void PlatformPrepareForSandboxing(void *args) {} diff --git a/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_linux.cpp b/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_linux.cpp index c1acc20fe0b9..5eb563ffa025 100644 --- a/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_linux.cpp +++ b/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_linux.cpp @@ -34,7 +34,7 @@ // format. Struct kernel_stat is defined as 'struct stat' in asm/stat.h. To // access stat from asm/stat.h, without conflicting with definition in // sys/stat.h, we use this trick. -#if defined(__mips64) +#if SANITIZER_MIPS64 #include #include #define stat kernel_stat @@ -124,8 +124,9 @@ const int FUTEX_WAKE_PRIVATE = FUTEX_WAKE | FUTEX_PRIVATE_FLAG; // Are we using 32-bit or 64-bit Linux syscalls? // x32 (which defines __x86_64__) has SANITIZER_WORDSIZE == 32 // but it still needs to use 64-bit syscalls. -#if SANITIZER_LINUX && (defined(__x86_64__) || defined(__powerpc64__) || \ - SANITIZER_WORDSIZE == 64) +#if SANITIZER_LINUX && (defined(__x86_64__) || defined(__powerpc64__) || \ + SANITIZER_WORDSIZE == 64 || \ + (defined(__mips__) && _MIPS_SIM == _ABIN32)) # define SANITIZER_LINUX_USES_64BIT_SYSCALLS 1 #else # define SANITIZER_LINUX_USES_64BIT_SYSCALLS 0 @@ -289,7 +290,7 @@ static void stat64_to_stat(struct stat64 *in, struct stat *out) { } #endif -#if defined(__mips64) +#if SANITIZER_MIPS64 // Undefine compatibility macros from // so that they would not clash with the kernel_stat // st_[a|m|c]time fields @@ -343,7 +344,9 @@ uptr internal_stat(const char *path, void *buf) { #if SANITIZER_FREEBSD return internal_syscall(SYSCALL(fstatat), AT_FDCWD, (uptr)path, (uptr)buf, 0); # elif SANITIZER_LINUX -# if (SANITIZER_WORDSIZE == 64 || SANITIZER_X32) && !SANITIZER_SPARC +# if (SANITIZER_WORDSIZE == 64 || SANITIZER_X32 || \ + (defined(__mips__) && _MIPS_SIM == _ABIN32)) && \ + !SANITIZER_SPARC return internal_syscall(SYSCALL(newfstatat), AT_FDCWD, (uptr)path, (uptr)buf, 0); # else @@ -366,7 +369,9 @@ uptr internal_lstat(const char *path, void *buf) { return internal_syscall(SYSCALL(fstatat), AT_FDCWD, (uptr)path, (uptr)buf, AT_SYMLINK_NOFOLLOW); # elif SANITIZER_LINUX -# if (defined(_LP64) || SANITIZER_X32) && !SANITIZER_SPARC +# if (defined(_LP64) || SANITIZER_X32 || \ + (defined(__mips__) && _MIPS_SIM == _ABIN32)) && \ + !SANITIZER_SPARC return internal_syscall(SYSCALL(newfstatat), AT_FDCWD, (uptr)path, (uptr)buf, AT_SYMLINK_NOFOLLOW); # else @@ -758,6 +763,13 @@ uptr internal_lseek(fd_t fd, OFF_T offset, int whence) { uptr internal_prctl(int option, uptr arg2, uptr arg3, uptr arg4, uptr arg5) { return internal_syscall(SYSCALL(prctl), option, arg2, arg3, arg4, arg5); } +# if defined(__x86_64__) +#include +// Currently internal_arch_prctl() is only needed on x86_64. +uptr internal_arch_prctl(int option, uptr arg2) { + return internal_syscall(__NR_arch_prctl, option, arg2); +} +# endif #endif uptr internal_sigaltstack(const void *ss, void *oss) { @@ -1057,7 +1069,7 @@ uptr GetMaxVirtualAddress() { return (1ULL << (MostSignificantSetBitIndex(GET_CURRENT_FRAME()) + 1)) - 1; #elif SANITIZER_RISCV64 return (1ULL << 38) - 1; -# elif defined(__mips64) +# elif SANITIZER_MIPS64 return (1ULL << 40) - 1; // 0x000000ffffffffffUL; # elif defined(__s390x__) return (1ULL << 53) - 1; // 0x001fffffffffffffUL; @@ -2175,10 +2187,6 @@ void InitializePlatformEarly() { // Do nothing. } -void MaybeReexec() { - // No need to re-exec on Linux. -} - void CheckASLR() { #if SANITIZER_NETBSD int mib[3]; diff --git a/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_linux.h b/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_linux.h index 45d8c921da12..761c57d1b8eb 100644 --- a/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_linux.h +++ b/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_linux.h @@ -69,6 +69,9 @@ uptr internal_clock_gettime(__sanitizer_clockid_t clk_id, void *tp); // Linux-only syscalls. #if SANITIZER_LINUX uptr internal_prctl(int option, uptr arg2, uptr arg3, uptr arg4, uptr arg5); +# if defined(__x86_64__) +uptr internal_arch_prctl(int option, uptr arg2); +# endif // Used only by sanitizer_stoptheworld. Signal handlers that are actually used // (like the process-wide error reporting SEGV handler) must use // internal_sigaction instead. diff --git a/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_mac.cpp b/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_mac.cpp index 327c7167dcf5..7ce6eff832e5 100644 --- a/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_mac.cpp +++ b/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_mac.cpp @@ -943,6 +943,9 @@ static void DisableMmapExcGuardExceptions() { set_behavior(mach_task_self(), task_exc_guard_none); } +static void VerifyInterceptorsWorking(); +static void StripEnv(); + void InitializePlatformEarly() { // Only use xnu_fast_mmap when on x86_64 and the kernel supports it. use_xnu_fast_mmap = @@ -953,17 +956,54 @@ void InitializePlatformEarly() { #endif if (GetDarwinKernelVersion() >= DarwinKernelVersion(19, 0)) DisableMmapExcGuardExceptions(); + +# if !SANITIZER_GO + MonotonicNanoTime(); // Call to initialize mach_timebase_info + VerifyInterceptorsWorking(); + StripEnv(); +# endif } #if !SANITIZER_GO static const char kDyldInsertLibraries[] = "DYLD_INSERT_LIBRARIES"; LowLevelAllocator allocator_for_env; +static bool ShouldCheckInterceptors() { + // Restrict "interceptors working?" check to ASan and TSan. + const char *sanitizer_names[] = {"AddressSanitizer", "ThreadSanitizer"}; + size_t count = sizeof(sanitizer_names) / sizeof(sanitizer_names[0]); + for (size_t i = 0; i < count; i++) { + if (internal_strcmp(sanitizer_names[i], SanitizerToolName) == 0) + return true; + } + return false; +} + +static void VerifyInterceptorsWorking() { + if (!common_flags()->verify_interceptors || !ShouldCheckInterceptors()) + return; + + // Verify that interceptors really work. We'll use dlsym to locate + // "puts", if interceptors are working, it should really point to + // "wrap_puts" within our own dylib. + Dl_info info_puts, info_runtime; + RAW_CHECK(dladdr(dlsym(RTLD_DEFAULT, "puts"), &info_puts)); + RAW_CHECK(dladdr((void *)__sanitizer_report_error_summary, &info_runtime)); + if (internal_strcmp(info_puts.dli_fname, info_runtime.dli_fname) != 0) { + Report( + "ERROR: Interceptors are not working. This may be because %s is " + "loaded too late (e.g. via dlopen). Please launch the executable " + "with:\n%s=%s\n", + SanitizerToolName, kDyldInsertLibraries, info_runtime.dli_fname); + RAW_CHECK("interceptors not installed" && 0); + } +} + // Change the value of the env var |name|, leaking the original value. // If |name_value| is NULL, the variable is deleted from the environment, // otherwise the corresponding "NAME=value" string is replaced with // |name_value|. -void LeakyResetEnv(const char *name, const char *name_value) { +static void LeakyResetEnv(const char *name, const char *name_value) { char **env = GetEnviron(); uptr name_len = internal_strlen(name); while (*env != 0) { @@ -988,100 +1028,28 @@ void LeakyResetEnv(const char *name, const char *name_value) { } } -SANITIZER_WEAK_CXX_DEFAULT_IMPL -bool ReexecDisabled() { - return false; -} - -static bool DyldNeedsEnvVariable() { - // If running on OS X 10.11+ or iOS 9.0+, dyld will interpose even if - // DYLD_INSERT_LIBRARIES is not set. - return GetMacosAlignedVersion() < MacosVersion(10, 11); -} - -void MaybeReexec() { - // FIXME: This should really live in some "InitializePlatform" method. - MonotonicNanoTime(); +static void StripEnv() { + if (!common_flags()->strip_env) + return; - if (ReexecDisabled()) return; + char *dyld_insert_libraries = + const_cast(GetEnv(kDyldInsertLibraries)); + if (!dyld_insert_libraries) + return; - // Make sure the dynamic runtime library is preloaded so that the - // wrappers work. If it is not, set DYLD_INSERT_LIBRARIES and re-exec - // ourselves. Dl_info info; - RAW_CHECK(dladdr((void*)((uptr)&__sanitizer_report_error_summary), &info)); - char *dyld_insert_libraries = - const_cast(GetEnv(kDyldInsertLibraries)); - uptr old_env_len = dyld_insert_libraries ? - internal_strlen(dyld_insert_libraries) : 0; - uptr fname_len = internal_strlen(info.dli_fname); + RAW_CHECK(dladdr((void *)__sanitizer_report_error_summary, &info)); const char *dylib_name = StripModuleName(info.dli_fname); - uptr dylib_name_len = internal_strlen(dylib_name); - - bool lib_is_in_env = dyld_insert_libraries && - internal_strstr(dyld_insert_libraries, dylib_name); - if (DyldNeedsEnvVariable() && !lib_is_in_env) { - // DYLD_INSERT_LIBRARIES is not set or does not contain the runtime - // library. - InternalMmapVector program_name(1024); - uint32_t buf_size = program_name.size(); - _NSGetExecutablePath(program_name.data(), &buf_size); - char *new_env = const_cast(info.dli_fname); - if (dyld_insert_libraries) { - // Append the runtime dylib name to the existing value of - // DYLD_INSERT_LIBRARIES. - new_env = (char*)allocator_for_env.Allocate(old_env_len + fname_len + 2); - internal_strncpy(new_env, dyld_insert_libraries, old_env_len); - new_env[old_env_len] = ':'; - // Copy fname_len and add a trailing zero. - internal_strncpy(new_env + old_env_len + 1, info.dli_fname, - fname_len + 1); - // Ok to use setenv() since the wrappers don't depend on the value of - // asan_inited. - setenv(kDyldInsertLibraries, new_env, /*overwrite*/1); - } else { - // Set DYLD_INSERT_LIBRARIES equal to the runtime dylib name. - setenv(kDyldInsertLibraries, info.dli_fname, /*overwrite*/0); - } - VReport(1, "exec()-ing the program with\n"); - VReport(1, "%s=%s\n", kDyldInsertLibraries, new_env); - VReport(1, "to enable wrappers.\n"); - execv(program_name.data(), *_NSGetArgv()); - - // We get here only if execv() failed. - Report("ERROR: The process is launched without DYLD_INSERT_LIBRARIES, " - "which is required for the sanitizer to work. We tried to set the " - "environment variable and re-execute itself, but execv() failed, " - "possibly because of sandbox restrictions. Make sure to launch the " - "executable with:\n%s=%s\n", kDyldInsertLibraries, new_env); - RAW_CHECK("execv failed" && 0); - } - - // Verify that interceptors really work. We'll use dlsym to locate - // "puts", if interceptors are working, it should really point to - // "wrap_puts" within our own dylib. - Dl_info info_puts; - void *dlopen_addr = dlsym(RTLD_DEFAULT, "puts"); - RAW_CHECK(dladdr(dlopen_addr, &info_puts)); - if (internal_strcmp(info.dli_fname, info_puts.dli_fname) != 0) { - Report( - "ERROR: Interceptors are not working. This may be because %s is " - "loaded too late (e.g. via dlopen). Please launch the executable " - "with:\n%s=%s\n", - SanitizerToolName, kDyldInsertLibraries, info.dli_fname); - RAW_CHECK("interceptors not installed" && 0); - } - + bool lib_is_in_env = internal_strstr(dyld_insert_libraries, dylib_name); if (!lib_is_in_env) return; - if (!common_flags()->strip_env) - return; - // DYLD_INSERT_LIBRARIES is set and contains the runtime library. Let's remove // the dylib from the environment variable, because interceptors are installed // and we don't want our children to inherit the variable. + uptr old_env_len = internal_strlen(dyld_insert_libraries); + uptr dylib_name_len = internal_strlen(dylib_name); uptr env_name_len = internal_strlen(kDyldInsertLibraries); // Allocate memory to hold the previous env var name, its value, the '=' // sign and the '\0' char. diff --git a/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform.h b/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform.h index 7676e1ca264d..4d89ecaf1071 100644 --- a/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform.h +++ b/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform.h @@ -64,9 +64,6 @@ // - SANITIZER_DRIVERKIT #if defined(__APPLE__) # define SANITIZER_APPLE 1 -// SANITIZER_MAC will be deprecated/removed in the future -# define SANITIZER_MAC \ - error "SANITIZER_MAC will be removed, please use SANITIZER_APPLE" # include # if TARGET_OS_OSX # define SANITIZER_OSX 1 @@ -100,8 +97,6 @@ # endif #else # define SANITIZER_APPLE 0 -# define SANITIZER_MAC \ - error "SANITIZER_MAC will be removed, please use SANITIZER_APPLE" # define SANITIZER_OSX 0 # define SANITIZER_IOS 0 # define SANITIZER_WATCHOS 0 @@ -177,7 +172,7 @@ #if defined(__mips__) # define SANITIZER_MIPS 1 -# if defined(__mips64) +# if defined(__mips64) && _MIPS_SIM == _ABI64 # define SANITIZER_MIPS32 0 # define SANITIZER_MIPS64 1 # else diff --git a/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_posix.cpp b/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_posix.cpp index 4bd425435d56..3a94b260686f 100644 --- a/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_posix.cpp +++ b/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_platform_limits_posix.cpp @@ -73,7 +73,9 @@ #include #include #include +#if SANITIZER_ANDROID #include +#endif #include #include #include @@ -876,10 +878,10 @@ unsigned struct_ElfW_Phdr_sz = sizeof(Elf_Phdr); unsigned IOCTL_EVIOCGPROP = IOCTL_NOT_PRESENT; unsigned IOCTL_EVIOCSKEYCODE_V2 = IOCTL_NOT_PRESENT; #endif - unsigned IOCTL_FS_IOC_GETFLAGS = FS_IOC_GETFLAGS; - unsigned IOCTL_FS_IOC_GETVERSION = FS_IOC_GETVERSION; - unsigned IOCTL_FS_IOC_SETFLAGS = FS_IOC_SETFLAGS; - unsigned IOCTL_FS_IOC_SETVERSION = FS_IOC_SETVERSION; + unsigned IOCTL_FS_IOC_GETFLAGS = _IOR('f', 1, long); + unsigned IOCTL_FS_IOC_GETVERSION = _IOR('v', 1, long); + unsigned IOCTL_FS_IOC_SETFLAGS = _IOW('f', 2, long); + unsigned IOCTL_FS_IOC_SETVERSION = _IOW('v', 2, long); unsigned IOCTL_GIO_CMAP = GIO_CMAP; unsigned IOCTL_GIO_FONT = GIO_FONT; unsigned IOCTL_GIO_UNIMAP = GIO_UNIMAP; diff --git a/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_procmaps_mac.cpp b/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_procmaps_mac.cpp index 66f4935bb62d..4b0e67819761 100644 --- a/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_procmaps_mac.cpp +++ b/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_procmaps_mac.cpp @@ -223,10 +223,10 @@ const mach_header *get_dyld_hdr() { if (GetMacosAlignedVersion() >= MacosVersion(13, 0)) { dyld_hdr = GetDyldImageHeaderViaSharedCache(); if (!dyld_hdr) { - Printf( - "Failed to lookup the dyld image header in the shared cache on " - "macOS 13+ (or no shared cache in use). Falling back to lookup via" - "vm_region_recurse_64().\n"); + VReport(1, + "Failed to lookup the dyld image header in the shared cache on " + "macOS 13+ (or no shared cache in use). Falling back to " + "lookup via vm_region_recurse_64().\n"); dyld_hdr = GetDyldImageHeaderViaVMRegion(); } } else { diff --git a/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_vector.h b/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_vector.h index 31216f3ec3a6..79ff275660d3 100644 --- a/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_vector.h +++ b/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_vector.h @@ -83,8 +83,8 @@ class Vector { } EnsureSize(size); if (old_size < size) { - for (uptr i = old_size; i < size; i++) - internal_memset(&begin_[i], 0, sizeof(begin_[i])); + internal_memset(&begin_[old_size], 0, + sizeof(begin_[old_size]) * (size - old_size)); } } diff --git a/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_win.cpp b/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_win.cpp index c997514cfed7..b4506e52efaa 100644 --- a/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_win.cpp +++ b/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_win.cpp @@ -1094,10 +1094,6 @@ void InitializePlatformEarly() { // Do nothing. } -void MaybeReexec() { - // No need to re-exec on Windows. -} - void CheckASLR() { // Do nothing } diff --git a/contrib/llvm-project/compiler-rt/lib/scudo/standalone/fuchsia.cpp b/contrib/llvm-project/compiler-rt/lib/scudo/standalone/fuchsia.cpp index 8ab2b382a36a..4ce3b4ce6d18 100644 --- a/contrib/llvm-project/compiler-rt/lib/scudo/standalone/fuchsia.cpp +++ b/contrib/llvm-project/compiler-rt/lib/scudo/standalone/fuchsia.cpp @@ -57,8 +57,9 @@ void *map(void *Addr, uptr Size, const char *Name, uptr Flags, if (Flags & MAP_NOACCESS) return allocateVmar(Size, Data, AllowNoMem); - const zx_handle_t Vmar = Data ? Data->Vmar : _zx_vmar_root_self(); - CHECK_NE(Vmar, ZX_HANDLE_INVALID); + const zx_handle_t Vmar = (Data && Data->Vmar != ZX_HANDLE_INVALID) + ? Data->Vmar + : _zx_vmar_root_self(); zx_status_t Status; zx_handle_t Vmo; @@ -126,7 +127,9 @@ void unmap(void *Addr, uptr Size, uptr Flags, MapPlatformData *Data) { CHECK_EQ(_zx_vmar_destroy(Vmar), ZX_OK); CHECK_EQ(_zx_handle_close(Vmar), ZX_OK); } else { - const zx_handle_t Vmar = Data ? Data->Vmar : _zx_vmar_root_self(); + const zx_handle_t Vmar = (Data && Data->Vmar != ZX_HANDLE_INVALID) + ? Data->Vmar + : _zx_vmar_root_self(); const zx_status_t Status = _zx_vmar_unmap(Vmar, reinterpret_cast(Addr), Size); if (UNLIKELY(Status != ZX_OK)) diff --git a/contrib/llvm-project/compiler-rt/lib/scudo/standalone/include/scudo/interface.h b/contrib/llvm-project/compiler-rt/lib/scudo/standalone/include/scudo/interface.h index 9b9a84623c51..23bcfba3982a 100644 --- a/contrib/llvm-project/compiler-rt/lib/scudo/standalone/include/scudo/interface.h +++ b/contrib/llvm-project/compiler-rt/lib/scudo/standalone/include/scudo/interface.h @@ -14,7 +14,7 @@ extern "C" { -__attribute__((weak)) const char *__scudo_default_options(); +__attribute__((weak)) const char *__scudo_default_options(void); // Post-allocation & pre-deallocation hooks. // They must be thread-safe and not use heap related functions. @@ -101,14 +101,14 @@ struct scudo_error_info { struct scudo_error_report reports[3]; }; -const char *__scudo_get_stack_depot_addr(); -size_t __scudo_get_stack_depot_size(); +const char *__scudo_get_stack_depot_addr(void); +size_t __scudo_get_stack_depot_size(void); -const char *__scudo_get_region_info_addr(); -size_t __scudo_get_region_info_size(); +const char *__scudo_get_region_info_addr(void); +size_t __scudo_get_region_info_size(void); -const char *__scudo_get_ring_buffer_addr(); -size_t __scudo_get_ring_buffer_size(); +const char *__scudo_get_ring_buffer_addr(void); +size_t __scudo_get_ring_buffer_size(void); #ifndef M_DECAY_TIME #define M_DECAY_TIME -100 diff --git a/contrib/llvm-project/compiler-rt/lib/scudo/standalone/release.h b/contrib/llvm-project/compiler-rt/lib/scudo/standalone/release.h index 293a8bc27bab..49cc6ae618af 100644 --- a/contrib/llvm-project/compiler-rt/lib/scudo/standalone/release.h +++ b/contrib/llvm-project/compiler-rt/lib/scudo/standalone/release.h @@ -82,7 +82,7 @@ public: } else { Buffer = reinterpret_cast( map(nullptr, roundUpTo(BufferSize, getPageSizeCached()), - "scudo:counters", MAP_ALLOWNOMEM)); + "scudo:counters", MAP_ALLOWNOMEM, &MapData)); } } ~PackedCounterArray() { @@ -92,7 +92,7 @@ public: Mutex.unlock(); else unmap(reinterpret_cast(Buffer), - roundUpTo(BufferSize, getPageSizeCached())); + roundUpTo(BufferSize, getPageSizeCached()), 0, &MapData); } bool isAllocated() const { return !!Buffer; } @@ -138,6 +138,7 @@ private: uptr SizePerRegion; uptr BufferSize; uptr *Buffer; + [[no_unique_address]] MapPlatformData MapData = {}; static HybridMutex Mutex; static uptr StaticBuffer[StaticBufferCount]; diff --git a/contrib/llvm-project/compiler-rt/lib/scudo/standalone/vector.h b/contrib/llvm-project/compiler-rt/lib/scudo/standalone/vector.h index eae774b56e28..d43205a7111d 100644 --- a/contrib/llvm-project/compiler-rt/lib/scudo/standalone/vector.h +++ b/contrib/llvm-project/compiler-rt/lib/scudo/standalone/vector.h @@ -27,7 +27,7 @@ public: } void destroy() { if (Data != &LocalData[0]) - unmap(Data, CapacityBytes); + unmap(Data, CapacityBytes, 0, &MapData); } T &operator[](uptr I) { DCHECK_LT(I, Size); @@ -83,8 +83,8 @@ private: DCHECK_GT(NewCapacity, 0); DCHECK_LE(Size, NewCapacity); NewCapacity = roundUpTo(NewCapacity * sizeof(T), getPageSizeCached()); - T *NewData = - reinterpret_cast(map(nullptr, NewCapacity, "scudo:vector")); + T *NewData = reinterpret_cast( + map(nullptr, NewCapacity, "scudo:vector", 0, &MapData)); memcpy(NewData, Data, Size * sizeof(T)); destroy(); Data = NewData; @@ -95,6 +95,7 @@ private: T LocalData[256 / sizeof(T)] = {}; uptr CapacityBytes = 0; uptr Size = 0; + [[no_unique_address]] MapPlatformData MapData = {}; }; template class Vector : public VectorNoCtor { diff --git a/contrib/llvm-project/compiler-rt/lib/tsan/rtl/tsan_rtl.cpp b/contrib/llvm-project/compiler-rt/lib/tsan/rtl/tsan_rtl.cpp index 3977d60c36e5..607f373871b4 100644 --- a/contrib/llvm-project/compiler-rt/lib/tsan/rtl/tsan_rtl.cpp +++ b/contrib/llvm-project/compiler-rt/lib/tsan/rtl/tsan_rtl.cpp @@ -651,9 +651,6 @@ void Initialize(ThreadState *thr) { __tsan::InitializePlatformEarly(); #if !SANITIZER_GO - // Re-exec ourselves if we need to set additional env or command line args. - MaybeReexec(); - InitializeAllocator(); ReplaceSystemMalloc(); #endif diff --git a/contrib/llvm-project/libcxx/include/__algorithm/binary_search.h b/contrib/llvm-project/libcxx/include/__algorithm/binary_search.h index 121a741d070b..a44007237850 100644 --- a/contrib/llvm-project/libcxx/include/__algorithm/binary_search.h +++ b/contrib/llvm-project/libcxx/include/__algorithm/binary_search.h @@ -25,20 +25,20 @@ template _LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 bool -binary_search(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_, _Compare __comp) +binary_search(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value, _Compare __comp) { using _Comp_ref = typename __comp_ref_type<_Compare>::type; - __first = std::lower_bound<_ForwardIterator, _Tp, _Comp_ref>(__first, __last, __value_, __comp); - return __first != __last && !__comp(__value_, *__first); + __first = std::lower_bound<_ForwardIterator, _Tp, _Comp_ref>(__first, __last, __value, __comp); + return __first != __last && !__comp(__value, *__first); } template _LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 bool -binary_search(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_) +binary_search(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value) { - return std::binary_search(__first, __last, __value_, + return std::binary_search(__first, __last, __value, __less::value_type, _Tp>()); } diff --git a/contrib/llvm-project/libcxx/include/__algorithm/count.h b/contrib/llvm-project/libcxx/include/__algorithm/count.h index e18128cae8a8..5b546934038d 100644 --- a/contrib/llvm-project/libcxx/include/__algorithm/count.h +++ b/contrib/llvm-project/libcxx/include/__algorithm/count.h @@ -22,10 +22,10 @@ _LIBCPP_BEGIN_NAMESPACE_STD template _LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 typename iterator_traits<_InputIterator>::difference_type - count(_InputIterator __first, _InputIterator __last, const _Tp& __value_) { + count(_InputIterator __first, _InputIterator __last, const _Tp& __value) { typename iterator_traits<_InputIterator>::difference_type __r(0); for (; __first != __last; ++__first) - if (*__first == __value_) + if (*__first == __value) ++__r; return __r; } diff --git a/contrib/llvm-project/libcxx/include/__algorithm/equal_range.h b/contrib/llvm-project/libcxx/include/__algorithm/equal_range.h index 2a07364bb66f..f30f55be64fc 100644 --- a/contrib/llvm-project/libcxx/include/__algorithm/equal_range.h +++ b/contrib/llvm-project/libcxx/include/__algorithm/equal_range.h @@ -30,7 +30,7 @@ _LIBCPP_BEGIN_NAMESPACE_STD template _LIBCPP_CONSTEXPR_AFTER_CXX17 pair<_ForwardIterator, _ForwardIterator> -__equal_range(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_, _Compare __comp) +__equal_range(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value, _Compare __comp) { typedef typename iterator_traits<_ForwardIterator>::difference_type difference_type; difference_type __len = _VSTD::distance(__first, __last); @@ -39,12 +39,12 @@ __equal_range(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __va difference_type __l2 = _VSTD::__half_positive(__len); _ForwardIterator __m = __first; _VSTD::advance(__m, __l2); - if (__comp(*__m, __value_)) + if (__comp(*__m, __value)) { __first = ++__m; __len -= __l2 + 1; } - else if (__comp(__value_, *__m)) + else if (__comp(__value, *__m)) { __last = __m; __len = __l2; @@ -55,8 +55,8 @@ __equal_range(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __va _ForwardIterator __mp1 = __m; return pair<_ForwardIterator, _ForwardIterator> ( - _VSTD::__lower_bound_impl<_StdIterOps>(__first, __m, __value_, __comp, __proj), - _VSTD::__upper_bound<_Compare>(++__mp1, __last, __value_, __comp) + _VSTD::__lower_bound_impl<_ClassicAlgPolicy>(__first, __m, __value, __comp, __proj), + _VSTD::__upper_bound<_Compare>(++__mp1, __last, __value, __comp) ); } } @@ -67,19 +67,19 @@ template _LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 pair<_ForwardIterator, _ForwardIterator> -equal_range(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_, _Compare __comp) +equal_range(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value, _Compare __comp) { typedef typename __comp_ref_type<_Compare>::type _Comp_ref; - return _VSTD::__equal_range<_Comp_ref>(__first, __last, __value_, __comp); + return _VSTD::__equal_range<_Comp_ref>(__first, __last, __value, __comp); } template _LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 pair<_ForwardIterator, _ForwardIterator> -equal_range(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_) +equal_range(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value) { - return _VSTD::equal_range(__first, __last, __value_, + return _VSTD::equal_range(__first, __last, __value, __less::value_type, _Tp>()); } diff --git a/contrib/llvm-project/libcxx/include/__algorithm/fill.h b/contrib/llvm-project/libcxx/include/__algorithm/fill.h index be5b4740a52a..ec9968fdb8b3 100644 --- a/contrib/llvm-project/libcxx/include/__algorithm/fill.h +++ b/contrib/llvm-project/libcxx/include/__algorithm/fill.h @@ -23,26 +23,26 @@ _LIBCPP_BEGIN_NAMESPACE_STD template inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 void -__fill(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_, forward_iterator_tag) +__fill(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value, forward_iterator_tag) { for (; __first != __last; ++__first) - *__first = __value_; + *__first = __value; } template inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 void -__fill(_RandomAccessIterator __first, _RandomAccessIterator __last, const _Tp& __value_, random_access_iterator_tag) +__fill(_RandomAccessIterator __first, _RandomAccessIterator __last, const _Tp& __value, random_access_iterator_tag) { - _VSTD::fill_n(__first, __last - __first, __value_); + _VSTD::fill_n(__first, __last - __first, __value); } template inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 void -fill(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_) +fill(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value) { - _VSTD::__fill(__first, __last, __value_, typename iterator_traits<_ForwardIterator>::iterator_category()); + _VSTD::__fill(__first, __last, __value, typename iterator_traits<_ForwardIterator>::iterator_category()); } _LIBCPP_END_NAMESPACE_STD diff --git a/contrib/llvm-project/libcxx/include/__algorithm/fill_n.h b/contrib/llvm-project/libcxx/include/__algorithm/fill_n.h index 590c8f38f3fd..7482a4188dd5 100644 --- a/contrib/llvm-project/libcxx/include/__algorithm/fill_n.h +++ b/contrib/llvm-project/libcxx/include/__algorithm/fill_n.h @@ -22,19 +22,19 @@ _LIBCPP_BEGIN_NAMESPACE_STD template inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 _OutputIterator -__fill_n(_OutputIterator __first, _Size __n, const _Tp& __value_) +__fill_n(_OutputIterator __first, _Size __n, const _Tp& __value) { for (; __n > 0; ++__first, (void) --__n) - *__first = __value_; + *__first = __value; return __first; } template inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 _OutputIterator -fill_n(_OutputIterator __first, _Size __n, const _Tp& __value_) +fill_n(_OutputIterator __first, _Size __n, const _Tp& __value) { - return _VSTD::__fill_n(__first, _VSTD::__convert_to_integral(__n), __value_); + return _VSTD::__fill_n(__first, _VSTD::__convert_to_integral(__n), __value); } _LIBCPP_END_NAMESPACE_STD diff --git a/contrib/llvm-project/libcxx/include/__algorithm/find.h b/contrib/llvm-project/libcxx/include/__algorithm/find.h index 641b85e2f645..ab37d81262f0 100644 --- a/contrib/llvm-project/libcxx/include/__algorithm/find.h +++ b/contrib/llvm-project/libcxx/include/__algorithm/find.h @@ -20,9 +20,9 @@ _LIBCPP_BEGIN_NAMESPACE_STD template _LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 _InputIterator -find(_InputIterator __first, _InputIterator __last, const _Tp& __value_) { +find(_InputIterator __first, _InputIterator __last, const _Tp& __value) { for (; __first != __last; ++__first) - if (*__first == __value_) + if (*__first == __value) break; return __first; } diff --git a/contrib/llvm-project/libcxx/include/__algorithm/find_end.h b/contrib/llvm-project/libcxx/include/__algorithm/find_end.h index 0220c0939711..65e9f29b1c1f 100644 --- a/contrib/llvm-project/libcxx/include/__algorithm/find_end.h +++ b/contrib/llvm-project/libcxx/include/__algorithm/find_end.h @@ -11,8 +11,16 @@ #define _LIBCPP___ALGORITHM_FIND_END_OF_H #include <__algorithm/comp.h> +#include <__algorithm/iterator_operations.h> +#include <__algorithm/search.h> #include <__config> +#include <__functional/identity.h> +#include <__iterator/advance.h> #include <__iterator/iterator_traits.h> +#include <__iterator/next.h> +#include <__iterator/reverse_iterator.h> +#include <__utility/pair.h> +#include #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) # pragma GCC system_header @@ -20,35 +28,52 @@ _LIBCPP_BEGIN_NAMESPACE_STD -template -_LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator1 __find_end(_ForwardIterator1 __first1, _ForwardIterator1 __last1, - _ForwardIterator2 __first2, _ForwardIterator2 __last2, - _BinaryPredicate __pred, forward_iterator_tag, - forward_iterator_tag) { +template < + class _AlgPolicy, + class _Iter1, + class _Sent1, + class _Iter2, + class _Sent2, + class _Pred, + class _Proj1, + class _Proj2> +_LIBCPP_HIDE_FROM_ABI inline _LIBCPP_CONSTEXPR_AFTER_CXX11 pair<_Iter1, _Iter1> __find_end_impl( + _Iter1 __first1, + _Sent1 __last1, + _Iter2 __first2, + _Sent2 __last2, + _Pred& __pred, + _Proj1& __proj1, + _Proj2& __proj2, + forward_iterator_tag, + forward_iterator_tag) { // modeled after search algorithm - _ForwardIterator1 __r = __last1; // __last1 is the "default" answer + _Iter1 __match_first = _IterOps<_AlgPolicy>::next(__first1, __last1); // __last1 is the "default" answer + _Iter1 __match_last = __match_first; if (__first2 == __last2) - return __r; + return pair<_Iter1, _Iter1>(__match_last, __match_last); while (true) { while (true) { - if (__first1 == __last1) // if source exhausted return last correct answer - return __r; // (or __last1 if never found) - if (__pred(*__first1, *__first2)) + if (__first1 == __last1) // if source exhausted return last correct answer (or __last1 if never found) + return pair<_Iter1, _Iter1>(__match_first, __match_last); + if (std::__invoke(__pred, std::__invoke(__proj1, *__first1), std::__invoke(__proj2, *__first2))) break; ++__first1; } // *__first1 matches *__first2, now match elements after here - _ForwardIterator1 __m1 = __first1; - _ForwardIterator2 __m2 = __first2; + _Iter1 __m1 = __first1; + _Iter2 __m2 = __first2; while (true) { if (++__m2 == __last2) { // Pattern exhaused, record answer and search for another one - __r = __first1; + __match_first = __first1; + __match_last = ++__m1; ++__first1; break; } if (++__m1 == __last1) // Source exhausted, return last answer - return __r; - if (!__pred(*__m1, *__m2)) // mismatch, restart with a new __first + return pair<_Iter1, _Iter1>(__match_first, __match_last); + // mismatch, restart with a new __first + if (!std::__invoke(__pred, std::__invoke(__proj1, *__m1), std::__invoke(__proj2, *__m2))) { ++__first1; break; @@ -57,33 +82,52 @@ _LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator1 __find_end(_ForwardIterator1 __f } } -template -_LIBCPP_CONSTEXPR_AFTER_CXX17 _BidirectionalIterator1 __find_end( - _BidirectionalIterator1 __first1, _BidirectionalIterator1 __last1, _BidirectionalIterator2 __first2, - _BidirectionalIterator2 __last2, _BinaryPredicate __pred, bidirectional_iterator_tag, bidirectional_iterator_tag) { +template < + class _IterOps, + class _Pred, + class _Iter1, + class _Sent1, + class _Iter2, + class _Sent2, + class _Proj1, + class _Proj2> +_LIBCPP_CONSTEXPR_AFTER_CXX17 _Iter1 __find_end( + _Iter1 __first1, + _Sent1 __sent1, + _Iter2 __first2, + _Sent2 __sent2, + _Pred& __pred, + _Proj1& __proj1, + _Proj2& __proj2, + bidirectional_iterator_tag, + bidirectional_iterator_tag) { + auto __last1 = _IterOps::next(__first1, __sent1); + auto __last2 = _IterOps::next(__first2, __sent2); // modeled after search algorithm (in reverse) if (__first2 == __last2) return __last1; // Everything matches an empty sequence - _BidirectionalIterator1 __l1 = __last1; - _BidirectionalIterator2 __l2 = __last2; + _Iter1 __l1 = __last1; + _Iter2 __l2 = __last2; --__l2; while (true) { // Find last element in sequence 1 that matchs *(__last2-1), with a mininum of loop checks while (true) { if (__first1 == __l1) // return __last1 if no element matches *__first2 return __last1; - if (__pred(*--__l1, *__l2)) + if (std::__invoke(__pred, std::__invoke(__proj1, *--__l1), std::__invoke(__proj2, *__l2))) break; } // *__l1 matches *__l2, now match elements before here - _BidirectionalIterator1 __m1 = __l1; - _BidirectionalIterator2 __m2 = __l2; + _Iter1 __m1 = __l1; + _Iter2 __m2 = __l2; while (true) { if (__m2 == __first2) // If pattern exhausted, __m1 is the answer (works for 1 element pattern) return __m1; if (__m1 == __first1) // Otherwise if source exhaused, pattern not found return __last1; - if (!__pred(*--__m1, *--__m2)) // if there is a mismatch, restart with a new __l1 + + // if there is a mismatch, restart with a new __l1 + if (!std::__invoke(__pred, std::__invoke(__proj1, *--__m1), std::__invoke(__proj2, *--__m2))) { break; } // else there is a match, check next elements @@ -91,37 +135,53 @@ _LIBCPP_CONSTEXPR_AFTER_CXX17 _BidirectionalIterator1 __find_end( } } -template -_LIBCPP_CONSTEXPR_AFTER_CXX11 _RandomAccessIterator1 __find_end( - _RandomAccessIterator1 __first1, _RandomAccessIterator1 __last1, _RandomAccessIterator2 __first2, - _RandomAccessIterator2 __last2, _BinaryPredicate __pred, random_access_iterator_tag, random_access_iterator_tag) { - typedef typename iterator_traits<_RandomAccessIterator1>::difference_type _D1; - typedef typename iterator_traits<_RandomAccessIterator2>::difference_type _D2; +template < + class _AlgPolicy, + class _Pred, + class _Iter1, + class _Sent1, + class _Iter2, + class _Sent2, + class _Proj1, + class _Proj2> +_LIBCPP_CONSTEXPR_AFTER_CXX11 _Iter1 __find_end( + _Iter1 __first1, + _Sent1 __sent1, + _Iter2 __first2, + _Sent2 __sent2, + _Pred& __pred, + _Proj1& __proj1, + _Proj2& __proj2, + random_access_iterator_tag, + random_access_iterator_tag) { + typedef typename iterator_traits<_Iter1>::difference_type _D1; + auto __last1 = _IterOps<_AlgPolicy>::next(__first1, __sent1); + auto __last2 = _IterOps<_AlgPolicy>::next(__first2, __sent2); // Take advantage of knowing source and pattern lengths. Stop short when source is smaller than pattern - _D2 __len2 = __last2 - __first2; + auto __len2 = __last2 - __first2; if (__len2 == 0) return __last1; - _D1 __len1 = __last1 - __first1; + auto __len1 = __last1 - __first1; if (__len1 < __len2) return __last1; - const _RandomAccessIterator1 __s = __first1 + _D1(__len2 - 1); // End of pattern match can't go before here - _RandomAccessIterator1 __l1 = __last1; - _RandomAccessIterator2 __l2 = __last2; + const _Iter1 __s = __first1 + _D1(__len2 - 1); // End of pattern match can't go before here + _Iter1 __l1 = __last1; + _Iter2 __l2 = __last2; --__l2; while (true) { while (true) { if (__s == __l1) return __last1; - if (__pred(*--__l1, *__l2)) + if (std::__invoke(__pred, std::__invoke(__proj1, *--__l1), std::__invoke(__proj2, *__l2))) break; } - _RandomAccessIterator1 __m1 = __l1; - _RandomAccessIterator2 __m2 = __l2; + _Iter1 __m1 = __l1; + _Iter2 __m2 = __l2; while (true) { if (__m2 == __first2) return __m1; // no need to check range on __m1 because __s guarantees we have enough source - if (!__pred(*--__m1, *--__m2)) { + if (!std::__invoke(__pred, std::__invoke(__proj1, *--__m1), std::__invoke(*--__m2))) { break; } } @@ -129,20 +189,39 @@ _LIBCPP_CONSTEXPR_AFTER_CXX11 _RandomAccessIterator1 __find_end( } template -_LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator1 -find_end(_ForwardIterator1 __first1, _ForwardIterator1 __last1, _ForwardIterator2 __first2, _ForwardIterator2 __last2, - _BinaryPredicate __pred) { - return _VSTD::__find_end<_BinaryPredicate&>( - __first1, __last1, __first2, __last2, __pred, typename iterator_traits<_ForwardIterator1>::iterator_category(), - typename iterator_traits<_ForwardIterator2>::iterator_category()); +_LIBCPP_NODISCARD inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX11 +_ForwardIterator1 __find_end_classic(_ForwardIterator1 __first1, _ForwardIterator1 __last1, + _ForwardIterator2 __first2, _ForwardIterator2 __last2, + _BinaryPredicate& __pred) { + auto __proj = __identity(); + return std::__find_end_impl<_ClassicAlgPolicy>( + __first1, + __last1, + __first2, + __last2, + __pred, + __proj, + __proj, + typename iterator_traits<_ForwardIterator1>::iterator_category(), + typename iterator_traits<_ForwardIterator2>::iterator_category()) + .first; +} + +template +_LIBCPP_NODISCARD_EXT inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX17 +_ForwardIterator1 find_end(_ForwardIterator1 __first1, _ForwardIterator1 __last1, + _ForwardIterator2 __first2, _ForwardIterator2 __last2, + _BinaryPredicate __pred) { + return std::__find_end_classic(__first1, __last1, __first2, __last2, __pred); } template -_LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator1 -find_end(_ForwardIterator1 __first1, _ForwardIterator1 __last1, _ForwardIterator2 __first2, _ForwardIterator2 __last2) { - typedef typename iterator_traits<_ForwardIterator1>::value_type __v1; - typedef typename iterator_traits<_ForwardIterator2>::value_type __v2; - return _VSTD::find_end(__first1, __last1, __first2, __last2, __equal_to<__v1, __v2>()); +_LIBCPP_NODISCARD_EXT inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX17 +_ForwardIterator1 find_end(_ForwardIterator1 __first1, _ForwardIterator1 __last1, + _ForwardIterator2 __first2, _ForwardIterator2 __last2) { + using __v1 = typename iterator_traits<_ForwardIterator1>::value_type; + using __v2 = typename iterator_traits<_ForwardIterator2>::value_type; + return std::find_end(__first1, __last1, __first2, __last2, __equal_to<__v1, __v2>()); } _LIBCPP_END_NAMESPACE_STD diff --git a/contrib/llvm-project/libcxx/include/__algorithm/iterator_operations.h b/contrib/llvm-project/libcxx/include/__algorithm/iterator_operations.h index c02f9bf649df..eb627e1ace7a 100644 --- a/contrib/llvm-project/libcxx/include/__algorithm/iterator_operations.h +++ b/contrib/llvm-project/libcxx/include/__algorithm/iterator_operations.h @@ -6,13 +6,20 @@ // //===----------------------------------------------------------------------===// -#ifndef _LIBCPP___ALGORIHTM_ITERATOR_OPERATIONS_H -#define _LIBCPP___ALGORIHTM_ITERATOR_OPERATIONS_H +#ifndef _LIBCPP___ALGORITHM_ITERATOR_OPERATIONS_H +#define _LIBCPP___ALGORITHM_ITERATOR_OPERATIONS_H +#include <__algorithm/iter_swap.h> #include <__config> #include <__iterator/advance.h> #include <__iterator/distance.h> +#include <__iterator/iter_move.h> +#include <__iterator/iter_swap.h> #include <__iterator/iterator_traits.h> +#include <__iterator/next.h> +#include <__utility/forward.h> +#include <__utility/move.h> +#include #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) # pragma GCC system_header @@ -20,28 +27,69 @@ _LIBCPP_BEGIN_NAMESPACE_STD +template struct _IterOps; + #if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) -struct _RangesIterOps { +struct _RangeAlgPolicy {}; + +template <> +struct _IterOps<_RangeAlgPolicy> { static constexpr auto advance = ranges::advance; static constexpr auto distance = ranges::distance; + static constexpr auto __iter_move = ranges::iter_move; + static constexpr auto iter_swap = ranges::iter_swap; + static constexpr auto next = ranges::next; + static constexpr auto __advance_to = ranges::advance; }; #endif -struct _StdIterOps { +struct _ClassicAlgPolicy {}; + +template <> +struct _IterOps<_ClassicAlgPolicy> { + + // advance + template + _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX11 + static void advance(_Iter& __iter, _Distance __count) { + std::advance(__iter, __count); + } + + // distance + template + _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX11 + static typename iterator_traits<_Iter>::difference_type distance(_Iter __first, _Iter __last) { + return std::distance(__first, __last); + } + + // iter_move + template + _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX11 + // Declaring the return type is necessary for the C++03 mode (which doesn't support placeholder return types). + static typename iterator_traits<__uncvref_t<_Iter> >::value_type&& __iter_move(_Iter&& __i) { + return std::move(*std::forward<_Iter>(__i)); + } - template - _LIBCPP_HIDE_FROM_ABI static _LIBCPP_CONSTEXPR_AFTER_CXX11 void advance(_Iterator& __iter, _Distance __count) { - return std::advance(__iter, __count); + // iter_swap + template + _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX11 + static void iter_swap(_Iter1&& __a, _Iter2&& __b) { + std::iter_swap(std::forward<_Iter1>(__a), std::forward<_Iter2>(__b)); } + // next template _LIBCPP_HIDE_FROM_ABI static _LIBCPP_CONSTEXPR_AFTER_CXX11 - typename iterator_traits<_Iterator>::difference_type distance(_Iterator __first, _Iterator __last) { - return std::distance(__first, __last); + _Iterator next(_Iterator, _Iterator __last) { + return __last; } + template + _LIBCPP_HIDE_FROM_ABI static _LIBCPP_CONSTEXPR_AFTER_CXX11 void __advance_to(_Iter& __first, _Iter __last) { + __first = __last; + } }; _LIBCPP_END_NAMESPACE_STD -#endif // _LIBCPP___ALGORIHTM_ITERATOR_OPERATIONS_H +#endif // _LIBCPP___ALGORITHM_ITERATOR_OPERATIONS_H diff --git a/contrib/llvm-project/libcxx/include/__algorithm/lower_bound.h b/contrib/llvm-project/libcxx/include/__algorithm/lower_bound.h index fbcd5c7e908a..2c92f715265a 100644 --- a/contrib/llvm-project/libcxx/include/__algorithm/lower_bound.h +++ b/contrib/llvm-project/libcxx/include/__algorithm/lower_bound.h @@ -19,6 +19,7 @@ #include <__iterator/distance.h> #include <__iterator/iterator_traits.h> #include <__type_traits/is_callable.h> +#include <__type_traits/remove_reference.h> #include #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) @@ -27,15 +28,15 @@ _LIBCPP_BEGIN_NAMESPACE_STD -template +template _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX17 _Iter __lower_bound_impl(_Iter __first, _Sent __last, const _Type& __value, _Comp& __comp, _Proj& __proj) { - auto __len = _IterOps::distance(__first, __last); + auto __len = _IterOps<_AlgPolicy>::distance(__first, __last); while (__len != 0) { auto __l2 = std::__half_positive(__len); _Iter __m = __first; - _IterOps::advance(__m, __l2); + _IterOps<_AlgPolicy>::advance(__m, __l2); if (std::__invoke(__comp, std::__invoke(__proj, *__m), __value)) { __first = ++__m; __len -= __l2 + 1; @@ -48,17 +49,17 @@ _Iter __lower_bound_impl(_Iter __first, _Sent __last, const _Type& __value, _Com template _LIBCPP_NODISCARD_EXT inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX17 -_ForwardIterator lower_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_, _Compare __comp) { +_ForwardIterator lower_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value, _Compare __comp) { static_assert(__is_callable<_Compare, decltype(*__first), const _Tp&>::value, "The comparator has to be callable"); auto __proj = std::__identity(); - return std::__lower_bound_impl<_StdIterOps>(__first, __last, __value_, __comp, __proj); + return std::__lower_bound_impl<_ClassicAlgPolicy>(__first, __last, __value, __comp, __proj); } template _LIBCPP_NODISCARD_EXT inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX17 -_ForwardIterator lower_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_) { - return std::lower_bound(__first, __last, __value_, +_ForwardIterator lower_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value) { + return std::lower_bound(__first, __last, __value, __less::value_type, _Tp>()); } diff --git a/contrib/llvm-project/libcxx/include/__algorithm/make_heap.h b/contrib/llvm-project/libcxx/include/__algorithm/make_heap.h index acac0aabf1e4..bc39d82bf916 100644 --- a/contrib/llvm-project/libcxx/include/__algorithm/make_heap.h +++ b/contrib/llvm-project/libcxx/include/__algorithm/make_heap.h @@ -14,6 +14,7 @@ #include <__algorithm/sift_down.h> #include <__config> #include <__iterator/iterator_traits.h> +#include <__utility/move.h> #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) # pragma GCC system_header @@ -22,36 +23,32 @@ _LIBCPP_BEGIN_NAMESPACE_STD template -_LIBCPP_CONSTEXPR_AFTER_CXX11 void -__make_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp) -{ - typedef typename iterator_traits<_RandomAccessIterator>::difference_type difference_type; - difference_type __n = __last - __first; - if (__n > 1) - { - // start from the first parent, there is no need to consider children - for (difference_type __start = (__n - 2) / 2; __start >= 0; --__start) - { - _VSTD::__sift_down<_Compare>(__first, __comp, __n, __first + __start); - } +inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX11 +void __make_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare& __comp) { + using _CompRef = typename __comp_ref_type<_Compare>::type; + _CompRef __comp_ref = __comp; + + using difference_type = typename iterator_traits<_RandomAccessIterator>::difference_type; + difference_type __n = __last - __first; + if (__n > 1) { + // start from the first parent, there is no need to consider children + for (difference_type __start = (__n - 2) / 2; __start >= 0; --__start) { + std::__sift_down<_CompRef>(__first, __comp_ref, __n, __first + __start); } + } } template -inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 -void -make_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp) -{ - typedef typename __comp_ref_type<_Compare>::type _Comp_ref; - _VSTD::__make_heap<_Comp_ref>(__first, __last, __comp); +inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX17 +void make_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp) { + std::__make_heap(std::move(__first), std::move(__last), __comp); } template -inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 -void -make_heap(_RandomAccessIterator __first, _RandomAccessIterator __last) -{ - _VSTD::make_heap(__first, __last, __less::value_type>()); +inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX17 +void make_heap(_RandomAccessIterator __first, _RandomAccessIterator __last) { + std::make_heap(std::move(__first), std::move(__last), + __less::value_type>()); } _LIBCPP_END_NAMESPACE_STD diff --git a/contrib/llvm-project/libcxx/include/__algorithm/make_projected.h b/contrib/llvm-project/libcxx/include/__algorithm/make_projected.h index 8141c4ed176f..6d8ebfd3d90e 100644 --- a/contrib/llvm-project/libcxx/include/__algorithm/make_projected.h +++ b/contrib/llvm-project/libcxx/include/__algorithm/make_projected.h @@ -13,6 +13,8 @@ #include <__config> #include <__functional/identity.h> #include <__functional/invoke.h> +#include <__type_traits/decay.h> +#include <__type_traits/is_member_pointer.h> #include <__utility/forward.h> #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) @@ -28,7 +30,7 @@ namespace ranges { template _LIBCPP_HIDE_FROM_ABI constexpr static decltype(auto) __make_projected_comp(_Comp& __comp, _Proj& __proj) { - if constexpr (same_as<_Proj, identity>) { + if constexpr (same_as, identity> && !is_member_pointer_v>) { // Avoid creating the lambda and just use the pristine comparator -- for certain algorithms, this would enable // optimizations that rely on the type of the comparator. return __comp; @@ -42,6 +44,24 @@ decltype(auto) __make_projected_comp(_Comp& __comp, _Proj& __proj) { } } +template +_LIBCPP_HIDE_FROM_ABI constexpr static +decltype(auto) __make_projected_comp(_Comp& __comp, _Proj1& __proj1, _Proj2& __proj2) { + if constexpr (same_as, identity> && same_as, identity> && + !is_member_pointer_v>) { + // Avoid creating the lambda and just use the pristine comparator -- for certain algorithms, this would enable + // optimizations that rely on the type of the comparator. + return __comp; + + } else { + return [&](auto&& __lhs, auto&& __rhs) { + return std::invoke(__comp, + std::invoke(__proj1, std::forward(__lhs)), + std::invoke(__proj2, std::forward(__rhs))); + }; + } +} + } // namespace ranges _LIBCPP_END_NAMESPACE_STD diff --git a/contrib/llvm-project/libcxx/include/__algorithm/minmax_element.h b/contrib/llvm-project/libcxx/include/__algorithm/minmax_element.h index fe5f20bf1c7f..cf67184e0b4c 100644 --- a/contrib/llvm-project/libcxx/include/__algorithm/minmax_element.h +++ b/contrib/llvm-project/libcxx/include/__algorithm/minmax_element.h @@ -24,17 +24,17 @@ _LIBCPP_BEGIN_NAMESPACE_STD template class _MinmaxElementLessFunc { - _Comp& __comp; - _Proj& __proj; + _Comp& __comp_; + _Proj& __proj_; public: _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR - _MinmaxElementLessFunc(_Comp& __comp_, _Proj& __proj_) : __comp(__comp_), __proj(__proj_) {} + _MinmaxElementLessFunc(_Comp& __comp, _Proj& __proj) : __comp_(__comp), __proj_(__proj) {} template _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX11 bool operator()(_Iter& __it1, _Iter& __it2) { - return std::__invoke(__comp, std::__invoke(__proj, *__it1), std::__invoke(__proj, *__it2)); + return std::__invoke(__comp_, std::__invoke(__proj_, *__it1), std::__invoke(__proj_, *__it2)); } }; diff --git a/contrib/llvm-project/libcxx/include/__algorithm/nth_element.h b/contrib/llvm-project/libcxx/include/__algorithm/nth_element.h index 60b9280f75f0..c7cdef5be817 100644 --- a/contrib/llvm-project/libcxx/include/__algorithm/nth_element.h +++ b/contrib/llvm-project/libcxx/include/__algorithm/nth_element.h @@ -14,13 +14,11 @@ #include <__algorithm/sort.h> #include <__config> #include <__debug> +#include <__debug_utils/randomize_range.h> #include <__iterator/iterator_traits.h> +#include <__utility/move.h> #include <__utility/swap.h> -#if defined(_LIBCPP_DEBUG_RANDOMIZE_UNSPECIFIED_STABILITY) -# include <__algorithm/shuffle.h> -#endif - #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) # pragma GCC system_header #endif @@ -223,25 +221,35 @@ __nth_element(_RandomAccessIterator __first, _RandomAccessIterator __nth, _Rando } template -inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 -void -nth_element(_RandomAccessIterator __first, _RandomAccessIterator __nth, _RandomAccessIterator __last, _Compare __comp) -{ - _LIBCPP_DEBUG_RANDOMIZE_RANGE(__first, __last); - typedef typename __comp_ref_type<_Compare>::type _Comp_ref; - _VSTD::__nth_element<_Comp_ref>(__first, __nth, __last, __comp); - _LIBCPP_DEBUG_RANDOMIZE_RANGE(__first, __nth); +inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX17 +void __nth_element_impl(_RandomAccessIterator __first, _RandomAccessIterator __nth, _RandomAccessIterator __last, + _Compare& __comp) { + if (__nth == __last) + return; + + std::__debug_randomize_range(__first, __last); + + using _Comp_ref = typename __comp_ref_type<_Compare>::type; + std::__nth_element<_Comp_ref>(__first, __nth, __last, __comp); + + std::__debug_randomize_range(__first, __nth); if (__nth != __last) { - _LIBCPP_DEBUG_RANDOMIZE_RANGE(++__nth, __last); + std::__debug_randomize_range(++__nth, __last); } } +template +inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX17 +void nth_element(_RandomAccessIterator __first, _RandomAccessIterator __nth, _RandomAccessIterator __last, + _Compare __comp) { + std::__nth_element_impl(std::move(__first), std::move(__nth), std::move(__last), __comp); +} + template -inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 -void -nth_element(_RandomAccessIterator __first, _RandomAccessIterator __nth, _RandomAccessIterator __last) -{ - _VSTD::nth_element(__first, __nth, __last, __less::value_type>()); +inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX17 +void nth_element(_RandomAccessIterator __first, _RandomAccessIterator __nth, _RandomAccessIterator __last) { + std::nth_element(std::move(__first), std::move(__nth), std::move(__last), __less::value_type>()); } _LIBCPP_END_NAMESPACE_STD diff --git a/contrib/llvm-project/libcxx/include/__algorithm/partial_sort.h b/contrib/llvm-project/libcxx/include/__algorithm/partial_sort.h index 3870c0cc9335..e008c0c99679 100644 --- a/contrib/llvm-project/libcxx/include/__algorithm/partial_sort.h +++ b/contrib/llvm-project/libcxx/include/__algorithm/partial_sort.h @@ -16,13 +16,10 @@ #include <__algorithm/sort_heap.h> #include <__config> #include <__debug> +#include <__debug_utils/randomize_range.h> #include <__iterator/iterator_traits.h> #include <__utility/swap.h> -#if defined(_LIBCPP_DEBUG_RANDOMIZE_UNSPECIFIED_STABILITY) -# include <__algorithm/shuffle.h> -#endif - #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) # pragma GCC system_header #endif @@ -55,10 +52,10 @@ void partial_sort(_RandomAccessIterator __first, _RandomAccessIterator __middle, _RandomAccessIterator __last, _Compare __comp) { - _LIBCPP_DEBUG_RANDOMIZE_RANGE(__first, __last); + std::__debug_randomize_range(__first, __last); typedef typename __comp_ref_type<_Compare>::type _Comp_ref; _VSTD::__partial_sort<_Comp_ref>(__first, __middle, __last, __comp); - _LIBCPP_DEBUG_RANDOMIZE_RANGE(__middle, __last); + std::__debug_randomize_range(__middle, __last); } template diff --git a/contrib/llvm-project/libcxx/include/__algorithm/pop_heap.h b/contrib/llvm-project/libcxx/include/__algorithm/pop_heap.h index 2932a5e31dbc..cadda81f6c88 100644 --- a/contrib/llvm-project/libcxx/include/__algorithm/pop_heap.h +++ b/contrib/llvm-project/libcxx/include/__algorithm/pop_heap.h @@ -13,6 +13,7 @@ #include <__algorithm/comp_ref_type.h> #include <__algorithm/push_heap.h> #include <__algorithm/sift_down.h> +#include <__assert> #include <__config> #include <__iterator/iterator_traits.h> #include <__utility/move.h> @@ -24,44 +25,43 @@ _LIBCPP_BEGIN_NAMESPACE_STD template -inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 -void -__pop_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp, - typename iterator_traits<_RandomAccessIterator>::difference_type __len) -{ - using value_type = typename iterator_traits<_RandomAccessIterator>::value_type; +inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX11 +void __pop_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare& __comp, + typename iterator_traits<_RandomAccessIterator>::difference_type __len) { + _LIBCPP_ASSERT(__len > 0, "The heap given to pop_heap must be non-empty"); - if (__len > 1) - { - value_type __top = std::move(*__first); // create a hole at __first - _RandomAccessIterator __hole = std::__floyd_sift_down<_Compare>(__first, __comp, __len); - --__last; - if (__hole == __last) { - *__hole = std::move(__top); - } else { - *__hole = std::move(*__last); - ++__hole; - *__last = std::move(__top); - std::__sift_up<_Compare>(__first, __hole, __comp, __hole - __first); - } + using _CompRef = typename __comp_ref_type<_Compare>::type; + _CompRef __comp_ref = __comp; + + using value_type = typename iterator_traits<_RandomAccessIterator>::value_type; + if (__len > 1) { + value_type __top = std::move(*__first); // create a hole at __first + _RandomAccessIterator __hole = std::__floyd_sift_down<_CompRef>(__first, __comp_ref, __len); + --__last; + + if (__hole == __last) { + *__hole = std::move(__top); + } else { + *__hole = std::move(*__last); + ++__hole; + *__last = std::move(__top); + std::__sift_up<_CompRef>(__first, __hole, __comp_ref, __hole - __first); } + } } template -inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 -void -pop_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp) -{ - typedef typename __comp_ref_type<_Compare>::type _Comp_ref; - _VSTD::__pop_heap<_Comp_ref>(__first, __last, __comp, __last - __first); +inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX17 +void pop_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp) { + typename iterator_traits<_RandomAccessIterator>::difference_type __len = __last - __first; + std::__pop_heap(std::move(__first), std::move(__last), __comp, __len); } template -inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 -void -pop_heap(_RandomAccessIterator __first, _RandomAccessIterator __last) -{ - _VSTD::pop_heap(__first, __last, __less::value_type>()); +inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX17 +void pop_heap(_RandomAccessIterator __first, _RandomAccessIterator __last) { + std::pop_heap(std::move(__first), std::move(__last), + __less::value_type>()); } _LIBCPP_END_NAMESPACE_STD diff --git a/contrib/llvm-project/libcxx/include/__algorithm/push_heap.h b/contrib/llvm-project/libcxx/include/__algorithm/push_heap.h index 66973e082f14..1e3eec373d4f 100644 --- a/contrib/llvm-project/libcxx/include/__algorithm/push_heap.h +++ b/contrib/llvm-project/libcxx/include/__algorithm/push_heap.h @@ -22,47 +22,50 @@ _LIBCPP_BEGIN_NAMESPACE_STD template -_LIBCPP_CONSTEXPR_AFTER_CXX11 void -__sift_up(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp, - typename iterator_traits<_RandomAccessIterator>::difference_type __len) -{ - typedef typename iterator_traits<_RandomAccessIterator>::value_type value_type; - if (__len > 1) - { - __len = (__len - 2) / 2; - _RandomAccessIterator __ptr = __first + __len; - if (__comp(*__ptr, *--__last)) - { - value_type __t(_VSTD::move(*__last)); - do - { - *__last = _VSTD::move(*__ptr); - __last = __ptr; - if (__len == 0) - break; - __len = (__len - 1) / 2; - __ptr = __first + __len; - } while (__comp(*__ptr, __t)); - *__last = _VSTD::move(__t); - } +_LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX11 +void __sift_up(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp, + typename iterator_traits<_RandomAccessIterator>::difference_type __len) { + using value_type = typename iterator_traits<_RandomAccessIterator>::value_type; + + if (__len > 1) { + __len = (__len - 2) / 2; + _RandomAccessIterator __ptr = __first + __len; + + if (__comp(*__ptr, *--__last)) { + value_type __t(std::move(*__last)); + do { + *__last = std::move(*__ptr); + __last = __ptr; + if (__len == 0) + break; + __len = (__len - 1) / 2; + __ptr = __first + __len; + } while (__comp(*__ptr, __t)); + + *__last = std::move(__t); } + } +} + +template +inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX11 +void __push_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare& __comp) { + using _CompRef = typename __comp_ref_type<_Compare>::type; + typename iterator_traits<_RandomAccessIterator>::difference_type __len = __last - __first; + std::__sift_up<_CompRef>(std::move(__first), std::move(__last), __comp, __len); } template -inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 -void -push_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp) -{ - typedef typename __comp_ref_type<_Compare>::type _Comp_ref; - _VSTD::__sift_up<_Comp_ref>(__first, __last, __comp, __last - __first); +inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX17 +void push_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp) { + std::__push_heap(std::move(__first), std::move(__last), __comp); } template -inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 -void -push_heap(_RandomAccessIterator __first, _RandomAccessIterator __last) -{ - _VSTD::push_heap(__first, __last, __less::value_type>()); +inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX17 +void push_heap(_RandomAccessIterator __first, _RandomAccessIterator __last) { + std::push_heap(std::move(__first), std::move(__last), + __less::value_type>()); } _LIBCPP_END_NAMESPACE_STD diff --git a/contrib/llvm-project/libcxx/include/__algorithm/ranges_binary_search.h b/contrib/llvm-project/libcxx/include/__algorithm/ranges_binary_search.h index 68359fb1388f..6da68834aa3b 100644 --- a/contrib/llvm-project/libcxx/include/__algorithm/ranges_binary_search.h +++ b/contrib/llvm-project/libcxx/include/__algorithm/ranges_binary_search.h @@ -35,7 +35,7 @@ struct __fn { indirect_strict_weak_order> _Comp = ranges::less> _LIBCPP_HIDE_FROM_ABI constexpr bool operator()(_Iter __first, _Sent __last, const _Type& __value, _Comp __comp = {}, _Proj __proj = {}) const { - auto __ret = std::__lower_bound_impl<_RangesIterOps>(__first, __last, __value, __comp, __proj); + auto __ret = std::__lower_bound_impl<_RangeAlgPolicy>(__first, __last, __value, __comp, __proj); return __ret != __last && !std::invoke(__comp, __value, std::invoke(__proj, *__first)); } @@ -45,7 +45,7 @@ struct __fn { bool operator()(_Range&& __r, const _Type& __value, _Comp __comp = {}, _Proj __proj = {}) const { auto __first = ranges::begin(__r); auto __last = ranges::end(__r); - auto __ret = std::__lower_bound_impl<_RangesIterOps>(__first, __last, __value, __comp, __proj); + auto __ret = std::__lower_bound_impl<_RangeAlgPolicy>(__first, __last, __value, __comp, __proj); return __ret != __last && !std::invoke(__comp, __value, std::invoke(__proj, *__first)); } }; diff --git a/contrib/llvm-project/libcxx/include/__algorithm/ranges_equal_range.h b/contrib/llvm-project/libcxx/include/__algorithm/ranges_equal_range.h new file mode 100644 index 000000000000..28d721530bda --- /dev/null +++ b/contrib/llvm-project/libcxx/include/__algorithm/ranges_equal_range.h @@ -0,0 +1,74 @@ +//===----------------------------------------------------------------------===// +// +// Part of the LLVM __project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef _LIBCPP___ALGORITHM_RANGES_EQUAL_RANGE_H +#define _LIBCPP___ALGORITHM_RANGES_EQUAL_RANGE_H + +#include <__algorithm/equal_range.h> +#include <__algorithm/make_projected.h> +#include <__config> +#include <__functional/identity.h> +#include <__functional/invoke.h> +#include <__functional/ranges_operations.h> +#include <__iterator/concepts.h> +#include <__iterator/iterator_traits.h> +#include <__iterator/projected.h> +#include <__ranges/access.h> +#include <__ranges/concepts.h> +#include <__ranges/dangling.h> +#include <__ranges/subrange.h> +#include <__utility/forward.h> +#include <__utility/move.h> + +#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) +# pragma GCC system_header +#endif + +#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +_LIBCPP_BEGIN_NAMESPACE_STD + +namespace ranges { +namespace __equal_range { + +struct __fn { + + template _Sent, class _Tp, class _Proj = identity, + indirect_strict_weak_order> _Comp = ranges::less> + _LIBCPP_HIDE_FROM_ABI constexpr + subrange<_Iter> operator()(_Iter __first, _Sent __last, const _Tp& __value, _Comp __comp = {}, + _Proj __proj = {}) const { + // TODO: implement + (void)__first; (void)__last; (void)__value; (void)__comp; (void)__proj; + return {}; + } + + template , _Proj>> _Comp = ranges::less> + _LIBCPP_HIDE_FROM_ABI constexpr + borrowed_subrange_t<_Range> operator()(_Range&& __range, const _Tp& __value, _Comp __comp = {}, + _Proj __proj = {}) const { + // TODO: implement + (void)__range; (void)__value; (void)__comp; (void)__proj; + return {}; + } + +}; + +} // namespace __equal_range + +inline namespace __cpo { + inline constexpr auto equal_range = __equal_range::__fn{}; +} // namespace __cpo +} // namespace ranges + +_LIBCPP_END_NAMESPACE_STD + +#endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +#endif // _LIBCPP___ALGORITHM_RANGES_EQUAL_RANGE_H diff --git a/contrib/llvm-project/libcxx/include/__algorithm/ranges_find_end.h b/contrib/llvm-project/libcxx/include/__algorithm/ranges_find_end.h new file mode 100644 index 000000000000..fec709e79f5a --- /dev/null +++ b/contrib/llvm-project/libcxx/include/__algorithm/ranges_find_end.h @@ -0,0 +1,113 @@ +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef _LIBCPP___ALGORITHM_RANGES_FIND_END_H +#define _LIBCPP___ALGORITHM_RANGES_FIND_END_H + +#include <__algorithm/find_end.h> +#include <__algorithm/iterator_operations.h> +#include <__config> +#include <__functional/identity.h> +#include <__functional/ranges_operations.h> +#include <__iterator/concepts.h> +#include <__iterator/indirectly_comparable.h> +#include <__iterator/iterator_traits.h> +#include <__ranges/access.h> +#include <__ranges/concepts.h> +#include <__ranges/subrange.h> + +#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) +# pragma GCC system_header +#endif + +#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +_LIBCPP_BEGIN_NAMESPACE_STD + +template +consteval auto __get_iterator_concept() { + if constexpr (contiguous_iterator<_Iter>) + return contiguous_iterator_tag(); + else if constexpr (random_access_iterator<_Iter>) + return random_access_iterator_tag(); + else if constexpr (bidirectional_iterator<_Iter>) + return bidirectional_iterator_tag(); + else if constexpr (forward_iterator<_Iter>) + return forward_iterator_tag(); + else if constexpr (input_iterator<_Iter>) + return input_iterator_tag(); +} + +template +using __iterator_concept = decltype(__get_iterator_concept<_Iter>()); + +namespace ranges { +namespace __find_end { +struct __fn { + template _Sent1, + forward_iterator _Iter2, sentinel_for<_Iter2> _Sent2, + class _Pred = ranges::equal_to, + class _Proj1 = identity, + class _Proj2 = identity> + requires indirectly_comparable<_Iter1, _Iter2, _Pred, _Proj1, _Proj2> + _LIBCPP_HIDE_FROM_ABI constexpr + subrange<_Iter1> operator()(_Iter1 __first1, _Sent1 __last1, + _Iter2 __first2, _Sent2 __last2, + _Pred __pred = {}, + _Proj1 __proj1 = {}, + _Proj2 __proj2 = {}) const { + auto __ret = std::__find_end_impl<_RangeAlgPolicy>( + __first1, + __last1, + __first2, + __last2, + __pred, + __proj1, + __proj2, + __iterator_concept<_Iter1>(), + __iterator_concept<_Iter2>()); + return {__ret.first, __ret.second}; + } + + template + requires indirectly_comparable, iterator_t<_Range2>, _Pred, _Proj1, _Proj2> + _LIBCPP_HIDE_FROM_ABI constexpr + borrowed_subrange_t<_Range1> operator()(_Range1&& __range1, + _Range2&& __range2, + _Pred __pred = {}, + _Proj1 __proj1 = {}, + _Proj2 __proj2 = {}) const { + auto __ret = std::__find_end_impl<_RangeAlgPolicy>( + ranges::begin(__range1), + ranges::end(__range1), + ranges::begin(__range2), + ranges::end(__range2), + __pred, + __proj1, + __proj2, + __iterator_concept>(), + __iterator_concept>()); + return {__ret.first, __ret.second}; + } +}; +} // namespace __find_end + +inline namespace __cpo { + inline constexpr auto find_end = __find_end::__fn{}; +} // namespace __cpo +} // namespace ranges + +_LIBCPP_END_NAMESPACE_STD + +#endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +#endif // _LIBCPP___ALGORITHM_RANGES_FIND_END_H diff --git a/contrib/llvm-project/libcxx/include/__algorithm/ranges_generate.h b/contrib/llvm-project/libcxx/include/__algorithm/ranges_generate.h new file mode 100644 index 000000000000..c23645e6d906 --- /dev/null +++ b/contrib/llvm-project/libcxx/include/__algorithm/ranges_generate.h @@ -0,0 +1,73 @@ +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef _LIBCPP___ALGORITHM_RANGES_GENERATE_H +#define _LIBCPP___ALGORITHM_RANGES_GENERATE_H + +#include <__algorithm/generate.h> +#include <__algorithm/make_projected.h> +#include <__concepts/constructible.h> +#include <__concepts/invocable.h> +#include <__config> +#include <__functional/identity.h> +#include <__functional/invoke.h> +#include <__functional/ranges_operations.h> +#include <__iterator/concepts.h> +#include <__iterator/iterator_traits.h> +#include <__iterator/projected.h> +#include <__ranges/access.h> +#include <__ranges/concepts.h> +#include <__ranges/dangling.h> +#include <__utility/forward.h> +#include <__utility/move.h> + +#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) +# pragma GCC system_header +#endif + +#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +_LIBCPP_BEGIN_NAMESPACE_STD + +namespace ranges { +namespace __generate { + +struct __fn { + + template _Sent, copy_constructible _Func> + requires invocable<_Func&> && indirectly_writable<_OutIter, invoke_result_t<_Func&>> + _LIBCPP_HIDE_FROM_ABI constexpr + _OutIter operator()(_OutIter __first, _Sent __last, _Func __gen) const { + // TODO: implement + (void)__first; (void)__last; (void)__gen; + return {}; + } + + template + requires invocable<_Func&> && output_range<_Range, invoke_result_t<_Func&>> + _LIBCPP_HIDE_FROM_ABI constexpr + borrowed_iterator_t<_Range> operator()(_Range&& __range, _Func __gen) const { + // TODO: implement + (void)__range; (void)__gen; + return {}; + } + +}; + +} // namespace __generate + +inline namespace __cpo { + inline constexpr auto generate = __generate::__fn{}; +} // namespace __cpo +} // namespace ranges + +_LIBCPP_END_NAMESPACE_STD + +#endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +#endif // _LIBCPP___ALGORITHM_RANGES_GENERATE_H diff --git a/contrib/llvm-project/libcxx/include/__algorithm/ranges_generate_n.h b/contrib/llvm-project/libcxx/include/__algorithm/ranges_generate_n.h new file mode 100644 index 000000000000..bcf50e025ecc --- /dev/null +++ b/contrib/llvm-project/libcxx/include/__algorithm/ranges_generate_n.h @@ -0,0 +1,65 @@ +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef _LIBCPP___ALGORITHM_RANGES_GENERATE_N_H +#define _LIBCPP___ALGORITHM_RANGES_GENERATE_N_H + +#include <__algorithm/generate_n.h> +#include <__algorithm/make_projected.h> +#include <__concepts/constructible.h> +#include <__concepts/invocable.h> +#include <__config> +#include <__functional/identity.h> +#include <__functional/invoke.h> +#include <__functional/ranges_operations.h> +#include <__iterator/concepts.h> +#include <__iterator/incrementable_traits.h> +#include <__iterator/iterator_traits.h> +#include <__iterator/projected.h> +#include <__ranges/access.h> +#include <__ranges/concepts.h> +#include <__ranges/dangling.h> +#include <__utility/forward.h> +#include <__utility/move.h> + +#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) +# pragma GCC system_header +#endif + +#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +_LIBCPP_BEGIN_NAMESPACE_STD + +namespace ranges { +namespace __generate_n { + +struct __fn { + + template + requires invocable<_Func&> && indirectly_writable<_OutIter, invoke_result_t<_Func&>> + _LIBCPP_HIDE_FROM_ABI constexpr + _OutIter operator()(_OutIter __first, iter_difference_t<_OutIter> __n, _Func __gen) const { + // TODO: implement + (void)__first; (void)__n; (void)__gen; + return {}; + } + +}; + +} // namespace __generate_n + +inline namespace __cpo { + inline constexpr auto generate_n = __generate_n::__fn{}; +} // namespace __cpo +} // namespace ranges + +_LIBCPP_END_NAMESPACE_STD + +#endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +#endif // _LIBCPP___ALGORITHM_RANGES_GENERATE_N_H diff --git a/contrib/llvm-project/libcxx/include/__algorithm/ranges_includes.h b/contrib/llvm-project/libcxx/include/__algorithm/ranges_includes.h new file mode 100644 index 000000000000..19c17870ed6f --- /dev/null +++ b/contrib/llvm-project/libcxx/include/__algorithm/ranges_includes.h @@ -0,0 +1,75 @@ +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef _LIBCPP___ALGORITHM_RANGES_INCLUDES_H +#define _LIBCPP___ALGORITHM_RANGES_INCLUDES_H + +#include <__algorithm/make_projected.h> +#include <__algorithm/includes.h> +#include <__config> +#include <__functional/identity.h> +#include <__functional/invoke.h> +#include <__functional/ranges_operations.h> +#include <__iterator/concepts.h> +#include <__iterator/iterator_traits.h> +#include <__iterator/projected.h> +#include <__ranges/access.h> +#include <__ranges/concepts.h> +#include <__ranges/dangling.h> +#include <__utility/forward.h> +#include <__utility/move.h> + +#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) +# pragma GCC system_header +#endif + +#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +_LIBCPP_BEGIN_NAMESPACE_STD + +namespace ranges { +namespace __includes { + +struct __fn { + + template _Sent1, input_iterator _Iter2, sentinel_for<_Iter2> _Sent2, + class _Proj1 = identity, class _Proj2 = identity, + indirect_strict_weak_order, projected<_Iter2, _Proj2>> _Comp = ranges::less> + _LIBCPP_HIDE_FROM_ABI constexpr + bool operator()(_Iter1 __first1, _Sent1 __last1, _Iter2 __first2, _Sent2 __last2, _Comp __comp = {}, + _Proj1 __proj1 = {}, _Proj2 __proj2 = {}) const { + // TODO: implement + (void)__first1; (void)__last1; (void)__first2; (void)__last2; (void)__comp; (void)__proj1; (void)__proj2; + return {}; + } + + template , _Proj1>, + projected, _Proj2>> _Comp = ranges::less> + _LIBCPP_HIDE_FROM_ABI constexpr + bool operator()(_Range1&& __range1, _Range2&& __range2, _Comp __comp = {}, + _Proj1 __proj1 = {}, _Proj2 __proj2 = {}) const { + // TODO: implement + (void)__range1; (void)__range2; (void)__comp; (void)__proj1; (void)__proj2; + return {}; + } + +}; + +} // namespace __includes + +inline namespace __cpo { + inline constexpr auto includes = __includes::__fn{}; +} // namespace __cpo +} // namespace ranges + +_LIBCPP_END_NAMESPACE_STD + +#endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +#endif // _LIBCPP___ALGORITHM_RANGES_INCLUDES_H diff --git a/contrib/llvm-project/libcxx/include/__algorithm/ranges_inplace_merge.h b/contrib/llvm-project/libcxx/include/__algorithm/ranges_inplace_merge.h new file mode 100644 index 000000000000..a0867e486c3a --- /dev/null +++ b/contrib/llvm-project/libcxx/include/__algorithm/ranges_inplace_merge.h @@ -0,0 +1,73 @@ +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef _LIBCPP___ALGORITHM_RANGES_INPLACE_MERGE_H +#define _LIBCPP___ALGORITHM_RANGES_INPLACE_MERGE_H + +#include <__algorithm/inplace_merge.h> +#include <__algorithm/make_projected.h> +#include <__config> +#include <__functional/identity.h> +#include <__functional/invoke.h> +#include <__functional/ranges_operations.h> +#include <__iterator/concepts.h> +#include <__iterator/iterator_traits.h> +#include <__iterator/projected.h> +#include <__iterator/sortable.h> +#include <__ranges/access.h> +#include <__ranges/concepts.h> +#include <__ranges/dangling.h> +#include <__utility/forward.h> +#include <__utility/move.h> + +#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) +# pragma GCC system_header +#endif + +#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +_LIBCPP_BEGIN_NAMESPACE_STD + +namespace ranges { +namespace __inplace_merge { + +struct __fn { + + template _Sent, class _Comp = ranges::less, class _Proj = identity> + requires sortable<_Iter, _Comp, _Proj> + _LIBCPP_HIDE_FROM_ABI + _Iter operator()(_Iter __first, _Iter __middle, _Sent __last, _Comp __comp = {}, _Proj __proj = {}) const { + // TODO: implement + (void)__first; (void)__middle; (void)__last; (void)__comp; (void)__proj; + return {}; + } + + template + requires sortable, _Comp, _Proj> + _LIBCPP_HIDE_FROM_ABI + borrowed_iterator_t<_Range> operator()(_Range&& __range, iterator_t<_Range> __middle, + _Comp __comp = {}, _Proj __proj = {}) const { + // TODO: implement + (void)__range; (void)__middle; (void)__comp; (void)__proj; + return {}; + } + +}; + +} // namespace __inplace_merge + +inline namespace __cpo { + inline constexpr auto inplace_merge = __inplace_merge::__fn{}; +} // namespace __cpo +} // namespace ranges + +_LIBCPP_END_NAMESPACE_STD + +#endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +#endif // _LIBCPP___ALGORITHM_RANGES_INPLACE_MERGE_H diff --git a/contrib/llvm-project/libcxx/include/__algorithm/ranges_is_heap.h b/contrib/llvm-project/libcxx/include/__algorithm/ranges_is_heap.h new file mode 100644 index 000000000000..0f10fa4dcec9 --- /dev/null +++ b/contrib/llvm-project/libcxx/include/__algorithm/ranges_is_heap.h @@ -0,0 +1,70 @@ +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef _LIBCPP___ALGORITHM_RANGES_IS_HEAP_H +#define _LIBCPP___ALGORITHM_RANGES_IS_HEAP_H + +#include <__algorithm/is_heap.h> +#include <__algorithm/make_projected.h> +#include <__config> +#include <__functional/identity.h> +#include <__functional/invoke.h> +#include <__functional/ranges_operations.h> +#include <__iterator/concepts.h> +#include <__iterator/iterator_traits.h> +#include <__iterator/projected.h> +#include <__ranges/access.h> +#include <__ranges/concepts.h> +#include <__ranges/dangling.h> +#include <__utility/forward.h> +#include <__utility/move.h> + +#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) +# pragma GCC system_header +#endif + +#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +_LIBCPP_BEGIN_NAMESPACE_STD + +namespace ranges { +namespace __is_heap { + +struct __fn { + + template _Sent, class _Proj = identity, + indirect_strict_weak_order> _Comp = ranges::less> + _LIBCPP_HIDE_FROM_ABI constexpr + bool operator()(_Iter __first, _Sent __last, _Comp __comp = {}, _Proj __proj = {}) const { + // TODO: implement + (void)__first; (void)__last; (void)__comp; (void)__proj; + return {}; + } + + template , _Proj>> _Comp = ranges::less> + _LIBCPP_HIDE_FROM_ABI constexpr + bool operator()(_Range&& __range, _Comp __comp = {}, _Proj __proj = {}) const { + // TODO: implement + (void)__range; (void)__comp; (void)__proj; + return {}; + } +}; + +} // namespace __is_heap + +inline namespace __cpo { + inline constexpr auto is_heap = __is_heap::__fn{}; +} // namespace __cpo +} // namespace ranges + +_LIBCPP_END_NAMESPACE_STD + +#endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +#endif // _LIBCPP___ALGORITHM_RANGES_IS_HEAP_H diff --git a/contrib/llvm-project/libcxx/include/__algorithm/ranges_is_heap_until.h b/contrib/llvm-project/libcxx/include/__algorithm/ranges_is_heap_until.h new file mode 100644 index 000000000000..ad021d6f2525 --- /dev/null +++ b/contrib/llvm-project/libcxx/include/__algorithm/ranges_is_heap_until.h @@ -0,0 +1,71 @@ +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef _LIBCPP___ALGORITHM_RANGES_IS_HEAP_UNTIL_H +#define _LIBCPP___ALGORITHM_RANGES_IS_HEAP_UNTIL_H + +#include <__algorithm/is_heap_until.h> +#include <__algorithm/make_projected.h> +#include <__config> +#include <__functional/identity.h> +#include <__functional/invoke.h> +#include <__functional/ranges_operations.h> +#include <__iterator/concepts.h> +#include <__iterator/iterator_traits.h> +#include <__iterator/projected.h> +#include <__ranges/access.h> +#include <__ranges/concepts.h> +#include <__ranges/dangling.h> +#include <__utility/forward.h> +#include <__utility/move.h> + +#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) +# pragma GCC system_header +#endif + +#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +_LIBCPP_BEGIN_NAMESPACE_STD + +namespace ranges { +namespace __is_heap_until { + +struct __fn { + + template _Sent, class _Proj = identity, + indirect_strict_weak_order> _Comp = ranges::less> + _LIBCPP_HIDE_FROM_ABI constexpr + _Iter operator()(_Iter __first, _Sent __last, _Comp __comp = {}, _Proj __proj = {}) const { + // TODO: implement + (void)__first; (void)__last; (void)__comp; (void)__proj; + return {}; + } + + template , _Proj>> _Comp = ranges::less> + _LIBCPP_HIDE_FROM_ABI constexpr + borrowed_iterator_t<_Range> operator()(_Range&& __range, _Comp __comp = {}, _Proj __proj = {}) const { + // TODO: implement + (void)__range; (void)__comp; (void)__proj; + return {}; + } + +}; + +} // namespace __is_heap_until + +inline namespace __cpo { + inline constexpr auto is_heap_until = __is_heap_until::__fn{}; +} // namespace __cpo +} // namespace ranges + +_LIBCPP_END_NAMESPACE_STD + +#endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +#endif // _LIBCPP___ALGORITHM_RANGES_IS_HEAP_UNTIL_H diff --git a/contrib/llvm-project/libcxx/include/__algorithm/ranges_lower_bound.h b/contrib/llvm-project/libcxx/include/__algorithm/ranges_lower_bound.h index a73470465cfd..1a9ae204a1ee 100644 --- a/contrib/llvm-project/libcxx/include/__algorithm/ranges_lower_bound.h +++ b/contrib/llvm-project/libcxx/include/__algorithm/ranges_lower_bound.h @@ -39,7 +39,7 @@ struct __fn { indirect_strict_weak_order> _Comp = ranges::less> _LIBCPP_HIDE_FROM_ABI constexpr _Iter operator()(_Iter __first, _Sent __last, const _Type& __value, _Comp __comp = {}, _Proj __proj = {}) const { - return std::__lower_bound_impl<_RangesIterOps>(__first, __last, __value, __comp, __proj); + return std::__lower_bound_impl<_RangeAlgPolicy>(__first, __last, __value, __comp, __proj); } template (ranges::begin(__r), ranges::end(__r), __value, __comp, __proj); + return std::__lower_bound_impl<_RangeAlgPolicy>(ranges::begin(__r), ranges::end(__r), __value, __comp, __proj); } }; } // namespace __lower_bound diff --git a/contrib/llvm-project/libcxx/include/__algorithm/ranges_make_heap.h b/contrib/llvm-project/libcxx/include/__algorithm/ranges_make_heap.h new file mode 100644 index 000000000000..fd488dc11a4b --- /dev/null +++ b/contrib/llvm-project/libcxx/include/__algorithm/ranges_make_heap.h @@ -0,0 +1,79 @@ +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef _LIBCPP___ALGORITHM_RANGES_MAKE_HEAP_H +#define _LIBCPP___ALGORITHM_RANGES_MAKE_HEAP_H + +#include <__algorithm/make_heap.h> +#include <__algorithm/make_projected.h> +#include <__concepts/same_as.h> +#include <__config> +#include <__functional/identity.h> +#include <__functional/invoke.h> +#include <__functional/ranges_operations.h> +#include <__iterator/concepts.h> +#include <__iterator/iterator_traits.h> +#include <__iterator/next.h> +#include <__iterator/projected.h> +#include <__iterator/sortable.h> +#include <__ranges/access.h> +#include <__ranges/concepts.h> +#include <__ranges/dangling.h> +#include <__utility/forward.h> +#include <__utility/move.h> + +#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) +# pragma GCC system_header +#endif + +#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +_LIBCPP_BEGIN_NAMESPACE_STD + +namespace ranges { +namespace __make_heap { + +struct __fn { + template + _LIBCPP_HIDE_FROM_ABI constexpr static + _Iter __make_heap_fn_impl(_Iter __first, _Sent __last, _Comp& __comp, _Proj& __proj) { + auto __last_iter = ranges::next(__first, __last); + + auto&& __projected_comp = ranges::__make_projected_comp(__comp, __proj); + std::__make_heap(std::move(__first), __last_iter, __projected_comp); + + return __last_iter; + } + + template _Sent, class _Comp = ranges::less, class _Proj = identity> + requires sortable<_Iter, _Comp, _Proj> + _LIBCPP_HIDE_FROM_ABI constexpr + _Iter operator()(_Iter __first, _Sent __last, _Comp __comp = {}, _Proj __proj = {}) const { + return __make_heap_fn_impl(std::move(__first), std::move(__last), __comp, __proj); + } + + template + requires sortable, _Comp, _Proj> + _LIBCPP_HIDE_FROM_ABI constexpr + borrowed_iterator_t<_Range> operator()(_Range&& __r, _Comp __comp = {}, _Proj __proj = {}) const { + return __make_heap_fn_impl(ranges::begin(__r), ranges::end(__r), __comp, __proj); + } +}; + +} // namespace __make_heap + +inline namespace __cpo { + inline constexpr auto make_heap = __make_heap::__fn{}; +} // namespace __cpo +} // namespace ranges + +_LIBCPP_END_NAMESPACE_STD + +#endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +#endif // _LIBCPP___ALGORITHM_RANGES_MAKE_HEAP_H diff --git a/contrib/llvm-project/libcxx/include/__algorithm/ranges_merge.h b/contrib/llvm-project/libcxx/include/__algorithm/ranges_merge.h new file mode 100644 index 000000000000..c73e09e94ccc --- /dev/null +++ b/contrib/llvm-project/libcxx/include/__algorithm/ranges_merge.h @@ -0,0 +1,142 @@ +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef _LIBCPP___ALGORITHM_RANGES_MERGE_H +#define _LIBCPP___ALGORITHM_RANGES_MERGE_H + +#include <__algorithm/in_in_out_result.h> +#include <__algorithm/ranges_copy.h> +#include <__config> +#include <__functional/identity.h> +#include <__functional/invoke.h> +#include <__functional/ranges_operations.h> +#include <__iterator/concepts.h> +#include <__iterator/mergeable.h> +#include <__ranges/access.h> +#include <__ranges/concepts.h> +#include <__ranges/dangling.h> +#include <__utility/move.h> +#include + +#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) +# pragma GCC system_header +#endif + +#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +_LIBCPP_BEGIN_NAMESPACE_STD + +namespace ranges { + +template +using merge_result = in_in_out_result<_InIter1, _InIter2, _OutIter>; + +namespace __merge { + +template < + class _InIter1, + class _Sent1, + class _InIter2, + class _Sent2, + class _OutIter, + class _Comp, + class _Proj1, + class _Proj2> +_LIBCPP_HIDE_FROM_ABI constexpr merge_result<__uncvref_t<_InIter1>, __uncvref_t<_InIter2>, __uncvref_t<_OutIter>> +__merge_impl( + _InIter1&& __first1, + _Sent1&& __last1, + _InIter2&& __first2, + _Sent2&& __last2, + _OutIter&& __result, + _Comp&& __comp, + _Proj1&& __proj1, + _Proj2&& __proj2) { + for (; __first1 != __last1 && __first2 != __last2; ++__result) { + if (std::invoke(__comp, std::invoke(__proj2, *__first2), std::invoke(__proj1, *__first1))) { + *__result = *__first2; + ++__first2; + } else { + *__result = *__first1; + ++__first1; + } + } + auto __ret1 = ranges::copy(std::move(__first1), std::move(__last1), std::move(__result)); + auto __ret2 = ranges::copy(std::move(__first2), std::move(__last2), std::move(__ret1.out)); + return {std::move(__ret1.in), std::move(__ret2.in), std::move(__ret2.out)}; +} + +struct __fn { + template < + input_iterator _InIter1, + sentinel_for<_InIter1> _Sent1, + input_iterator _InIter2, + sentinel_for<_InIter2> _Sent2, + weakly_incrementable _OutIter, + class _Comp = less, + class _Proj1 = identity, + class _Proj2 = identity> + requires mergeable<_InIter1, _InIter2, _OutIter, _Comp, _Proj1, _Proj2> + _LIBCPP_HIDE_FROM_ABI constexpr merge_result<_InIter1, _InIter2, _OutIter> operator()( + _InIter1 __first1, + _Sent1 __last1, + _InIter2 __first2, + _Sent2 __last2, + _OutIter __result, + _Comp __comp = {}, + _Proj1 __proj1 = {}, + _Proj2 __proj2 = {}) const { + return __merge::__merge_impl(__first1, __last1, __first2, __last2, __result, __comp, __proj1, __proj2); + } + + template < + input_range _Range1, + input_range _Range2, + weakly_incrementable _OutIter, + class _Comp = less, + class _Proj1 = identity, + class _Proj2 = identity> + requires mergeable< + iterator_t<_Range1>, + iterator_t<_Range2>, + _OutIter, + _Comp, + _Proj1, + _Proj2> + _LIBCPP_HIDE_FROM_ABI constexpr merge_result, borrowed_iterator_t<_Range2>, _OutIter> + operator()( + _Range1&& __range1, + _Range2&& __range2, + _OutIter __result, + _Comp __comp = {}, + _Proj1 __proj1 = {}, + _Proj2 __proj2 = {}) const { + return __merge::__merge_impl( + ranges::begin(__range1), + ranges::end(__range1), + ranges::begin(__range2), + ranges::end(__range2), + __result, + __comp, + __proj1, + __proj2); + } +}; + +} // namespace __merge + +inline namespace __cpo { + inline constexpr auto merge = __merge::__fn{}; +} // namespace __cpo +} // namespace ranges + +_LIBCPP_END_NAMESPACE_STD + +#endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +#endif // _LIBCPP___ALGORITHM_RANGES_MERGE_H diff --git a/contrib/llvm-project/libcxx/include/__algorithm/ranges_nth_element.h b/contrib/llvm-project/libcxx/include/__algorithm/ranges_nth_element.h new file mode 100644 index 000000000000..2a929eacb89d --- /dev/null +++ b/contrib/llvm-project/libcxx/include/__algorithm/ranges_nth_element.h @@ -0,0 +1,79 @@ +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef _LIBCPP___ALGORITHM_RANGES_NTH_ELEMENT_H +#define _LIBCPP___ALGORITHM_RANGES_NTH_ELEMENT_H + +#include <__algorithm/make_projected.h> +#include <__algorithm/nth_element.h> +#include <__config> +#include <__functional/identity.h> +#include <__functional/invoke.h> +#include <__functional/ranges_operations.h> +#include <__iterator/concepts.h> +#include <__iterator/iterator_traits.h> +#include <__iterator/next.h> +#include <__iterator/projected.h> +#include <__iterator/sortable.h> +#include <__ranges/access.h> +#include <__ranges/concepts.h> +#include <__ranges/dangling.h> +#include <__utility/forward.h> +#include <__utility/move.h> + +#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) +# pragma GCC system_header +#endif + +#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +_LIBCPP_BEGIN_NAMESPACE_STD + +namespace ranges { +namespace __nth_element { + +struct __fn { + template + _LIBCPP_HIDE_FROM_ABI constexpr static + _Iter __nth_element_fn_impl(_Iter __first, _Iter __nth, _Sent __last, _Comp& __comp, _Proj& __proj) { + auto __last_iter = ranges::next(__first, __last); + + auto&& __projected_comp = ranges::__make_projected_comp(__comp, __proj); + std::__nth_element_impl(std::move(__first), std::move(__nth), __last_iter, __projected_comp); + + return __last_iter; + } + + template _Sent, class _Comp = ranges::less, class _Proj = identity> + requires sortable<_Iter, _Comp, _Proj> + _LIBCPP_HIDE_FROM_ABI constexpr + _Iter operator()(_Iter __first, _Iter __nth, _Sent __last, _Comp __comp = {}, _Proj __proj = {}) const { + return __nth_element_fn_impl(std::move(__first), std::move(__nth), std::move(__last), __comp, __proj); + } + + template + requires sortable, _Comp, _Proj> + _LIBCPP_HIDE_FROM_ABI constexpr + borrowed_iterator_t<_Range> operator()(_Range&& __r, iterator_t<_Range> __nth, _Comp __comp = {}, + _Proj __proj = {}) const { + return __nth_element_fn_impl(ranges::begin(__r), std::move(__nth), ranges::end(__r), __comp, __proj); + } +}; + +} // namespace __nth_element + +inline namespace __cpo { + inline constexpr auto nth_element = __nth_element::__fn{}; +} // namespace __cpo +} // namespace ranges + +_LIBCPP_END_NAMESPACE_STD + +#endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +#endif // _LIBCPP___ALGORITHM_RANGES_NTH_ELEMENT_H diff --git a/contrib/llvm-project/libcxx/include/__algorithm/ranges_partial_sort_copy.h b/contrib/llvm-project/libcxx/include/__algorithm/ranges_partial_sort_copy.h new file mode 100644 index 000000000000..55ad2ca4e686 --- /dev/null +++ b/contrib/llvm-project/libcxx/include/__algorithm/ranges_partial_sort_copy.h @@ -0,0 +1,88 @@ +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef _LIBCPP___ALGORITHM_RANGES_PARTIAL_SORT_COPY_H +#define _LIBCPP___ALGORITHM_RANGES_PARTIAL_SORT_COPY_H + +#include <__algorithm/in_out_result.h> +#include <__algorithm/make_projected.h> +#include <__algorithm/partial_sort_copy.h> +#include <__config> +#include <__functional/identity.h> +#include <__functional/invoke.h> +#include <__functional/ranges_operations.h> +#include <__iterator/concepts.h> +#include <__iterator/iterator_traits.h> +#include <__iterator/projected.h> +#include <__iterator/sortable.h> +#include <__ranges/access.h> +#include <__ranges/concepts.h> +#include <__ranges/dangling.h> +#include <__utility/forward.h> +#include <__utility/move.h> + +#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) +# pragma GCC system_header +#endif + +#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +_LIBCPP_BEGIN_NAMESPACE_STD + +namespace ranges { + +template +using partial_sort_copy_result = in_out_result<_InIter, _OutIter>; + +namespace __partial_sort_copy { + +struct __fn { + + template _Sent1, + random_access_iterator _Iter2, sentinel_for<_Iter2> _Sent2, + class _Comp = ranges::less, class _Proj1 = identity, class _Proj2 = identity> + requires indirectly_copyable<_Iter1, _Iter2> && sortable<_Iter2, _Comp, _Proj2> && + indirect_strict_weak_order<_Comp, projected<_Iter1, _Proj1>, projected<_Iter2, _Proj2>> + _LIBCPP_HIDE_FROM_ABI constexpr + partial_sort_copy_result<_Iter1, _Iter2> + operator()(_Iter1 __first, _Sent1 __last, _Iter2 __result_first, _Sent2 __result_last, + _Comp __comp = {}, _Proj1 __proj1 = {}, _Proj2 __proj2 = {}) const { + // TODO: implement + (void)__first; (void)__last; (void)__result_first; (void)__result_last; (void)__comp; (void)__proj1; (void)__proj2; + return {}; + } + + template + requires indirectly_copyable, iterator_t<_Range2>> && + sortable, _Comp, _Proj2> && + indirect_strict_weak_order<_Comp, projected, _Proj1>, + projected, _Proj2>> + _LIBCPP_HIDE_FROM_ABI constexpr + partial_sort_copy_result, borrowed_iterator_t<_Range2>> + operator()(_Range1&& __range, _Range2&& __result_range, _Comp __comp = {}, + _Proj1 __proj1 = {}, _Proj2 __proj2 = {}) const { + // TODO: implement + (void)__range; (void)__result_range; (void)__comp; (void)__proj1; (void)__proj2; + return {}; + } + +}; + +} // namespace __partial_sort_copy + +inline namespace __cpo { + inline constexpr auto partial_sort_copy = __partial_sort_copy::__fn{}; +} // namespace __cpo +} // namespace ranges + +_LIBCPP_END_NAMESPACE_STD + +#endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +#endif // _LIBCPP___ALGORITHM_RANGES_PARTIAL_SORT_COPY_H diff --git a/contrib/llvm-project/libcxx/include/__algorithm/ranges_partition.h b/contrib/llvm-project/libcxx/include/__algorithm/ranges_partition.h new file mode 100644 index 000000000000..c145e7bdb4a2 --- /dev/null +++ b/contrib/llvm-project/libcxx/include/__algorithm/ranges_partition.h @@ -0,0 +1,74 @@ +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef _LIBCPP___ALGORITHM_RANGES_PARTITION_H +#define _LIBCPP___ALGORITHM_RANGES_PARTITION_H + +#include <__algorithm/make_projected.h> +#include <__algorithm/partition.h> +#include <__config> +#include <__functional/identity.h> +#include <__functional/invoke.h> +#include <__functional/ranges_operations.h> +#include <__iterator/concepts.h> +#include <__iterator/iterator_traits.h> +#include <__iterator/permutable.h> +#include <__iterator/projected.h> +#include <__ranges/access.h> +#include <__ranges/concepts.h> +#include <__ranges/dangling.h> +#include <__ranges/subrange.h> +#include <__utility/forward.h> +#include <__utility/move.h> + +#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) +# pragma GCC system_header +#endif + +#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +_LIBCPP_BEGIN_NAMESPACE_STD + +namespace ranges { +namespace __partition { + +struct __fn { + + template _Sent, class _Proj = identity, + indirect_unary_predicate> _Pred> + _LIBCPP_HIDE_FROM_ABI constexpr + subrange<_Iter> operator()(_Iter __first, _Sent __last, _Pred __pred, _Proj __proj = {}) const { + // TODO: implement + (void)__first; (void)__last; (void)__pred; (void)__proj; + return {}; + } + + template , _Proj>> _Pred> + requires permutable> + _LIBCPP_HIDE_FROM_ABI constexpr + borrowed_subrange_t<_Range> operator()(_Range&& __range, _Pred __pred, _Proj __proj = {}) const { + // TODO: implement + (void)__range; (void)__pred; (void)__proj; + return {}; + } + +}; + +} // namespace __partition + +inline namespace __cpo { + inline constexpr auto partition = __partition::__fn{}; +} // namespace __cpo +} // namespace ranges + +_LIBCPP_END_NAMESPACE_STD + +#endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +#endif // _LIBCPP___ALGORITHM_RANGES_PARTITION_H diff --git a/contrib/llvm-project/libcxx/include/__algorithm/ranges_partition_copy.h b/contrib/llvm-project/libcxx/include/__algorithm/ranges_partition_copy.h new file mode 100644 index 000000000000..f55089b94ea5 --- /dev/null +++ b/contrib/llvm-project/libcxx/include/__algorithm/ranges_partition_copy.h @@ -0,0 +1,82 @@ +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef _LIBCPP___ALGORITHM_RANGES_PARTITION_COPY_H +#define _LIBCPP___ALGORITHM_RANGES_PARTITION_COPY_H + +#include <__algorithm/in_out_out_result.h> +#include <__algorithm/make_projected.h> +#include <__algorithm/partition_copy.h> +#include <__config> +#include <__functional/identity.h> +#include <__functional/invoke.h> +#include <__functional/ranges_operations.h> +#include <__iterator/concepts.h> +#include <__iterator/iterator_traits.h> +#include <__iterator/projected.h> +#include <__ranges/access.h> +#include <__ranges/concepts.h> +#include <__ranges/dangling.h> +#include <__utility/forward.h> +#include <__utility/move.h> + +#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) +# pragma GCC system_header +#endif + +#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +_LIBCPP_BEGIN_NAMESPACE_STD + +namespace ranges { + +template +using partition_copy_result = in_out_out_result<_InIter, _OutIter1, _OutIter2>; + +namespace __partition_copy { + +struct __fn { + + template _Sent, + weakly_incrementable _OutIter1, weakly_incrementable _OutIter2, + class _Proj = identity, indirect_unary_predicate> _Pred> + requires indirectly_copyable<_InIter, _OutIter1> && indirectly_copyable<_InIter, _OutIter2> + _LIBCPP_HIDE_FROM_ABI constexpr + partition_copy_result<_InIter, _OutIter1, _OutIter2> + operator()(_InIter __first, _Sent __last, _OutIter1 __out_true, _OutIter2 __out_false, + _Pred __pred, _Proj __proj = {}) const { + // TODO: implement + (void)__first; (void)__last; (void)__out_true; (void)__out_false; (void)__pred; (void)__proj; + return {}; + } + + template , _Proj>> _Pred> + requires indirectly_copyable, _OutIter1> && indirectly_copyable, _OutIter2> + _LIBCPP_HIDE_FROM_ABI constexpr + partition_copy_result, _OutIter1, _OutIter2> + operator()(_Range&& __range, _OutIter1 __out_true, _OutIter2 __out_false, _Pred __pred, _Proj __proj = {}) const { + // TODO: implement + (void)__range; (void)__out_true; (void)__out_false; (void)__pred; (void)__proj; + return {}; + } + +}; + +} // namespace __partition_copy + +inline namespace __cpo { + inline constexpr auto partition_copy = __partition_copy::__fn{}; +} // namespace __cpo +} // namespace ranges + +_LIBCPP_END_NAMESPACE_STD + +#endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +#endif // _LIBCPP___ALGORITHM_RANGES_PARTITION_COPY_H diff --git a/contrib/llvm-project/libcxx/include/__algorithm/ranges_partition_point.h b/contrib/llvm-project/libcxx/include/__algorithm/ranges_partition_point.h new file mode 100644 index 000000000000..336b29f63284 --- /dev/null +++ b/contrib/llvm-project/libcxx/include/__algorithm/ranges_partition_point.h @@ -0,0 +1,71 @@ +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef _LIBCPP___ALGORITHM_RANGES_PARTITION_POINT_H +#define _LIBCPP___ALGORITHM_RANGES_PARTITION_POINT_H + +#include <__algorithm/make_projected.h> +#include <__algorithm/partition_point.h> +#include <__config> +#include <__functional/identity.h> +#include <__functional/invoke.h> +#include <__functional/ranges_operations.h> +#include <__iterator/concepts.h> +#include <__iterator/iterator_traits.h> +#include <__iterator/projected.h> +#include <__ranges/access.h> +#include <__ranges/concepts.h> +#include <__ranges/dangling.h> +#include <__utility/forward.h> +#include <__utility/move.h> + +#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) +# pragma GCC system_header +#endif + +#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +_LIBCPP_BEGIN_NAMESPACE_STD + +namespace ranges { +namespace __partition_point { + +struct __fn { + + template _Sent, class _Proj = identity, + indirect_unary_predicate> _Pred> + _LIBCPP_HIDE_FROM_ABI constexpr + _Iter operator()(_Iter __first, _Sent __last, _Pred __pred, _Proj __proj = {}) const { + // TODO: implement + (void)__first; (void)__last; (void)__pred; (void)__proj; + return {}; + } + + template , _Proj>> _Pred> + _LIBCPP_HIDE_FROM_ABI constexpr + borrowed_iterator_t<_Range> operator()(_Range&& __range, _Pred __pred, _Proj __proj = {}) const { + // TODO: implement + (void)__range; (void)__pred; (void)__proj; + return {}; + } + +}; + +} // namespace __partition_point + +inline namespace __cpo { + inline constexpr auto partition_point = __partition_point::__fn{}; +} // namespace __cpo +} // namespace ranges + +_LIBCPP_END_NAMESPACE_STD + +#endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +#endif // _LIBCPP___ALGORITHM_RANGES_PARTITION_POINT_H diff --git a/contrib/llvm-project/libcxx/include/__algorithm/ranges_pop_heap.h b/contrib/llvm-project/libcxx/include/__algorithm/ranges_pop_heap.h new file mode 100644 index 000000000000..d0b8314e5b0a --- /dev/null +++ b/contrib/llvm-project/libcxx/include/__algorithm/ranges_pop_heap.h @@ -0,0 +1,80 @@ +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef _LIBCPP___ALGORITHM_RANGES_POP_HEAP_H +#define _LIBCPP___ALGORITHM_RANGES_POP_HEAP_H + +#include <__algorithm/make_projected.h> +#include <__algorithm/pop_heap.h> +#include <__concepts/same_as.h> +#include <__config> +#include <__functional/identity.h> +#include <__functional/invoke.h> +#include <__functional/ranges_operations.h> +#include <__iterator/concepts.h> +#include <__iterator/iterator_traits.h> +#include <__iterator/next.h> +#include <__iterator/projected.h> +#include <__iterator/sortable.h> +#include <__ranges/access.h> +#include <__ranges/concepts.h> +#include <__ranges/dangling.h> +#include <__utility/forward.h> +#include <__utility/move.h> + +#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) +# pragma GCC system_header +#endif + +#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +_LIBCPP_BEGIN_NAMESPACE_STD + +namespace ranges { +namespace __pop_heap { + +struct __fn { + template + _LIBCPP_HIDE_FROM_ABI constexpr static + _Iter __pop_heap_fn_impl(_Iter __first, _Sent __last, _Comp& __comp, _Proj& __proj) { + auto __last_iter = ranges::next(__first, __last); + auto __len = __last_iter - __first; + + auto&& __projected_comp = ranges::__make_projected_comp(__comp, __proj); + std::__pop_heap(std::move(__first), __last_iter, __projected_comp, __len); + + return __last_iter; + } + + template _Sent, class _Comp = ranges::less, class _Proj = identity> + requires sortable<_Iter, _Comp, _Proj> + _LIBCPP_HIDE_FROM_ABI constexpr + _Iter operator()(_Iter __first, _Sent __last, _Comp __comp = {}, _Proj __proj = {}) const { + return __pop_heap_fn_impl(std::move(__first), std::move(__last), __comp, __proj); + } + + template + requires sortable, _Comp, _Proj> + _LIBCPP_HIDE_FROM_ABI constexpr + borrowed_iterator_t<_Range> operator()(_Range&& __r, _Comp __comp = {}, _Proj __proj = {}) const { + return __pop_heap_fn_impl(ranges::begin(__r), ranges::end(__r), __comp, __proj); + } +}; + +} // namespace __pop_heap + +inline namespace __cpo { + inline constexpr auto pop_heap = __pop_heap::__fn{}; +} // namespace __cpo +} // namespace ranges + +_LIBCPP_END_NAMESPACE_STD + +#endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +#endif // _LIBCPP___ALGORITHM_RANGES_POP_HEAP_H diff --git a/contrib/llvm-project/libcxx/include/__algorithm/ranges_push_heap.h b/contrib/llvm-project/libcxx/include/__algorithm/ranges_push_heap.h new file mode 100644 index 000000000000..e46ad19cfed7 --- /dev/null +++ b/contrib/llvm-project/libcxx/include/__algorithm/ranges_push_heap.h @@ -0,0 +1,79 @@ +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef _LIBCPP___ALGORITHM_RANGES_PUSH_HEAP_H +#define _LIBCPP___ALGORITHM_RANGES_PUSH_HEAP_H + +#include <__algorithm/make_projected.h> +#include <__algorithm/push_heap.h> +#include <__concepts/same_as.h> +#include <__config> +#include <__functional/identity.h> +#include <__functional/invoke.h> +#include <__functional/ranges_operations.h> +#include <__iterator/concepts.h> +#include <__iterator/iterator_traits.h> +#include <__iterator/next.h> +#include <__iterator/projected.h> +#include <__iterator/sortable.h> +#include <__ranges/access.h> +#include <__ranges/concepts.h> +#include <__ranges/dangling.h> +#include <__utility/forward.h> +#include <__utility/move.h> + +#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) +# pragma GCC system_header +#endif + +#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +_LIBCPP_BEGIN_NAMESPACE_STD + +namespace ranges { +namespace __push_heap { + +struct __fn { + template + _LIBCPP_HIDE_FROM_ABI constexpr static + _Iter __push_heap_fn_impl(_Iter __first, _Sent __last, _Comp& __comp, _Proj& __proj) { + auto __last_iter = ranges::next(__first, __last); + + auto&& __projected_comp = ranges::__make_projected_comp(__comp, __proj); + std::__push_heap(std::move(__first), __last_iter, __projected_comp); + + return __last_iter; + } + + template _Sent, class _Comp = ranges::less, class _Proj = identity> + requires sortable<_Iter, _Comp, _Proj> + _LIBCPP_HIDE_FROM_ABI constexpr + _Iter operator()(_Iter __first, _Sent __last, _Comp __comp = {}, _Proj __proj = {}) const { + return __push_heap_fn_impl(std::move(__first), std::move(__last), __comp, __proj); + } + + template + requires sortable, _Comp, _Proj> + _LIBCPP_HIDE_FROM_ABI constexpr + borrowed_iterator_t<_Range> operator()(_Range&& __r, _Comp __comp = {}, _Proj __proj = {}) const { + return __push_heap_fn_impl(ranges::begin(__r), ranges::end(__r), __comp, __proj); + } +}; + +} // namespace __push_heap + +inline namespace __cpo { + inline constexpr auto push_heap = __push_heap::__fn{}; +} // namespace __cpo +} // namespace ranges + +_LIBCPP_END_NAMESPACE_STD + +#endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +#endif // _LIBCPP___ALGORITHM_RANGES_PUSH_HEAP_H diff --git a/contrib/llvm-project/libcxx/include/__algorithm/ranges_remove.h b/contrib/llvm-project/libcxx/include/__algorithm/ranges_remove.h new file mode 100644 index 000000000000..a6a1200763d2 --- /dev/null +++ b/contrib/llvm-project/libcxx/include/__algorithm/ranges_remove.h @@ -0,0 +1,64 @@ +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef _LIBCPP___ALGORITHM_RANGES_REMOVE_H +#define _LIBCPP___ALGORITHM_RANGES_REMOVE_H +#include <__config> + +#include <__algorithm/ranges_remove_if.h> +#include <__functional/identity.h> +#include <__functional/ranges_operations.h> +#include <__iterator/concepts.h> +#include <__iterator/permutable.h> +#include <__iterator/projected.h> +#include <__ranges/access.h> +#include <__ranges/concepts.h> +#include <__ranges/subrange.h> +#include <__utility/move.h> + +#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) +# pragma GCC system_header +#endif + +#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +_LIBCPP_BEGIN_NAMESPACE_STD + +namespace ranges { +namespace __remove { +struct __fn { + + template _Sent, class _Type, class _Proj = identity> + requires indirect_binary_predicate, const _Type*> + _LIBCPP_HIDE_FROM_ABI constexpr + subrange<_Iter> operator()(_Iter __first, _Sent __last, const _Type& __value, _Proj __proj = {}) const { + auto __pred = [&](auto&& __other) { return __value == __other; }; + return ranges::__remove_if_impl(std::move(__first), std::move(__last), __pred, __proj); + } + + template + requires permutable> + && indirect_binary_predicate, _Proj>, const _Type*> + _LIBCPP_HIDE_FROM_ABI constexpr + borrowed_subrange_t<_Range> operator()(_Range&& __range, const _Type& __value, _Proj __proj = {}) const { + auto __pred = [&](auto&& __other) { return __value == __other; }; + return ranges::__remove_if_impl(ranges::begin(__range), ranges::end(__range), __pred, __proj); + } +}; +} // namespace __remove + +inline namespace __cpo { + inline constexpr auto remove = __remove::__fn{}; +} // namespace __cpo +} // namespace ranges + +_LIBCPP_END_NAMESPACE_STD + +#endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +#endif // _LIBCPP___ALGORITHM_RANGES_REMOVE_H diff --git a/contrib/llvm-project/libcxx/include/__algorithm/ranges_remove_copy.h b/contrib/llvm-project/libcxx/include/__algorithm/ranges_remove_copy.h new file mode 100644 index 000000000000..16e9009e7ef0 --- /dev/null +++ b/contrib/llvm-project/libcxx/include/__algorithm/ranges_remove_copy.h @@ -0,0 +1,81 @@ +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef _LIBCPP___ALGORITHM_RANGES_REMOVE_COPY_H +#define _LIBCPP___ALGORITHM_RANGES_REMOVE_COPY_H + +#include <__algorithm/in_out_result.h> +#include <__algorithm/make_projected.h> +#include <__algorithm/remove_copy.h> +#include <__config> +#include <__functional/identity.h> +#include <__functional/invoke.h> +#include <__functional/ranges_operations.h> +#include <__iterator/concepts.h> +#include <__iterator/iterator_traits.h> +#include <__iterator/projected.h> +#include <__ranges/access.h> +#include <__ranges/concepts.h> +#include <__ranges/dangling.h> +#include <__utility/forward.h> +#include <__utility/move.h> + +#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) +# pragma GCC system_header +#endif + +#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +_LIBCPP_BEGIN_NAMESPACE_STD + +namespace ranges { + +template +using remove_copy_result = in_out_result<_InIter, _OutIter>; + +namespace __remove_copy { + +struct __fn { + + template _Sent, weakly_incrementable _OutIter, class _Type, + class _Proj = identity> + requires indirectly_copyable<_InIter, _OutIter> && + indirect_binary_predicate, const _Type*> + _LIBCPP_HIDE_FROM_ABI constexpr + remove_copy_result<_InIter, _OutIter> + operator()(_InIter __first, _Sent __last, _OutIter __result, const _Type& __value, _Proj __proj = {}) const { + // TODO: implement + (void)__first; (void)__last; (void)__result; (void)__value; (void)__proj; + return {}; + } + + template + requires indirectly_copyable, _OutIter> && + indirect_binary_predicate, _Proj>, const _Type*> + _LIBCPP_HIDE_FROM_ABI constexpr + remove_copy_result, _OutIter> + operator()(_Range&& __range, _OutIter __result, const _Type& __value, _Proj __proj = {}) const { + // TODO: implement + (void)__range; (void)__result; (void)__value; (void)__proj; + return {}; + } + +}; + +} // namespace __remove_copy + +inline namespace __cpo { + inline constexpr auto remove_copy = __remove_copy::__fn{}; +} // namespace __cpo +} // namespace ranges + +_LIBCPP_END_NAMESPACE_STD + +#endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +#endif // _LIBCPP___ALGORITHM_RANGES_REMOVE_COPY_H diff --git a/contrib/llvm-project/libcxx/include/__algorithm/ranges_remove_copy_if.h b/contrib/llvm-project/libcxx/include/__algorithm/ranges_remove_copy_if.h new file mode 100644 index 000000000000..4eafe425b8e3 --- /dev/null +++ b/contrib/llvm-project/libcxx/include/__algorithm/ranges_remove_copy_if.h @@ -0,0 +1,80 @@ +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef _LIBCPP___ALGORITHM_RANGES_REMOVE_COPY_IF_H +#define _LIBCPP___ALGORITHM_RANGES_REMOVE_COPY_IF_H + +#include <__algorithm/in_out_result.h> +#include <__algorithm/make_projected.h> +#include <__algorithm/remove_copy_if.h> +#include <__config> +#include <__functional/identity.h> +#include <__functional/invoke.h> +#include <__functional/ranges_operations.h> +#include <__iterator/concepts.h> +#include <__iterator/iterator_traits.h> +#include <__iterator/projected.h> +#include <__ranges/access.h> +#include <__ranges/concepts.h> +#include <__ranges/dangling.h> +#include <__utility/forward.h> +#include <__utility/move.h> + +#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) +# pragma GCC system_header +#endif + +#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +_LIBCPP_BEGIN_NAMESPACE_STD + +namespace ranges { + +template +using remove_copy_if_result = in_out_result<_InIter, _OutIter>; + +namespace __remove_copy_if { + +struct __fn { + + template _Sent, weakly_incrementable _OutIter, + class _Proj = identity, indirect_unary_predicate> _Pred> + requires indirectly_copyable<_InIter, _OutIter> + _LIBCPP_HIDE_FROM_ABI constexpr + remove_copy_if_result<_InIter, _OutIter> + operator()(_InIter __first, _Sent __last, _OutIter __result, _Pred __pred, _Proj __proj = {}) const { + // TODO: implement + (void)__first; (void)__last; (void)__result; (void)__pred; (void)__proj; + return {}; + } + + template , _Proj>> _Pred> + requires indirectly_copyable, _OutIter> + _LIBCPP_HIDE_FROM_ABI constexpr + remove_copy_if_result, _OutIter> + operator()(_Range&& __range, _OutIter __result, _Pred __pred, _Proj __proj = {}) const { + // TODO: implement + (void)__range; (void)__result; (void)__pred; (void)__proj; + return {}; + } + +}; + +} // namespace __remove_copy_if + +inline namespace __cpo { + inline constexpr auto remove_copy_if = __remove_copy_if::__fn{}; +} // namespace __cpo +} // namespace ranges + +_LIBCPP_END_NAMESPACE_STD + +#endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +#endif // _LIBCPP___ALGORITHM_RANGES_REMOVE_COPY_IF_H diff --git a/contrib/llvm-project/libcxx/include/__algorithm/ranges_remove_if.h b/contrib/llvm-project/libcxx/include/__algorithm/ranges_remove_if.h new file mode 100644 index 000000000000..d4e382e551c6 --- /dev/null +++ b/contrib/llvm-project/libcxx/include/__algorithm/ranges_remove_if.h @@ -0,0 +1,85 @@ +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef _LIBCPP___ALGORITHM_RANGES_REMOVE_IF_H +#define _LIBCPP___ALGORITHM_RANGES_REMOVE_IF_H +#include <__config> + +#include <__algorithm/ranges_find_if.h> +#include <__functional/identity.h> +#include <__functional/invoke.h> +#include <__functional/ranges_operations.h> +#include <__iterator/concepts.h> +#include <__iterator/iter_move.h> +#include <__iterator/permutable.h> +#include <__iterator/projected.h> +#include <__ranges/access.h> +#include <__ranges/concepts.h> +#include <__ranges/subrange.h> +#include <__utility/move.h> + +#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) +# pragma GCC system_header +#endif + +#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +_LIBCPP_BEGIN_NAMESPACE_STD + +namespace ranges { + +template +_LIBCPP_HIDE_FROM_ABI constexpr +subrange<_Iter> __remove_if_impl(_Iter __first, _Sent __last, _Pred& __pred, _Proj& __proj) { + auto __new_end = ranges::__find_if_impl(__first, __last, __pred, __proj); + if (__new_end == __last) + return {__new_end, __new_end}; + + _Iter __i = __new_end; + while (++__i != __last) { + if (!std::invoke(__pred, std::invoke(__proj, *__i))) { + *__new_end = ranges::iter_move(__i); + ++__new_end; + } + } + return {__new_end, __i}; +} + +namespace __remove_if { +struct __fn { + + template _Sent, + class _Proj = identity, + indirect_unary_predicate> _Pred> + _LIBCPP_HIDE_FROM_ABI constexpr + subrange<_Iter> operator()(_Iter __first, _Sent __last, _Pred __pred, _Proj __proj = {}) const { + return ranges::__remove_if_impl(std::move(__first), std::move(__last), __pred, __proj); + } + + template , _Proj>> _Pred> + requires permutable> + _LIBCPP_HIDE_FROM_ABI constexpr + borrowed_subrange_t<_Range> operator()(_Range&& __range, _Pred __pred, _Proj __proj = {}) const { + return ranges::__remove_if_impl(ranges::begin(__range), ranges::end(__range), __pred, __proj); + } + +}; +} // namespace __remove_if + +inline namespace __cpo { + inline constexpr auto remove_if = __remove_if::__fn{}; +} // namespace __cpo +} // namespace ranges + +_LIBCPP_END_NAMESPACE_STD + +#endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +#endif // _LIBCPP___ALGORITHM_RANGES_REMOVE_IF_H diff --git a/contrib/llvm-project/libcxx/include/__algorithm/ranges_replace_copy.h b/contrib/llvm-project/libcxx/include/__algorithm/ranges_replace_copy.h new file mode 100644 index 000000000000..19ef635d6f15 --- /dev/null +++ b/contrib/llvm-project/libcxx/include/__algorithm/ranges_replace_copy.h @@ -0,0 +1,84 @@ +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef _LIBCPP___ALGORITHM_RANGES_REPLACE_COPY_H +#define _LIBCPP___ALGORITHM_RANGES_REPLACE_COPY_H + +#include <__algorithm/in_out_result.h> +#include <__algorithm/make_projected.h> +#include <__algorithm/replace_copy.h> +#include <__config> +#include <__functional/identity.h> +#include <__functional/invoke.h> +#include <__functional/ranges_operations.h> +#include <__iterator/concepts.h> +#include <__iterator/iterator_traits.h> +#include <__iterator/projected.h> +#include <__ranges/access.h> +#include <__ranges/concepts.h> +#include <__ranges/dangling.h> +#include <__utility/forward.h> +#include <__utility/move.h> + +#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) +# pragma GCC system_header +#endif + +#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +_LIBCPP_BEGIN_NAMESPACE_STD + +namespace ranges { + +template +using replace_copy_result = in_out_result<_InIter, _OutIter>; + +namespace __replace_copy { + +struct __fn { + + template _Sent, class _Type1, class _Type2, + output_iterator _OutIter, class _Proj = identity> + requires indirectly_copyable<_InIter, _OutIter> && + indirect_binary_predicate, const _Type1*> + _LIBCPP_HIDE_FROM_ABI constexpr + replace_copy_result<_InIter, _OutIter> + operator()(_InIter __first, _Sent __last, _OutIter __result, const _Type1& __old_value, const _Type2& __new_value, + _Proj __proj = {}) const { + // TODO: implement + (void)__first; (void)__last; (void)__result; (void)__old_value; (void)__new_value; (void)__proj; + return {}; + } + + template _OutIter, + class _Proj = identity> + requires indirectly_copyable, _OutIter> && + indirect_binary_predicate, _Proj>, const _Type1*> + _LIBCPP_HIDE_FROM_ABI constexpr + replace_copy_result, _OutIter> + operator()(_Range&& __range, _OutIter __result, const _Type1& __old_value, const _Type2& __new_value, + _Proj __proj = {}) const { + // TODO: implement + (void)__range; (void)__result; (void)__old_value; (void)__new_value; (void)__proj; + return {}; + } + +}; + +} // namespace __replace_copy + +inline namespace __cpo { + inline constexpr auto replace_copy = __replace_copy::__fn{}; +} // namespace __cpo +} // namespace ranges + +_LIBCPP_END_NAMESPACE_STD + +#endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +#endif // _LIBCPP___ALGORITHM_RANGES_REPLACE_COPY_H diff --git a/contrib/llvm-project/libcxx/include/__algorithm/ranges_replace_copy_if.h b/contrib/llvm-project/libcxx/include/__algorithm/ranges_replace_copy_if.h new file mode 100644 index 000000000000..2a908e2057af --- /dev/null +++ b/contrib/llvm-project/libcxx/include/__algorithm/ranges_replace_copy_if.h @@ -0,0 +1,81 @@ +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef _LIBCPP___ALGORITHM_RANGES_REPLACE_COPY_IF_H +#define _LIBCPP___ALGORITHM_RANGES_REPLACE_COPY_IF_H + +#include <__algorithm/in_out_result.h> +#include <__algorithm/make_projected.h> +#include <__algorithm/replace_copy_if.h> +#include <__config> +#include <__functional/identity.h> +#include <__functional/invoke.h> +#include <__functional/ranges_operations.h> +#include <__iterator/concepts.h> +#include <__iterator/iterator_traits.h> +#include <__iterator/projected.h> +#include <__ranges/access.h> +#include <__ranges/concepts.h> +#include <__ranges/dangling.h> +#include <__utility/forward.h> +#include <__utility/move.h> + +#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) +# pragma GCC system_header +#endif + +#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +_LIBCPP_BEGIN_NAMESPACE_STD + +namespace ranges { + +template +using replace_copy_if_result = in_out_result<_InIter, _OutIter>; + +namespace __replace_copy_if { + +struct __fn { + + template _Sent, class _Type, output_iterator _OutIter, + class _Proj = identity, indirect_unary_predicate> _Pred> + requires indirectly_copyable<_InIter, _OutIter> + _LIBCPP_HIDE_FROM_ABI constexpr + replace_copy_if_result<_InIter, _OutIter> + operator()(_InIter __first, _Sent __last, _OutIter __result, _Pred __pred, const _Type& __new_value, + _Proj __proj = {}) const { + // TODO: implement + (void)__first; (void)__last; (void)__result; (void)__pred; (void)__new_value; (void)__proj; + return {}; + } + + template _OutIter, class _Proj = identity, + indirect_unary_predicate, _Proj>> _Pred> + requires indirectly_copyable, _OutIter> + _LIBCPP_HIDE_FROM_ABI constexpr + replace_copy_if_result, _OutIter> + operator()(_Range&& __range, _OutIter __result, _Pred __pred, const _Type& __new_value, _Proj __proj = {}) const { + // TODO: implement + (void)__range; (void)__result; (void)__pred; (void)__new_value; (void)__proj; + return {}; + } + +}; + +} // namespace __replace_copy_if + +inline namespace __cpo { + inline constexpr auto replace_copy_if = __replace_copy_if::__fn{}; +} // namespace __cpo +} // namespace ranges + +_LIBCPP_END_NAMESPACE_STD + +#endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +#endif // _LIBCPP___ALGORITHM_RANGES_REPLACE_COPY_IF_H diff --git a/contrib/llvm-project/libcxx/include/__algorithm/ranges_reverse_copy.h b/contrib/llvm-project/libcxx/include/__algorithm/ranges_reverse_copy.h new file mode 100644 index 000000000000..e2da9b484aaf --- /dev/null +++ b/contrib/llvm-project/libcxx/include/__algorithm/ranges_reverse_copy.h @@ -0,0 +1,67 @@ +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef _LIBCPP___ALGORITHM_RANGES_REVERSE_COPY_H +#define _LIBCPP___ALGORITHM_RANGES_REVERSE_COPY_H + +#include <__algorithm/in_out_result.h> +#include <__algorithm/ranges_copy.h> +#include <__config> +#include <__iterator/concepts.h> +#include <__iterator/next.h> +#include <__iterator/reverse_iterator.h> +#include <__ranges/access.h> +#include <__ranges/concepts.h> +#include <__ranges/dangling.h> +#include <__ranges/subrange.h> +#include <__utility/move.h> + +#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) +# pragma GCC system_header +#endif + +#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +_LIBCPP_BEGIN_NAMESPACE_STD + +namespace ranges { + +template +using reverse_copy_result = in_out_result<_InIter, _OutIter>; + +namespace __reverse_copy { +struct __fn { + + template _Sent, weakly_incrementable _OutIter> + requires indirectly_copyable<_InIter, _OutIter> + _LIBCPP_HIDE_FROM_ABI constexpr + reverse_copy_result<_InIter, _OutIter> operator()(_InIter __first, _Sent __last, _OutIter __result) const { + return (*this)(subrange(std::move(__first), std::move(__last)), std::move(__result)); + } + + template + requires indirectly_copyable, _OutIter> + _LIBCPP_HIDE_FROM_ABI constexpr + reverse_copy_result, _OutIter> operator()(_Range&& __range, _OutIter __result) const { + auto __ret = ranges::copy(std::__reverse_range(__range), std::move(__result)); + return {ranges::next(ranges::begin(__range), ranges::end(__range)), std::move(__ret.out)}; + } + +}; +} // namespace __reverse_copy + +inline namespace __cpo { + inline constexpr auto reverse_copy = __reverse_copy::__fn{}; +} // namespace __cpo +} // namespace ranges + +_LIBCPP_END_NAMESPACE_STD + +#endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +#endif // _LIBCPP___ALGORITHM_RANGES_REVERSE_COPY_H diff --git a/contrib/llvm-project/libcxx/include/__algorithm/ranges_rotate_copy.h b/contrib/llvm-project/libcxx/include/__algorithm/ranges_rotate_copy.h new file mode 100644 index 000000000000..d7a282c86750 --- /dev/null +++ b/contrib/llvm-project/libcxx/include/__algorithm/ranges_rotate_copy.h @@ -0,0 +1,68 @@ +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef _LIBCPP___ALGORITHM_RANGES_ROTATE_COPY_H +#define _LIBCPP___ALGORITHM_RANGES_ROTATE_COPY_H + +#include <__algorithm/in_out_result.h> +#include <__algorithm/ranges_copy.h> +#include <__config> +#include <__iterator/concepts.h> +#include <__iterator/reverse_iterator.h> +#include <__ranges/access.h> +#include <__ranges/concepts.h> +#include <__ranges/dangling.h> +#include <__utility/move.h> + +#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) +# pragma GCC system_header +#endif + +#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +_LIBCPP_BEGIN_NAMESPACE_STD + +namespace ranges { + +template +using rotate_copy_result = in_out_result<_InIter, _OutIter>; + +namespace __rotate_copy { +struct __fn { + + template _Sent, weakly_incrementable _OutIter> + requires indirectly_copyable<_InIter, _OutIter> + _LIBCPP_HIDE_FROM_ABI constexpr + rotate_copy_result<_InIter, _OutIter> + operator()(_InIter __first, _InIter __middle, _Sent __last, _OutIter __result) const { + auto __res1 = ranges::copy(__middle, __last, std::move(__result)); + auto __res2 = ranges::copy(__first, __middle, std::move(__res1.out)); + return {std::move(__res1.in), std::move(__res2.out)}; + } + + template + requires indirectly_copyable, _OutIter> + _LIBCPP_HIDE_FROM_ABI constexpr + rotate_copy_result, _OutIter> + operator()(_Range&& __range, iterator_t<_Range> __middle, _OutIter __result) const { + return (*this)(ranges::begin(__range), std::move(__middle), ranges::end(__range), std::move(__result)); + } + +}; +} // namespace __rotate_copy + +inline namespace __cpo { + inline constexpr auto rotate_copy = __rotate_copy::__fn{}; +} // namespace __cpo +} // namespace ranges + +_LIBCPP_END_NAMESPACE_STD + +#endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +#endif // _LIBCPP___ALGORITHM_RANGES_ROTATE_COPY_H diff --git a/contrib/llvm-project/libcxx/include/__algorithm/ranges_search.h b/contrib/llvm-project/libcxx/include/__algorithm/ranges_search.h new file mode 100644 index 000000000000..0564bbe1f8b3 --- /dev/null +++ b/contrib/llvm-project/libcxx/include/__algorithm/ranges_search.h @@ -0,0 +1,134 @@ +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef _LIBCPP___ALGORITHM_RANGES_SEARCH_H +#define _LIBCPP___ALGORITHM_RANGES_SEARCH_H + +#include <__algorithm/iterator_operations.h> +#include <__algorithm/search.h> +#include <__config> +#include <__functional/identity.h> +#include <__functional/ranges_operations.h> +#include <__iterator/advance.h> +#include <__iterator/concepts.h> +#include <__iterator/distance.h> +#include <__iterator/indirectly_comparable.h> +#include <__ranges/access.h> +#include <__ranges/concepts.h> +#include <__ranges/size.h> +#include <__ranges/subrange.h> + +#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) +# pragma GCC system_header +#endif + +#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +_LIBCPP_BEGIN_NAMESPACE_STD + +namespace ranges { +namespace __search { +struct __fn { + template + _LIBCPP_HIDE_FROM_ABI static constexpr subrange<_Iter1> __ranges_search_impl( + _Iter1 __first1, + _Sent1 __last1, + _Iter2 __first2, + _Sent2 __last2, + _Pred& __pred, + _Proj1& __proj1, + _Proj2& __proj2) { + if constexpr (sized_sentinel_for<_Sent2, _Iter2>) { + auto __size2 = ranges::distance(__first2, __last2); + if (__size2 == 0) + return {__first1, __first1}; + + if constexpr (sized_sentinel_for<_Sent1, _Iter1>) { + auto __size1 = ranges::distance(__first1, __last1); + if (__size1 < __size2) { + ranges::advance(__first1, __last1); + return {__first1, __first1}; + } + + if constexpr (random_access_iterator<_Iter1> && random_access_iterator<_Iter2>) { + auto __ret = std::__search_random_access_impl<_RangeAlgPolicy>( + __first1, __last1, __first2, __last2, __pred, __proj1, __proj2, __size1, __size2); + return {__ret.first, __ret.second}; + } + } + } + + auto __ret = + std::__search_forward_impl<_RangeAlgPolicy>(__first1, __last1, __first2, __last2, __pred, __proj1, __proj2); + return {__ret.first, __ret.second}; + } + + template _Sent1, + forward_iterator _Iter2, sentinel_for<_Iter2> _Sent2, + class _Pred = ranges::equal_to, + class _Proj1 = identity, + class _Proj2 = identity> + requires indirectly_comparable<_Iter1, _Iter2, _Pred, _Proj1, _Proj2> + _LIBCPP_HIDE_FROM_ABI constexpr + subrange<_Iter1> operator()(_Iter1 __first1, _Sent1 __last1, + _Iter2 __first2, _Sent2 __last2, + _Pred __pred = {}, + _Proj1 __proj1 = {}, + _Proj2 __proj2 = {}) const { + return __ranges_search_impl(__first1, __last1, __first2, __last2, __pred, __proj1, __proj2); + } + + template + requires indirectly_comparable, iterator_t<_Range2>, _Pred, _Proj1, _Proj2> + _LIBCPP_HIDE_FROM_ABI constexpr + borrowed_subrange_t<_Range1> operator()(_Range1&& __range1, + _Range2&& __range2, + _Pred __pred = {}, + _Proj1 __proj1 = {}, + _Proj2 __proj2 = {}) const { + auto __first1 = ranges::begin(__range1); + if constexpr (sized_range<_Range2>) { + auto __size2 = ranges::size(__range2); + if (__size2 == 0) + return {__first1, __first1}; + if constexpr (sized_range<_Range1>) { + auto __size1 = ranges::size(__range1); + if (__size1 < __size2) { + ranges::advance(__first1, ranges::end(__range1)); + return {__first1, __first1}; + } + } + } + + return __ranges_search_impl( + ranges::begin(__range1), + ranges::end(__range1), + ranges::begin(__range2), + ranges::end(__range2), + __pred, + __proj1, + __proj2); + } + +}; +} // namespace __search + +inline namespace __cpo { + inline constexpr auto search = __search::__fn{}; +} // namespace __cpo +} // namespace ranges + +_LIBCPP_END_NAMESPACE_STD + +#endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +#endif // _LIBCPP___ALGORITHM_RANGES_SEARCH_H diff --git a/contrib/llvm-project/libcxx/include/__algorithm/ranges_search_n.h b/contrib/llvm-project/libcxx/include/__algorithm/ranges_search_n.h new file mode 100644 index 000000000000..29fdbfb1c725 --- /dev/null +++ b/contrib/llvm-project/libcxx/include/__algorithm/ranges_search_n.h @@ -0,0 +1,120 @@ +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef _LIBCPP___ALGORITHM_RANGES_SEARCH_N_H +#define _LIBCPP___ALGORITHM_RANGES_SEARCH_N_H + +#include <__algorithm/iterator_operations.h> +#include <__algorithm/search_n.h> +#include <__config> +#include <__functional/identity.h> +#include <__functional/ranges_operations.h> +#include <__iterator/advance.h> +#include <__iterator/concepts.h> +#include <__iterator/distance.h> +#include <__iterator/incrementable_traits.h> +#include <__iterator/indirectly_comparable.h> +#include <__iterator/iterator_traits.h> +#include <__ranges/access.h> +#include <__ranges/concepts.h> +#include <__ranges/size.h> +#include <__ranges/subrange.h> +#include <__utility/move.h> + +#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) +# pragma GCC system_header +#endif + +#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +_LIBCPP_BEGIN_NAMESPACE_STD + +namespace ranges { +namespace __search_n { +struct __fn { + + template + _LIBCPP_HIDE_FROM_ABI static constexpr subrange<_Iter1> __ranges_search_n_impl( + _Iter1 __first, _Sent1 __last, _SizeT __count, const _Type& __value, _Pred& __pred, _Proj& __proj) { + if (__count == 0) + return {__first, __first}; + + if constexpr (sized_sentinel_for<_Sent1, _Iter1>) { + auto __size = ranges::distance(__first, __last); + if (__size < __count) { + ranges::advance(__first, __last); + return {__first, __first}; + } + + if constexpr (random_access_iterator<_Iter1>) { + auto __ret = __search_n_random_access_impl<_RangeAlgPolicy>(__first, __last, + __count, + __value, + __pred, + __proj, + __size); + return {std::move(__ret.first), std::move(__ret.second)}; + } + } + + auto __ret = std::__search_n_forward_impl<_RangeAlgPolicy>(__first, __last, + __count, + __value, + __pred, + __proj); + return {std::move(__ret.first), std::move(__ret.second)}; + } + + template _Sent, + class _Type, + class _Pred = ranges::equal_to, + class _Proj = identity> + requires indirectly_comparable<_Iter, const _Type*, _Pred, _Proj> + _LIBCPP_HIDE_FROM_ABI constexpr + subrange<_Iter> operator()(_Iter __first, _Sent __last, + iter_difference_t<_Iter> __count, + const _Type& __value, + _Pred __pred = {}, + _Proj __proj = _Proj{}) const { + return __ranges_search_n_impl(__first, __last, __count, __value, __pred, __proj); + } + + template + requires indirectly_comparable, const _Type*, _Pred, _Proj> + _LIBCPP_HIDE_FROM_ABI constexpr + borrowed_subrange_t<_Range> operator()(_Range&& __range, + range_difference_t<_Range> __count, + const _Type& __value, + _Pred __pred = {}, + _Proj __proj = {}) const { + auto __first = ranges::begin(__range); + if (__count <= 0) + return {__first, __first}; + if constexpr (sized_range<_Range>) { + auto __size1 = ranges::size(__range); + if (__size1 < static_cast>(__count)) { + ranges::advance(__first, ranges::end(__range)); + return {__first, __first}; + } + } + + return __ranges_search_n_impl(ranges::begin(__range), ranges::end(__range), __count, __value, __pred, __proj); + } +}; +} // namespace __search_n + +inline namespace __cpo { + inline constexpr auto search_n = __search_n::__fn{}; +} // namespace __cpo +} // namespace ranges + +_LIBCPP_END_NAMESPACE_STD + +#endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +#endif // _LIBCPP___ALGORITHM_RANGES_SEARCH_N_H diff --git a/contrib/llvm-project/libcxx/include/__algorithm/ranges_set_difference.h b/contrib/llvm-project/libcxx/include/__algorithm/ranges_set_difference.h new file mode 100644 index 000000000000..4eb3efad3895 --- /dev/null +++ b/contrib/llvm-project/libcxx/include/__algorithm/ranges_set_difference.h @@ -0,0 +1,104 @@ +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef _LIBCPP___ALGORITHM_RANGES_SET_DIFFERENCE_H +#define _LIBCPP___ALGORITHM_RANGES_SET_DIFFERENCE_H + +#include <__algorithm/in_out_result.h> +#include <__algorithm/make_projected.h> +#include <__algorithm/set_difference.h> +#include <__config> +#include <__functional/identity.h> +#include <__functional/invoke.h> +#include <__functional/ranges_operations.h> +#include <__iterator/concepts.h> +#include <__iterator/mergeable.h> +#include <__ranges/access.h> +#include <__ranges/concepts.h> +#include <__ranges/dangling.h> +#include <__type_traits/decay.h> +#include <__utility/move.h> + +#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) +# pragma GCC system_header +#endif + +#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +_LIBCPP_BEGIN_NAMESPACE_STD + +namespace ranges { + +template +using set_difference_result = in_out_result<_InIter, _OutIter>; + +namespace __set_difference { + +struct __fn { + template < + input_iterator _InIter1, + sentinel_for<_InIter1> _Sent1, + input_iterator _InIter2, + sentinel_for<_InIter2> _Sent2, + weakly_incrementable _OutIter, + class _Comp = less, + class _Proj1 = identity, + class _Proj2 = identity> + requires mergeable<_InIter1, _InIter2, _OutIter, _Comp, _Proj1, _Proj2> + _LIBCPP_HIDE_FROM_ABI constexpr set_difference_result<_InIter1, _OutIter> operator()( + _InIter1 __first1, + _Sent1 __last1, + _InIter2 __first2, + _Sent2 __last2, + _OutIter __result, + _Comp __comp = {}, + _Proj1 __proj1 = {}, + _Proj2 __proj2 = {}) const { + auto __ret = std::__set_difference( + __first1, __last1, __first2, __last2, __result, ranges::__make_projected_comp(__comp, __proj1, __proj2)); + return {std::move(__ret.first), std::move(__ret.second)}; + } + + template < + input_range _Range1, + input_range _Range2, + weakly_incrementable _OutIter, + class _Comp = less, + class _Proj1 = identity, + class _Proj2 = identity> + requires mergeable, iterator_t<_Range2>, _OutIter, _Comp, _Proj1, _Proj2> + _LIBCPP_HIDE_FROM_ABI constexpr set_difference_result, _OutIter> + operator()( + _Range1&& __range1, + _Range2&& __range2, + _OutIter __result, + _Comp __comp = {}, + _Proj1 __proj1 = {}, + _Proj2 __proj2 = {}) const { + auto __ret = std::__set_difference( + ranges::begin(__range1), + ranges::end(__range1), + ranges::begin(__range2), + ranges::end(__range2), + __result, + ranges::__make_projected_comp(__comp, __proj1, __proj2)); + return {std::move(__ret.first), std::move(__ret.second)}; + } +}; + +} // namespace __set_difference + +inline namespace __cpo { + inline constexpr auto set_difference = __set_difference::__fn{}; +} // namespace __cpo +} // namespace ranges + +_LIBCPP_END_NAMESPACE_STD + +#endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) +#endif // _LIBCPP___ALGORITHM_RANGES_SET_DIFFERENCE_H diff --git a/contrib/llvm-project/libcxx/include/__algorithm/ranges_set_intersection.h b/contrib/llvm-project/libcxx/include/__algorithm/ranges_set_intersection.h new file mode 100644 index 000000000000..05af91ae29e5 --- /dev/null +++ b/contrib/llvm-project/libcxx/include/__algorithm/ranges_set_intersection.h @@ -0,0 +1,117 @@ +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef _LIBCPP___ALGORITHM_RANGES_SET_INTERSECTION_H +#define _LIBCPP___ALGORITHM_RANGES_SET_INTERSECTION_H + +#include <__algorithm/in_in_out_result.h> +#include <__algorithm/iterator_operations.h> +#include <__algorithm/make_projected.h> +#include <__algorithm/set_intersection.h> +#include <__config> +#include <__functional/identity.h> +#include <__functional/invoke.h> +#include <__functional/ranges_operations.h> +#include <__iterator/concepts.h> +#include <__iterator/mergeable.h> +#include <__ranges/access.h> +#include <__ranges/concepts.h> +#include <__ranges/dangling.h> +#include <__utility/move.h> + +#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) +# pragma GCC system_header +#endif + +#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +_LIBCPP_BEGIN_NAMESPACE_STD + +namespace ranges { + +template +using set_intersection_result = in_in_out_result<_InIter1, _InIter2, _OutIter>; + +namespace __set_intersection { + +struct __fn { + template < + input_iterator _InIter1, + sentinel_for<_InIter1> _Sent1, + input_iterator _InIter2, + sentinel_for<_InIter2> _Sent2, + weakly_incrementable _OutIter, + class _Comp = less, + class _Proj1 = identity, + class _Proj2 = identity> + requires mergeable<_InIter1, _InIter2, _OutIter, _Comp, _Proj1, _Proj2> + _LIBCPP_HIDE_FROM_ABI constexpr set_intersection_result<_InIter1, _InIter2, _OutIter> operator()( + _InIter1 __first1, + _Sent1 __last1, + _InIter2 __first2, + _Sent2 __last2, + _OutIter __result, + _Comp __comp = {}, + _Proj1 __proj1 = {}, + _Proj2 __proj2 = {}) const { + auto __ret = std::__set_intersection<_RangeAlgPolicy>( + std::move(__first1), + std::move(__last1), + std::move(__first2), + std::move(__last2), + std::move(__result), + ranges::__make_projected_comp(__comp, __proj1, __proj2)); + return {std::move(__ret.__in1_), std::move(__ret.__in2_), std::move(__ret.__out_)}; + } + + template < + input_range _Range1, + input_range _Range2, + weakly_incrementable _OutIter, + class _Comp = less, + class _Proj1 = identity, + class _Proj2 = identity> + requires mergeable< + iterator_t<_Range1>, + iterator_t<_Range2>, + _OutIter, + _Comp, + _Proj1, + _Proj2> + _LIBCPP_HIDE_FROM_ABI constexpr set_intersection_result, + borrowed_iterator_t<_Range2>, + _OutIter> + operator()( + _Range1&& __range1, + _Range2&& __range2, + _OutIter __result, + _Comp __comp = {}, + _Proj1 __proj1 = {}, + _Proj2 __proj2 = {}) const { + auto __ret = std::__set_intersection<_RangeAlgPolicy>( + ranges::begin(__range1), + ranges::end(__range1), + ranges::begin(__range2), + ranges::end(__range2), + std::move(__result), + ranges::__make_projected_comp(__comp, __proj1, __proj2)); + return {std::move(__ret.__in1_), std::move(__ret.__in2_), std::move(__ret.__out_)}; + } +}; + +} // namespace __set_intersection + +inline namespace __cpo { + inline constexpr auto set_intersection = __set_intersection::__fn{}; +} // namespace __cpo +} // namespace ranges + +_LIBCPP_END_NAMESPACE_STD + +#endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) +#endif // _LIBCPP___ALGORITHM_RANGES_SET_INTERSECTION_H diff --git a/contrib/llvm-project/libcxx/include/__algorithm/ranges_set_symmetric_difference.h b/contrib/llvm-project/libcxx/include/__algorithm/ranges_set_symmetric_difference.h new file mode 100644 index 000000000000..c54cf3a65112 --- /dev/null +++ b/contrib/llvm-project/libcxx/include/__algorithm/ranges_set_symmetric_difference.h @@ -0,0 +1,116 @@ +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef _LIBCPP___ALGORITHM_RANGES_SET_SYMMETRIC_DIFFERENCE_H +#define _LIBCPP___ALGORITHM_RANGES_SET_SYMMETRIC_DIFFERENCE_H + +#include <__algorithm/in_in_out_result.h> +#include <__algorithm/make_projected.h> +#include <__algorithm/set_symmetric_difference.h> +#include <__config> +#include <__functional/identity.h> +#include <__functional/invoke.h> +#include <__functional/ranges_operations.h> +#include <__iterator/concepts.h> +#include <__iterator/mergeable.h> +#include <__ranges/access.h> +#include <__ranges/concepts.h> +#include <__ranges/dangling.h> +#include <__utility/move.h> + +#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) +# pragma GCC system_header +#endif + +#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +_LIBCPP_BEGIN_NAMESPACE_STD + +namespace ranges { + +template +using set_symmetric_difference_result = in_in_out_result<_InIter1, _InIter2, _OutIter>; + +namespace __set_symmetric_difference { + +struct __fn { + template < + input_iterator _InIter1, + sentinel_for<_InIter1> _Sent1, + input_iterator _InIter2, + sentinel_for<_InIter2> _Sent2, + weakly_incrementable _OutIter, + class _Comp = ranges::less, + class _Proj1 = identity, + class _Proj2 = identity> + requires mergeable<_InIter1, _InIter2, _OutIter, _Comp, _Proj1, _Proj2> + _LIBCPP_HIDE_FROM_ABI constexpr set_symmetric_difference_result<_InIter1, _InIter2, _OutIter> operator()( + _InIter1 __first1, + _Sent1 __last1, + _InIter2 __first2, + _Sent2 __last2, + _OutIter __result, + _Comp __comp = {}, + _Proj1 __proj1 = {}, + _Proj2 __proj2 = {}) const { + auto __ret = std::__set_symmetric_difference( + std::move(__first1), + std::move(__last1), + std::move(__first2), + std::move(__last2), + std::move(__result), + ranges::__make_projected_comp(__comp, __proj1, __proj2)); + return {std::move(__ret.__in1_), std::move(__ret.__in2_), std::move(__ret.__out_)}; + } + + template < + input_range _Range1, + input_range _Range2, + weakly_incrementable _OutIter, + class _Comp = ranges::less, + class _Proj1 = identity, + class _Proj2 = identity> + requires mergeable< + iterator_t<_Range1>, + iterator_t<_Range2>, + _OutIter, + _Comp, + _Proj1, + _Proj2> + _LIBCPP_HIDE_FROM_ABI constexpr set_symmetric_difference_result, + borrowed_iterator_t<_Range2>, + _OutIter> + operator()( + _Range1&& __range1, + _Range2&& __range2, + _OutIter __result, + _Comp __comp = {}, + _Proj1 __proj1 = {}, + _Proj2 __proj2 = {}) const { + auto __ret = std::__set_symmetric_difference( + ranges::begin(__range1), + ranges::end(__range1), + ranges::begin(__range2), + ranges::end(__range2), + std::move(__result), + ranges::__make_projected_comp(__comp, __proj1, __proj2)); + return {std::move(__ret.__in1_), std::move(__ret.__in2_), std::move(__ret.__out_)}; + } +}; + +} // namespace __set_symmetric_difference + +inline namespace __cpo { + inline constexpr auto set_symmetric_difference = __set_symmetric_difference::__fn{}; +} // namespace __cpo +} // namespace ranges + +_LIBCPP_END_NAMESPACE_STD + +#endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) +#endif // _LIBCPP___ALGORITHM_RANGES_SET_SYMMETRIC_DIFFERENCE_H diff --git a/contrib/llvm-project/libcxx/include/__algorithm/ranges_set_union.h b/contrib/llvm-project/libcxx/include/__algorithm/ranges_set_union.h new file mode 100644 index 000000000000..39537503b98f --- /dev/null +++ b/contrib/llvm-project/libcxx/include/__algorithm/ranges_set_union.h @@ -0,0 +1,86 @@ +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef _LIBCPP___ALGORITHM_RANGES_SET_UNION_H +#define _LIBCPP___ALGORITHM_RANGES_SET_UNION_H + +#include <__algorithm/in_in_out_result.h> +#include <__algorithm/make_projected.h> +#include <__algorithm/set_union.h> +#include <__config> +#include <__functional/identity.h> +#include <__functional/invoke.h> +#include <__functional/ranges_operations.h> +#include <__iterator/concepts.h> +#include <__iterator/iterator_traits.h> +#include <__iterator/mergeable.h> +#include <__iterator/projected.h> +#include <__ranges/access.h> +#include <__ranges/concepts.h> +#include <__ranges/dangling.h> +#include <__utility/forward.h> +#include <__utility/move.h> + +#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) +# pragma GCC system_header +#endif + +#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +_LIBCPP_BEGIN_NAMESPACE_STD + +namespace ranges { + +template +using set_union_result = in_in_out_result<_InIter1, _InIter2, _OutIter>; + +namespace __set_union { + +struct __fn { + + template _Sent1, + input_iterator _InIter2, sentinel_for<_InIter2> _Sent2, + weakly_incrementable _OutIter, class _Comp = ranges::less, + class _Proj1 = identity, class _Proj2 = identity> + requires mergeable<_InIter1, _InIter2, _OutIter, _Comp, _Proj1, _Proj2> + _LIBCPP_HIDE_FROM_ABI constexpr + set_union_result<_InIter1, _InIter2, _OutIter> + operator()(_InIter1 __first1, _Sent1 __last1, _InIter2 __first2, _Sent2 __last2, _OutIter __result, _Comp __comp = {}, + _Proj1 __proj1 = {}, _Proj2 __proj2 = {}) const { + // TODO: implement + (void)__first1; (void)__last1; (void)__first2; (void)__last2; (void)__result; (void)__comp; (void)__proj1; + (void)__proj2; + return {}; + } + + template + requires mergeable, iterator_t<_Range2>, _OutIter, _Comp, _Proj1, _Proj2> + _LIBCPP_HIDE_FROM_ABI constexpr + set_union_result, borrowed_iterator_t<_Range2>, _OutIter> + operator()(_Range1&& __range1, _Range2&& __range2, _OutIter __result, _Comp __comp = {}, + _Proj1 __proj1 = {}, _Proj2 __proj2 = {}) const { + // TODO: implement + (void)__range1; (void)__range2; (void)__result; (void)__comp; (void)__proj1; (void)__proj2; + return {}; + } + +}; + +} // namespace __set_union + +inline namespace __cpo { + inline constexpr auto set_union = __set_union::__fn{}; +} // namespace __cpo +} // namespace ranges + +_LIBCPP_END_NAMESPACE_STD + +#endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +#endif // _LIBCPP___ALGORITHM_RANGES_SET_UNION_H diff --git a/contrib/llvm-project/libcxx/include/__algorithm/ranges_shuffle.h b/contrib/llvm-project/libcxx/include/__algorithm/ranges_shuffle.h new file mode 100644 index 000000000000..bf9c28b4ce26 --- /dev/null +++ b/contrib/llvm-project/libcxx/include/__algorithm/ranges_shuffle.h @@ -0,0 +1,74 @@ +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef _LIBCPP___ALGORITHM_RANGES_SHUFFLE_H +#define _LIBCPP___ALGORITHM_RANGES_SHUFFLE_H + +#include <__algorithm/make_projected.h> +#include <__algorithm/shuffle.h> +#include <__config> +#include <__functional/identity.h> +#include <__functional/invoke.h> +#include <__functional/ranges_operations.h> +#include <__iterator/concepts.h> +#include <__iterator/iterator_traits.h> +#include <__iterator/permutable.h> +#include <__iterator/projected.h> +#include <__random/uniform_random_bit_generator.h> +#include <__ranges/access.h> +#include <__ranges/concepts.h> +#include <__ranges/dangling.h> +#include <__type_traits/remove_reference.h> +#include <__utility/forward.h> +#include <__utility/move.h> + +#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) +# pragma GCC system_header +#endif + +#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +_LIBCPP_BEGIN_NAMESPACE_STD + +namespace ranges { +namespace __shuffle { + +struct __fn { + + template _Sent, class _Gen> + requires permutable<_Iter> && uniform_random_bit_generator> + _LIBCPP_HIDE_FROM_ABI + _Iter operator()(_Iter __first, _Sent __last, _Gen&& __gen) const { + // TODO: implement + (void)__first; (void)__last; (void)__gen; + return {}; + } + + template + requires permutable> && uniform_random_bit_generator> + _LIBCPP_HIDE_FROM_ABI + borrowed_iterator_t<_Range> operator()(_Range&& __range, _Gen&& __gen) const { + // TODO: implement + (void)__range; (void)__gen; + return {}; + } + +}; + +} // namespace __shuffle + +inline namespace __cpo { + inline constexpr auto shuffle = __shuffle::__fn{}; +} // namespace __cpo +} // namespace ranges + +_LIBCPP_END_NAMESPACE_STD + +#endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +#endif // _LIBCPP___ALGORITHM_RANGES_SHUFFLE_H diff --git a/contrib/llvm-project/libcxx/include/__algorithm/ranges_sort_heap.h b/contrib/llvm-project/libcxx/include/__algorithm/ranges_sort_heap.h new file mode 100644 index 000000000000..c753e20c44a6 --- /dev/null +++ b/contrib/llvm-project/libcxx/include/__algorithm/ranges_sort_heap.h @@ -0,0 +1,79 @@ +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef _LIBCPP___ALGORITHM_RANGES_SORT_HEAP_H +#define _LIBCPP___ALGORITHM_RANGES_SORT_HEAP_H + +#include <__algorithm/make_projected.h> +#include <__algorithm/sort_heap.h> +#include <__concepts/same_as.h> +#include <__config> +#include <__functional/identity.h> +#include <__functional/invoke.h> +#include <__functional/ranges_operations.h> +#include <__iterator/concepts.h> +#include <__iterator/iterator_traits.h> +#include <__iterator/next.h> +#include <__iterator/projected.h> +#include <__iterator/sortable.h> +#include <__ranges/access.h> +#include <__ranges/concepts.h> +#include <__ranges/dangling.h> +#include <__utility/forward.h> +#include <__utility/move.h> + +#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) +# pragma GCC system_header +#endif + +#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +_LIBCPP_BEGIN_NAMESPACE_STD + +namespace ranges { +namespace __sort_heap { + +struct __fn { + template + _LIBCPP_HIDE_FROM_ABI constexpr static + _Iter __sort_heap_fn_impl(_Iter __first, _Sent __last, _Comp& __comp, _Proj& __proj) { + auto __last_iter = ranges::next(__first, __last); + + auto&& __projected_comp = ranges::__make_projected_comp(__comp, __proj); + std::__sort_heap(std::move(__first), __last_iter, __projected_comp); + + return __last_iter; + } + + template _Sent, class _Comp = ranges::less, class _Proj = identity> + requires sortable<_Iter, _Comp, _Proj> + _LIBCPP_HIDE_FROM_ABI constexpr + _Iter operator()(_Iter __first, _Sent __last, _Comp __comp = {}, _Proj __proj = {}) const { + return __sort_heap_fn_impl(std::move(__first), std::move(__last), __comp, __proj); + } + + template + requires sortable, _Comp, _Proj> + _LIBCPP_HIDE_FROM_ABI constexpr + borrowed_iterator_t<_Range> operator()(_Range&& __r, _Comp __comp = {}, _Proj __proj = {}) const { + return __sort_heap_fn_impl(ranges::begin(__r), ranges::end(__r), __comp, __proj); + } +}; + +} // namespace __sort_heap + +inline namespace __cpo { + inline constexpr auto sort_heap = __sort_heap::__fn{}; +} // namespace __cpo +} // namespace ranges + +_LIBCPP_END_NAMESPACE_STD + +#endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +#endif // _LIBCPP___ALGORITHM_RANGES_SORT_HEAP_H diff --git a/contrib/llvm-project/libcxx/include/__algorithm/ranges_stable_partition.h b/contrib/llvm-project/libcxx/include/__algorithm/ranges_stable_partition.h new file mode 100644 index 000000000000..178c953ebdae --- /dev/null +++ b/contrib/llvm-project/libcxx/include/__algorithm/ranges_stable_partition.h @@ -0,0 +1,75 @@ +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef _LIBCPP___ALGORITHM_RANGES_STABLE_PARTITION_H +#define _LIBCPP___ALGORITHM_RANGES_STABLE_PARTITION_H + +#include <__algorithm/make_projected.h> +#include <__algorithm/stable_partition.h> +#include <__config> +#include <__functional/identity.h> +#include <__functional/invoke.h> +#include <__functional/ranges_operations.h> +#include <__iterator/concepts.h> +#include <__iterator/iterator_traits.h> +#include <__iterator/permutable.h> +#include <__iterator/projected.h> +#include <__ranges/access.h> +#include <__ranges/concepts.h> +#include <__ranges/dangling.h> +#include <__ranges/subrange.h> +#include <__utility/forward.h> +#include <__utility/move.h> + +#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) +# pragma GCC system_header +#endif + +#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +_LIBCPP_BEGIN_NAMESPACE_STD + +namespace ranges { +namespace __stable_partition { + +struct __fn { + + template _Sent, class _Proj = identity, + indirect_unary_predicate> _Pred> + requires permutable<_Iter> + _LIBCPP_HIDE_FROM_ABI + subrange<_Iter> operator()(_Iter __first, _Sent __last, _Pred __pred, _Proj __proj = {}) const { + // TODO: implement + (void)__first; (void)__last; (void)__pred; (void)__proj; + return {}; + } + + template , _Proj>> _Pred> + requires permutable> + _LIBCPP_HIDE_FROM_ABI + borrowed_subrange_t<_Range> operator()(_Range&& __range, _Pred __pred, _Proj __proj = {}) const { + // TODO: implement + (void)__range; (void)__pred; (void)__proj; + return {}; + } + +}; + +} // namespace __stable_partition + +inline namespace __cpo { + inline constexpr auto stable_partition = __stable_partition::__fn{}; +} // namespace __cpo +} // namespace ranges + +_LIBCPP_END_NAMESPACE_STD + +#endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +#endif // _LIBCPP___ALGORITHM_RANGES_STABLE_PARTITION_H diff --git a/contrib/llvm-project/libcxx/include/__algorithm/ranges_unique.h b/contrib/llvm-project/libcxx/include/__algorithm/ranges_unique.h new file mode 100644 index 000000000000..bdf755e9406e --- /dev/null +++ b/contrib/llvm-project/libcxx/include/__algorithm/ranges_unique.h @@ -0,0 +1,74 @@ +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef _LIBCPP___ALGORITHM_RANGES_UNIQUE_H +#define _LIBCPP___ALGORITHM_RANGES_UNIQUE_H + +#include <__algorithm/make_projected.h> +#include <__algorithm/unique.h> +#include <__config> +#include <__functional/identity.h> +#include <__functional/invoke.h> +#include <__functional/ranges_operations.h> +#include <__iterator/concepts.h> +#include <__iterator/iterator_traits.h> +#include <__iterator/permutable.h> +#include <__iterator/projected.h> +#include <__ranges/access.h> +#include <__ranges/concepts.h> +#include <__ranges/dangling.h> +#include <__ranges/subrange.h> +#include <__utility/forward.h> +#include <__utility/move.h> + +#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) +# pragma GCC system_header +#endif + +#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +_LIBCPP_BEGIN_NAMESPACE_STD + +namespace ranges { +namespace __unique { + +struct __fn { + + template _Sent, class _Proj = identity, + indirect_equivalence_relation> _Comp = ranges::equal_to> + _LIBCPP_HIDE_FROM_ABI constexpr + subrange<_Iter> operator()(_Iter __first, _Sent __last, _Comp __comp = {}, _Proj __proj = {}) const { + // TODO: implement + (void)__first; (void)__last; (void)__comp; (void)__proj; + return {}; + } + + template , _Proj>> _Comp = ranges::equal_to> + requires permutable> + _LIBCPP_HIDE_FROM_ABI constexpr + borrowed_subrange_t<_Range> operator()(_Range&& __range, _Comp __comp = {}, _Proj __proj = {}) const { + // TODO: implement + (void)__range; (void)__comp; (void)__proj; + return {}; + } + +}; + +} // namespace __unique + +inline namespace __cpo { + inline constexpr auto unique = __unique::__fn{}; +} // namespace __cpo +} // namespace ranges + +_LIBCPP_END_NAMESPACE_STD + +#endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +#endif // _LIBCPP___ALGORITHM_RANGES_UNIQUE_H diff --git a/contrib/llvm-project/libcxx/include/__algorithm/ranges_unique_copy.h b/contrib/llvm-project/libcxx/include/__algorithm/ranges_unique_copy.h new file mode 100644 index 000000000000..56361aa8ae2f --- /dev/null +++ b/contrib/llvm-project/libcxx/include/__algorithm/ranges_unique_copy.h @@ -0,0 +1,88 @@ +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef _LIBCPP___ALGORITHM_RANGES_UNIQUE_COPY_H +#define _LIBCPP___ALGORITHM_RANGES_UNIQUE_COPY_H + +#include <__algorithm/in_out_result.h> +#include <__algorithm/make_projected.h> +#include <__algorithm/unique_copy.h> +#include <__concepts/same_as.h> +#include <__config> +#include <__functional/identity.h> +#include <__functional/invoke.h> +#include <__functional/ranges_operations.h> +#include <__iterator/concepts.h> +#include <__iterator/iterator_traits.h> +#include <__iterator/readable_traits.h> +#include <__iterator/projected.h> +#include <__ranges/access.h> +#include <__ranges/concepts.h> +#include <__ranges/dangling.h> +#include <__utility/forward.h> +#include <__utility/move.h> + +#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) +# pragma GCC system_header +#endif + +#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +_LIBCPP_BEGIN_NAMESPACE_STD + +namespace ranges { + +template +using unique_copy_result = in_out_result<_InIter, _OutIter>; + +namespace __unique_copy { + +struct __fn { + + template _Sent, weakly_incrementable _OutIter, class _Proj = identity, + indirect_equivalence_relation> _Comp = ranges::equal_to> + requires indirectly_copyable<_InIter, _OutIter> && + (forward_iterator<_InIter> || + (input_iterator<_OutIter> && same_as, iter_value_t<_OutIter>>) || + indirectly_copyable_storable<_InIter, _OutIter>) + _LIBCPP_HIDE_FROM_ABI constexpr + unique_copy_result<_InIter, _OutIter> + operator()(_InIter __first, _Sent __last, _OutIter __result, _Comp __comp = {}, _Proj __proj = {}) const { + // TODO: implement + (void)__first; (void)__last; (void)__result; (void)__comp; (void)__proj; + return {}; + } + + template , _Proj>> _Comp = ranges::equal_to> + requires indirectly_copyable, _OutIter> && + (forward_iterator> || + (input_iterator<_OutIter> && same_as, iter_value_t<_OutIter>>) || + indirectly_copyable_storable, _OutIter>) + _LIBCPP_HIDE_FROM_ABI constexpr + unique_copy_result, _OutIter> + operator()(_Range&& __range, _OutIter __result, _Comp __comp = {}, _Proj __proj = {}) const { + // TODO: implement + (void)__range; (void)__result; (void)__comp; (void)__proj; + return {}; + } + +}; + +} // namespace __unique_copy + +inline namespace __cpo { + inline constexpr auto unique_copy = __unique_copy::__fn{}; +} // namespace __cpo +} // namespace ranges + +_LIBCPP_END_NAMESPACE_STD + +#endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) + +#endif // _LIBCPP___ALGORITHM_RANGES_UNIQUE_COPY_H diff --git a/contrib/llvm-project/libcxx/include/__algorithm/ranges_upper_bound.h b/contrib/llvm-project/libcxx/include/__algorithm/ranges_upper_bound.h index 94b5269c86af..3c63249248fa 100644 --- a/contrib/llvm-project/libcxx/include/__algorithm/ranges_upper_bound.h +++ b/contrib/llvm-project/libcxx/include/__algorithm/ranges_upper_bound.h @@ -40,7 +40,7 @@ struct __fn { return !std::invoke(__comp, __rhs, __lhs); }; - return std::__lower_bound_impl<_RangesIterOps>(__first, __last, __value, __comp_lhs_rhs_swapped, __proj); + return std::__lower_bound_impl<_RangeAlgPolicy>(__first, __last, __value, __comp_lhs_rhs_swapped, __proj); } template (ranges::begin(__r), + return std::__lower_bound_impl<_RangeAlgPolicy>(ranges::begin(__r), ranges::end(__r), __value, __comp_lhs_rhs_swapped, diff --git a/contrib/llvm-project/libcxx/include/__algorithm/remove.h b/contrib/llvm-project/libcxx/include/__algorithm/remove.h index c00f96f78a63..8a7e99ba09a1 100644 --- a/contrib/llvm-project/libcxx/include/__algorithm/remove.h +++ b/contrib/llvm-project/libcxx/include/__algorithm/remove.h @@ -22,15 +22,15 @@ _LIBCPP_BEGIN_NAMESPACE_STD template _LIBCPP_NODISCARD_EXT _LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator -remove(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_) +remove(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value) { - __first = _VSTD::find(__first, __last, __value_); + __first = _VSTD::find(__first, __last, __value); if (__first != __last) { _ForwardIterator __i = __first; while (++__i != __last) { - if (!(*__i == __value_)) + if (!(*__i == __value)) { *__first = _VSTD::move(*__i); ++__first; diff --git a/contrib/llvm-project/libcxx/include/__algorithm/remove_copy.h b/contrib/llvm-project/libcxx/include/__algorithm/remove_copy.h index a29a385af9ac..55fc1d90a1e7 100644 --- a/contrib/llvm-project/libcxx/include/__algorithm/remove_copy.h +++ b/contrib/llvm-project/libcxx/include/__algorithm/remove_copy.h @@ -20,11 +20,11 @@ _LIBCPP_BEGIN_NAMESPACE_STD template inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 _OutputIterator -remove_copy(_InputIterator __first, _InputIterator __last, _OutputIterator __result, const _Tp& __value_) +remove_copy(_InputIterator __first, _InputIterator __last, _OutputIterator __result, const _Tp& __value) { for (; __first != __last; ++__first) { - if (!(*__first == __value_)) + if (!(*__first == __value)) { *__result = *__first; ++__result; diff --git a/contrib/llvm-project/libcxx/include/__algorithm/search.h b/contrib/llvm-project/libcxx/include/__algorithm/search.h index d89ec2b1c5bc..4ead6cac82b7 100644 --- a/contrib/llvm-project/libcxx/include/__algorithm/search.h +++ b/contrib/llvm-project/libcxx/include/__algorithm/search.h @@ -11,9 +11,15 @@ #define _LIBCPP___ALGORITHM_SEARCH_H #include <__algorithm/comp.h> +#include <__algorithm/iterator_operations.h> #include <__config> +#include <__functional/identity.h> +#include <__iterator/advance.h> +#include <__iterator/concepts.h> #include <__iterator/iterator_traits.h> +#include <__type_traits/is_callable.h> #include <__utility/pair.h> +#include #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) # pragma GCC system_header @@ -21,31 +27,43 @@ _LIBCPP_BEGIN_NAMESPACE_STD -template -pair<_ForwardIterator1, _ForwardIterator1> - _LIBCPP_CONSTEXPR_AFTER_CXX11 __search(_ForwardIterator1 __first1, _ForwardIterator1 __last1, - _ForwardIterator2 __first2, _ForwardIterator2 __last2, - _BinaryPredicate __pred, forward_iterator_tag, forward_iterator_tag) { +template +_LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX11 +pair<_Iter1, _Iter1> __search_forward_impl(_Iter1 __first1, _Sent1 __last1, + _Iter2 __first2, _Sent2 __last2, + _Pred& __pred, + _Proj1& __proj1, + _Proj2& __proj2) { if (__first2 == __last2) - return _VSTD::make_pair(__first1, __first1); // Everything matches an empty sequence + return std::make_pair(__first1, __first1); // Everything matches an empty sequence while (true) { // Find first element in sequence 1 that matchs *__first2, with a mininum of loop checks while (true) { - if (__first1 == __last1) // return __last1 if no element matches *__first2 - return _VSTD::make_pair(__last1, __last1); - if (__pred(*__first1, *__first2)) + if (__first1 == __last1) { // return __last1 if no element matches *__first2 + _IterOps<_AlgPolicy>::__advance_to(__first1, __last1); + return std::make_pair(__first1, __first1); + } + if (std::__invoke(__pred, std::__invoke(__proj1, *__first1), std::__invoke(__proj2, *__first2))) break; ++__first1; } // *__first1 matches *__first2, now match elements after here - _ForwardIterator1 __m1 = __first1; - _ForwardIterator2 __m2 = __first2; + _Iter1 __m1 = __first1; + _Iter2 __m2 = __first2; while (true) { if (++__m2 == __last2) // If pattern exhausted, __first1 is the answer (works for 1 element pattern) - return _VSTD::make_pair(__first1, __m1); - if (++__m1 == __last1) // Otherwise if source exhaused, pattern not found - return _VSTD::make_pair(__last1, __last1); - if (!__pred(*__m1, *__m2)) // if there is a mismatch, restart with a new __first1 + return std::make_pair(__first1, ++__m1); + if (++__m1 == __last1) { // Otherwise if source exhaused, pattern not found + return std::make_pair(__m1, __m1); + } + + // if there is a mismatch, restart with a new __first1 + if (!std::__invoke(__pred, std::__invoke(__proj1, *__m1), std::__invoke(__proj2, *__m2))) { ++__first1; break; @@ -54,38 +72,42 @@ pair<_ForwardIterator1, _ForwardIterator1> } } -template -_LIBCPP_CONSTEXPR_AFTER_CXX11 pair<_RandomAccessIterator1, _RandomAccessIterator1> -__search(_RandomAccessIterator1 __first1, _RandomAccessIterator1 __last1, _RandomAccessIterator2 __first2, - _RandomAccessIterator2 __last2, _BinaryPredicate __pred, random_access_iterator_tag, - random_access_iterator_tag) { - typedef typename iterator_traits<_RandomAccessIterator1>::difference_type _D1; - typedef typename iterator_traits<_RandomAccessIterator2>::difference_type _D2; - // Take advantage of knowing source and pattern lengths. Stop short when source is smaller than pattern - const _D2 __len2 = __last2 - __first2; - if (__len2 == 0) - return _VSTD::make_pair(__first1, __first1); - const _D1 __len1 = __last1 - __first1; - if (__len1 < __len2) - return _VSTD::make_pair(__last1, __last1); - const _RandomAccessIterator1 __s = __last1 - _D1(__len2 - 1); // Start of pattern match can't go beyond here +template +_LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX11 +pair<_Iter1, _Iter1> __search_random_access_impl(_Iter1 __first1, _Sent1 __last1, + _Iter2 __first2, _Sent2 __last2, + _Pred& __pred, + _Proj1& __proj1, + _Proj2& __proj2, + _DiffT1 __size1, + _DiffT2 __size2) { + const _Iter1 __s = __first1 + __size1 - _DiffT1(__size2 - 1); // Start of pattern match can't go beyond here while (true) { while (true) { - if (__first1 == __s) - return _VSTD::make_pair(__last1, __last1); - if (__pred(*__first1, *__first2)) + if (__first1 == __s) { + _IterOps<_AlgPolicy>::__advance_to(__first1, __last1); + return std::make_pair(__first1, __first1); + } + if (std::__invoke(__pred, std::__invoke(__proj1, *__first1), std::__invoke(__proj2, *__first2))) break; ++__first1; } - _RandomAccessIterator1 __m1 = __first1; - _RandomAccessIterator2 __m2 = __first2; + _Iter1 __m1 = __first1; + _Iter2 __m2 = __first2; while (true) { if (++__m2 == __last2) - return _VSTD::make_pair(__first1, __first1 + _D1(__len2)); + return std::make_pair(__first1, __first1 + _DiffT1(__size2)); ++__m1; // no need to check range on __m1 because __s guarantees we have enough source - if (!__pred(*__m1, *__m2)) { + if (!std::__invoke(__pred, std::__invoke(__proj1, *__m1), std::__invoke(__proj2, *__m2))) { ++__first1; break; } @@ -93,22 +115,78 @@ __search(_RandomAccessIterator1 __first1, _RandomAccessIterator1 __last1, _Rando } } +template +_LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX11 +pair<_Iter1, _Iter1> __search_impl(_Iter1 __first1, _Sent1 __last1, + _Iter2 __first2, _Sent2 __last2, + _Pred& __pred, + _Proj1& __proj1, + _Proj2& __proj2, + __enable_if_t<__is_cpp17_random_access_iterator<_Iter1>::value + && __is_cpp17_random_access_iterator<_Iter2>::value>* = nullptr) { + + auto __size2 = __last2 - __first2; + if (__size2 == 0) + return std::make_pair(__first1, __first1); + + auto __size1 = __last1 - __first1; + if (__size1 < __size2) { + return std::make_pair(__last1, __last1); + } + + return std::__search_random_access_impl<_ClassicAlgPolicy>(__first1, __last1, + __first2, __last2, + __pred, + __proj1, + __proj2, + __size1, + __size2); +} + +template +_LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX11 +pair<_Iter1, _Iter1> __search_impl(_Iter1 __first1, _Sent1 __last1, + _Iter2 __first2, _Sent2 __last2, + _Pred& __pred, + _Proj1& __proj1, + _Proj2& __proj2, + __enable_if_t<__is_cpp17_forward_iterator<_Iter1>::value + && __is_cpp17_forward_iterator<_Iter2>::value + && !(__is_cpp17_random_access_iterator<_Iter1>::value + && __is_cpp17_random_access_iterator<_Iter2>::value)>* = nullptr) { + return std::__search_forward_impl<_ClassicAlgPolicy>(__first1, __last1, + __first2, __last2, + __pred, + __proj1, + __proj2); +} + template -_LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator1 -search(_ForwardIterator1 __first1, _ForwardIterator1 __last1, _ForwardIterator2 __first2, _ForwardIterator2 __last2, - _BinaryPredicate __pred) { - return _VSTD::__search<_BinaryPredicate&>( - __first1, __last1, __first2, __last2, __pred, - typename iterator_traits<_ForwardIterator1>::iterator_category(), - typename iterator_traits<_ForwardIterator2>::iterator_category()).first; +_LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 +_ForwardIterator1 search(_ForwardIterator1 __first1, _ForwardIterator1 __last1, + _ForwardIterator2 __first2, _ForwardIterator2 __last2, + _BinaryPredicate __pred) { + static_assert(__is_callable<_BinaryPredicate, decltype(*__first1), decltype(*__first2)>::value, + "BinaryPredicate has to be callable"); + auto __proj = __identity(); + return std::__search_impl(__first1, __last1, __first2, __last2, __pred, __proj, __proj).first; } template -_LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator1 -search(_ForwardIterator1 __first1, _ForwardIterator1 __last1, _ForwardIterator2 __first2, _ForwardIterator2 __last2) { - typedef typename iterator_traits<_ForwardIterator1>::value_type __v1; - typedef typename iterator_traits<_ForwardIterator2>::value_type __v2; - return _VSTD::search(__first1, __last1, __first2, __last2, __equal_to<__v1, __v2>()); +_LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 +_ForwardIterator1 search(_ForwardIterator1 __first1, _ForwardIterator1 __last1, + _ForwardIterator2 __first2, _ForwardIterator2 __last2) { + using __v1 = typename iterator_traits<_ForwardIterator1>::value_type; + using __v2 = typename iterator_traits<_ForwardIterator2>::value_type; + return std::search(__first1, __last1, __first2, __last2, __equal_to<__v1, __v2>()); } #if _LIBCPP_STD_VER > 14 diff --git a/contrib/llvm-project/libcxx/include/__algorithm/search_n.h b/contrib/llvm-project/libcxx/include/__algorithm/search_n.h index 4c083de65ee2..2a0547565ee9 100644 --- a/contrib/llvm-project/libcxx/include/__algorithm/search_n.h +++ b/contrib/llvm-project/libcxx/include/__algorithm/search_n.h @@ -11,8 +11,15 @@ #define _LIBCPP___ALGORITHM_SEARCH_N_H #include <__algorithm/comp.h> +#include <__algorithm/iterator_operations.h> #include <__config> +#include <__functional/identity.h> +#include <__iterator/advance.h> +#include <__iterator/concepts.h> +#include <__iterator/distance.h> #include <__iterator/iterator_traits.h> +#include <__ranges/concepts.h> +#include <__utility/pair.h> #include // __convert_to_integral #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) @@ -21,30 +28,39 @@ _LIBCPP_BEGIN_NAMESPACE_STD -template -_LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator __search_n(_ForwardIterator __first, _ForwardIterator __last, - _Size __count, const _Tp& __value_, _BinaryPredicate __pred, - forward_iterator_tag) { +template +_LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX11 +pair<_Iter, _Iter> __search_n_forward_impl(_Iter __first, _Sent __last, + _SizeT __count, + const _Type& __value, + _Pred& __pred, + _Proj& __proj) { if (__count <= 0) - return __first; + return std::make_pair(__first, __first); while (true) { - // Find first element in sequence that matchs __value_, with a mininum of loop checks + // Find first element in sequence that matchs __value, with a mininum of loop checks while (true) { - if (__first == __last) // return __last if no element matches __value_ - return __last; - if (__pred(*__first, __value_)) + if (__first == __last) { // return __last if no element matches __value + _IterOps<_AlgPolicy>::__advance_to(__first, __last); + return std::make_pair(__first, __first); + } + if (std::__invoke(__pred, std::__invoke(__proj, *__first), __value)) break; ++__first; } - // *__first matches __value_, now match elements after here - _ForwardIterator __m = __first; - _Size __c(0); + // *__first matches __value, now match elements after here + _Iter __m = __first; + _SizeT __c(0); while (true) { if (++__c == __count) // If pattern exhausted, __first is the answer (works for 1 element pattern) - return __first; - if (++__m == __last) // Otherwise if source exhaused, pattern not found - return __last; - if (!__pred(*__m, __value_)) // if there is a mismatch, restart with a new __first + return std::make_pair(__first, ++__m); + if (++__m == __last) { // Otherwise if source exhaused, pattern not found + _IterOps<_AlgPolicy>::__advance_to(__first, __last); + return std::make_pair(__first, __first); + } + + // if there is a mismatch, restart with a new __first + if (!std::__invoke(__pred, std::__invoke(__proj, *__m), __value)) { __first = __m; ++__first; @@ -54,35 +70,44 @@ _LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator __search_n(_ForwardIterator __fir } } -template -_LIBCPP_CONSTEXPR_AFTER_CXX17 _RandomAccessIterator __search_n(_RandomAccessIterator __first, - _RandomAccessIterator __last, _Size __count, - const _Tp& __value_, _BinaryPredicate __pred, - random_access_iterator_tag) { - typedef typename iterator_traits<_RandomAccessIterator>::difference_type difference_type; - if (__count <= 0) - return __first; - _Size __len = static_cast<_Size>(__last - __first); - if (__len < __count) - return __last; - const _RandomAccessIterator __s = __last - difference_type(__count - 1); // Start of pattern match can't go beyond here +template +_LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX11 +std::pair<_Iter, _Iter> __search_n_random_access_impl(_Iter __first, _Sent __last, + _SizeT __count, + const _Type& __value, + _Pred& __pred, + _Proj& __proj, + _DiffT __size1) { + using difference_type = typename iterator_traits<_Iter>::difference_type; + if (__count == 0) + return std::make_pair(__first, __first); + if (__size1 < static_cast<_DiffT>(__count)) { + _IterOps<_AlgPolicy>::__advance_to(__first, __last); + return std::make_pair(__first, __first); + } + + const auto __s = __first + __size1 - difference_type(__count - 1); // Start of pattern match can't go beyond here while (true) { - // Find first element in sequence that matchs __value_, with a mininum of loop checks + // Find first element in sequence that matchs __value, with a mininum of loop checks while (true) { - if (__first >= __s) // return __last if no element matches __value_ - return __last; - if (__pred(*__first, __value_)) + if (__first >= __s) { // return __last if no element matches __value + _IterOps<_AlgPolicy>::__advance_to(__first, __last); + return std::make_pair(__first, __first); + } + if (std::__invoke(__pred, std::__invoke(__proj, *__first), __value)) break; ++__first; } // *__first matches __value_, now match elements after here - _RandomAccessIterator __m = __first; - _Size __c(0); + auto __m = __first; + _SizeT __c(0); while (true) { if (++__c == __count) // If pattern exhausted, __first is the answer (works for 1 element pattern) - return __first; - ++__m; // no need to check range on __m because __s guarantees we have enough source - if (!__pred(*__m, __value_)) // if there is a mismatch, restart with a new __first + return std::make_pair(__first, __first + _DiffT(__count)); + ++__m; // no need to check range on __m because __s guarantees we have enough source + + // if there is a mismatch, restart with a new __first + if (!std::__invoke(__pred, std::__invoke(__proj, *__m), __value)) { __first = __m; ++__first; @@ -92,19 +117,63 @@ _LIBCPP_CONSTEXPR_AFTER_CXX17 _RandomAccessIterator __search_n(_RandomAccessIter } } +template +_LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX11 +pair<_Iter, _Iter> __search_n_impl(_Iter __first, _Sent __last, + _DiffT __count, + const _Type& __value, + _Pred& __pred, + _Proj& __proj, + __enable_if_t<__is_cpp17_random_access_iterator<_Iter>::value>* = nullptr) { + return std::__search_n_random_access_impl<_ClassicAlgPolicy>(__first, __last, + __count, + __value, + __pred, + __proj, + __last - __first); +} + +template +_LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX11 +pair<_Iter1, _Iter1> __search_n_impl(_Iter1 __first, _Sent1 __last, + _DiffT __count, + const _Type& __value, + _Pred& __pred, + _Proj& __proj, + __enable_if_t<__is_cpp17_forward_iterator<_Iter1>::value + && !__is_cpp17_random_access_iterator<_Iter1>::value>* = nullptr) { + return std::__search_n_forward_impl<_ClassicAlgPolicy>(__first, __last, + __count, + __value, + __pred, + __proj); +} + template -_LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator search_n( - _ForwardIterator __first, _ForwardIterator __last, _Size __count, const _Tp& __value_, _BinaryPredicate __pred) { - return _VSTD::__search_n<_BinaryPredicate&>( - __first, __last, _VSTD::__convert_to_integral(__count), __value_, __pred, - typename iterator_traits<_ForwardIterator>::iterator_category()); +_LIBCPP_NODISCARD_EXT inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX17 +_ForwardIterator search_n(_ForwardIterator __first, _ForwardIterator __last, + _Size __count, + const _Tp& __value, + _BinaryPredicate __pred) { + static_assert(__is_callable<_BinaryPredicate, decltype(*__first), decltype(*__last)>::value, + "BinaryPredicate has to be callable"); + auto __proj = __identity(); + return std::__search_n_impl(__first, __last, std::__convert_to_integral(__count), __value, __pred, __proj).first; } template -_LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator -search_n(_ForwardIterator __first, _ForwardIterator __last, _Size __count, const _Tp& __value_) { +_LIBCPP_NODISCARD_EXT inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX17 +_ForwardIterator search_n(_ForwardIterator __first, _ForwardIterator __last, _Size __count, const _Tp& __value) { typedef typename iterator_traits<_ForwardIterator>::value_type __v; - return _VSTD::search_n(__first, __last, _VSTD::__convert_to_integral(__count), __value_, __equal_to<__v, _Tp>()); + return std::search_n(__first, __last, std::__convert_to_integral(__count), __value, __equal_to<__v, _Tp>()); } _LIBCPP_END_NAMESPACE_STD diff --git a/contrib/llvm-project/libcxx/include/__algorithm/set_difference.h b/contrib/llvm-project/libcxx/include/__algorithm/set_difference.h index 5e2dca24e446..4378bd5304d9 100644 --- a/contrib/llvm-project/libcxx/include/__algorithm/set_difference.h +++ b/contrib/llvm-project/libcxx/include/__algorithm/set_difference.h @@ -13,7 +13,12 @@ #include <__algorithm/comp_ref_type.h> #include <__algorithm/copy.h> #include <__config> +#include <__functional/identity.h> +#include <__functional/invoke.h> #include <__iterator/iterator_traits.h> +#include <__utility/move.h> +#include <__utility/pair.h> +#include #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) # pragma GCC system_header @@ -21,50 +26,52 @@ _LIBCPP_BEGIN_NAMESPACE_STD -template -_LIBCPP_CONSTEXPR_AFTER_CXX17 _OutputIterator -__set_difference(_InputIterator1 __first1, _InputIterator1 __last1, - _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp) -{ - while (__first1 != __last1) - { - if (__first2 == __last2) - return _VSTD::copy(__first1, __last1, __result); - if (__comp(*__first1, *__first2)) - { - *__result = *__first1; - ++__result; - ++__first1; - } - else - { - if (!__comp(*__first2, *__first1)) - ++__first1; - ++__first2; - } +template < class _Comp, class _InIter1, class _Sent1, class _InIter2, class _Sent2, class _OutIter> +_LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX17 pair<__uncvref_t<_InIter1>, __uncvref_t<_OutIter> > +__set_difference( + _InIter1&& __first1, _Sent1&& __last1, _InIter2&& __first2, _Sent2&& __last2, _OutIter&& __result, _Comp&& __comp) { + while (__first1 != __last1 && __first2 != __last2) { + if (__comp(*__first1, *__first2)) { + *__result = *__first1; + ++__first1; + ++__result; + } else if (__comp(*__first2, *__first1)) { + ++__first2; + } else { + ++__first1; + ++__first2; } - return __result; + } + return std::__copy(std::move(__first1), std::move(__last1), std::move(__result)); } template -inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 -_OutputIterator -set_difference(_InputIterator1 __first1, _InputIterator1 __last1, - _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp) -{ - typedef typename __comp_ref_type<_Compare>::type _Comp_ref; - return _VSTD::__set_difference<_Comp_ref>(__first1, __last1, __first2, __last2, __result, __comp); +inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX17 _OutputIterator set_difference( + _InputIterator1 __first1, + _InputIterator1 __last1, + _InputIterator2 __first2, + _InputIterator2 __last2, + _OutputIterator __result, + _Compare __comp) { + typedef typename __comp_ref_type<_Compare>::type _Comp_ref; + return std::__set_difference<_Comp_ref>(__first1, __last1, __first2, __last2, __result, __comp).second; } template -inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 -_OutputIterator -set_difference(_InputIterator1 __first1, _InputIterator1 __last1, - _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result) -{ - return _VSTD::set_difference(__first1, __last1, __first2, __last2, __result, - __less::value_type, - typename iterator_traits<_InputIterator2>::value_type>()); +inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX17 _OutputIterator set_difference( + _InputIterator1 __first1, + _InputIterator1 __last1, + _InputIterator2 __first2, + _InputIterator2 __last2, + _OutputIterator __result) { + return std::__set_difference( + __first1, + __last1, + __first2, + __last2, + __result, + __less::value_type, + typename iterator_traits<_InputIterator2>::value_type>()).second; } _LIBCPP_END_NAMESPACE_STD diff --git a/contrib/llvm-project/libcxx/include/__algorithm/set_intersection.h b/contrib/llvm-project/libcxx/include/__algorithm/set_intersection.h index c4163fcd4c3c..77cc83738d1f 100644 --- a/contrib/llvm-project/libcxx/include/__algorithm/set_intersection.h +++ b/contrib/llvm-project/libcxx/include/__algorithm/set_intersection.h @@ -11,8 +11,11 @@ #include <__algorithm/comp.h> #include <__algorithm/comp_ref_type.h> +#include <__algorithm/iterator_operations.h> #include <__config> #include <__iterator/iterator_traits.h> +#include <__iterator/next.h> +#include <__utility/move.h> #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) # pragma GCC system_header @@ -20,48 +23,76 @@ _LIBCPP_BEGIN_NAMESPACE_STD -template -_LIBCPP_CONSTEXPR_AFTER_CXX17 _OutputIterator -__set_intersection(_InputIterator1 __first1, _InputIterator1 __last1, - _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp) -{ - while (__first1 != __last1 && __first2 != __last2) - { - if (__comp(*__first1, *__first2)) - ++__first1; - else - { - if (!__comp(*__first2, *__first1)) - { - *__result = *__first1; - ++__result; - ++__first1; - } - ++__first2; - } +template +struct __set_intersection_result { + _InIter1 __in1_; + _InIter2 __in2_; + _OutIter __out_; + + // need a constructor as C++03 aggregate init is hard + _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX17 + __set_intersection_result(_InIter1&& __in_iter1, _InIter2&& __in_iter2, _OutIter&& __out_iter) + : __in1_(std::move(__in_iter1)), __in2_(std::move(__in_iter2)), __out_(std::move(__out_iter)) {} +}; + +template +_LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX17 __set_intersection_result<_InIter1, _InIter2, _OutIter> +__set_intersection( + _InIter1 __first1, _Sent1 __last1, _InIter2 __first2, _Sent2 __last2, _OutIter __result, _Compare&& __comp) { + while (__first1 != __last1 && __first2 != __last2) { + if (__comp(*__first1, *__first2)) + ++__first1; + else { + if (!__comp(*__first2, *__first1)) { + *__result = *__first1; + ++__result; + ++__first1; + } + ++__first2; } - return __result; + } + + return __set_intersection_result<_InIter1, _InIter2, _OutIter>( + _IterOps<_AlgPolicy>::next(std::move(__first1), std::move(__last1)), + _IterOps<_AlgPolicy>::next(std::move(__first2), std::move(__last2)), + std::move(__result)); } template -inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 -_OutputIterator -set_intersection(_InputIterator1 __first1, _InputIterator1 __last1, - _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp) -{ - typedef typename __comp_ref_type<_Compare>::type _Comp_ref; - return _VSTD::__set_intersection<_Comp_ref>(__first1, __last1, __first2, __last2, __result, __comp); +inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX17 _OutputIterator set_intersection( + _InputIterator1 __first1, + _InputIterator1 __last1, + _InputIterator2 __first2, + _InputIterator2 __last2, + _OutputIterator __result, + _Compare __comp) { + typedef typename __comp_ref_type<_Compare>::type _Comp_ref; + return std::__set_intersection<_ClassicAlgPolicy, _Comp_ref>( + std::move(__first1), + std::move(__last1), + std::move(__first2), + std::move(__last2), + std::move(__result), + __comp) + .__out_; } template -inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 -_OutputIterator -set_intersection(_InputIterator1 __first1, _InputIterator1 __last1, - _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result) -{ - return _VSTD::set_intersection(__first1, __last1, __first2, __last2, __result, - __less::value_type, - typename iterator_traits<_InputIterator2>::value_type>()); +inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX17 _OutputIterator set_intersection( + _InputIterator1 __first1, + _InputIterator1 __last1, + _InputIterator2 __first2, + _InputIterator2 __last2, + _OutputIterator __result) { + return std::__set_intersection<_ClassicAlgPolicy>( + std::move(__first1), + std::move(__last1), + std::move(__first2), + std::move(__last2), + std::move(__result), + __less::value_type, + typename iterator_traits<_InputIterator2>::value_type>()) + .__out_; } _LIBCPP_END_NAMESPACE_STD diff --git a/contrib/llvm-project/libcxx/include/__algorithm/set_symmetric_difference.h b/contrib/llvm-project/libcxx/include/__algorithm/set_symmetric_difference.h index 2dbfb35d7be6..cd532ab5800d 100644 --- a/contrib/llvm-project/libcxx/include/__algorithm/set_symmetric_difference.h +++ b/contrib/llvm-project/libcxx/include/__algorithm/set_symmetric_difference.h @@ -14,6 +14,7 @@ #include <__algorithm/copy.h> #include <__config> #include <__iterator/iterator_traits.h> +#include <__utility/move.h> #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) # pragma GCC system_header @@ -21,55 +22,81 @@ _LIBCPP_BEGIN_NAMESPACE_STD -template -_LIBCPP_CONSTEXPR_AFTER_CXX17 _OutputIterator -__set_symmetric_difference(_InputIterator1 __first1, _InputIterator1 __last1, - _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp) -{ - while (__first1 != __last1) - { - if (__first2 == __last2) - return _VSTD::copy(__first1, __last1, __result); - if (__comp(*__first1, *__first2)) - { - *__result = *__first1; - ++__result; - ++__first1; - } - else - { - if (__comp(*__first2, *__first1)) - { - *__result = *__first2; - ++__result; - } - else - ++__first1; - ++__first2; - } +template +struct __set_symmetric_difference_result { + _InIter1 __in1_; + _InIter2 __in2_; + _OutIter __out_; + + // need a constructor as C++03 aggregate init is hard + _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX17 + __set_symmetric_difference_result(_InIter1&& __in_iter1, _InIter2&& __in_iter2, _OutIter&& __out_iter) + : __in1_(std::move(__in_iter1)), __in2_(std::move(__in_iter2)), __out_(std::move(__out_iter)) {} +}; + +template +_LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX17 __set_symmetric_difference_result<_InIter1, _InIter2, _OutIter> +__set_symmetric_difference( + _InIter1 __first1, _Sent1 __last1, _InIter2 __first2, _Sent2 __last2, _OutIter __result, _Compare&& __comp) { + while (__first1 != __last1) { + if (__first2 == __last2) { + auto __ret1 = std::__copy_impl(std::move(__first1), std::move(__last1), std::move(__result)); + return __set_symmetric_difference_result<_InIter1, _InIter2, _OutIter>( + std::move(__ret1.first), std::move(__first2), std::move((__ret1.second))); + } + if (__comp(*__first1, *__first2)) { + *__result = *__first1; + ++__result; + ++__first1; + } else { + if (__comp(*__first2, *__first1)) { + *__result = *__first2; + ++__result; + } else { + ++__first1; + } + ++__first2; } - return _VSTD::copy(__first2, __last2, __result); + } + auto __ret2 = std::__copy_impl(std::move(__first2), std::move(__last2), std::move(__result)); + return __set_symmetric_difference_result<_InIter1, _InIter2, _OutIter>( + std::move(__first1), std::move(__ret2.first), std::move((__ret2.second))); } template -inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 -_OutputIterator -set_symmetric_difference(_InputIterator1 __first1, _InputIterator1 __last1, - _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp) -{ - typedef typename __comp_ref_type<_Compare>::type _Comp_ref; - return _VSTD::__set_symmetric_difference<_Comp_ref>(__first1, __last1, __first2, __last2, __result, __comp); +_LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX17 _OutputIterator set_symmetric_difference( + _InputIterator1 __first1, + _InputIterator1 __last1, + _InputIterator2 __first2, + _InputIterator2 __last2, + _OutputIterator __result, + _Compare __comp) { + typedef typename __comp_ref_type<_Compare>::type _Comp_ref; + return std::__set_symmetric_difference<_Comp_ref>( + std::move(__first1), + std::move(__last1), + std::move(__first2), + std::move(__last2), + std::move(__result), + __comp) + .__out_; } template -inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 -_OutputIterator -set_symmetric_difference(_InputIterator1 __first1, _InputIterator1 __last1, - _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result) -{ - return _VSTD::set_symmetric_difference(__first1, __last1, __first2, __last2, __result, - __less::value_type, - typename iterator_traits<_InputIterator2>::value_type>()); +_LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX17 _OutputIterator set_symmetric_difference( + _InputIterator1 __first1, + _InputIterator1 __last1, + _InputIterator2 __first2, + _InputIterator2 __last2, + _OutputIterator __result) { + return std::set_symmetric_difference( + std::move(__first1), + std::move(__last1), + std::move(__first2), + std::move(__last2), + std::move(__result), + __less::value_type, + typename iterator_traits<_InputIterator2>::value_type>()); } _LIBCPP_END_NAMESPACE_STD diff --git a/contrib/llvm-project/libcxx/include/__algorithm/sort.h b/contrib/llvm-project/libcxx/include/__algorithm/sort.h index f7406a5170e1..76a18215731b 100644 --- a/contrib/llvm-project/libcxx/include/__algorithm/sort.h +++ b/contrib/llvm-project/libcxx/include/__algorithm/sort.h @@ -17,6 +17,7 @@ #include <__bits> #include <__config> #include <__debug> +#include <__debug_utils/randomize_range.h> #include <__functional/operations.h> #include <__functional/ranges_operations.h> #include <__iterator/iterator_traits.h> @@ -24,10 +25,6 @@ #include #include -#if defined(_LIBCPP_DEBUG_RANDOMIZE_UNSPECIFIED_STABILITY) -# include <__algorithm/shuffle.h> -#endif - #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) # pragma GCC system_header #endif @@ -582,7 +579,7 @@ extern template _LIBCPP_FUNC_VIS unsigned __sort5<__less&, long dou template inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX17 void __sort_impl(_RandomAccessIterator __first, _RandomAccessIterator __last, _Comp& __comp) { - _LIBCPP_DEBUG_RANDOMIZE_RANGE(__first, __last); + std::__debug_randomize_range(__first, __last); using _Comp_ref = typename __comp_ref_type<_Comp>::type; if (__libcpp_is_constant_evaluated()) { std::__partial_sort<_Comp_ref>(__first, __last, __last, _Comp_ref(__comp)); diff --git a/contrib/llvm-project/libcxx/include/__algorithm/sort_heap.h b/contrib/llvm-project/libcxx/include/__algorithm/sort_heap.h index 3a63d744fc1c..261adedd0eaf 100644 --- a/contrib/llvm-project/libcxx/include/__algorithm/sort_heap.h +++ b/contrib/llvm-project/libcxx/include/__algorithm/sort_heap.h @@ -14,6 +14,7 @@ #include <__algorithm/pop_heap.h> #include <__config> #include <__iterator/iterator_traits.h> +#include <__utility/move.h> #include // swap #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) @@ -23,29 +24,27 @@ _LIBCPP_BEGIN_NAMESPACE_STD template -_LIBCPP_CONSTEXPR_AFTER_CXX17 void -__sort_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp) -{ - typedef typename iterator_traits<_RandomAccessIterator>::difference_type difference_type; - for (difference_type __n = __last - __first; __n > 1; --__last, (void) --__n) - _VSTD::__pop_heap<_Compare>(__first, __last, __comp, __n); +inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX11 +void __sort_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare& __comp) { + using _CompRef = typename __comp_ref_type<_Compare>::type; + _CompRef __comp_ref = __comp; + + using difference_type = typename iterator_traits<_RandomAccessIterator>::difference_type; + for (difference_type __n = __last - __first; __n > 1; --__last, (void) --__n) + std::__pop_heap<_CompRef>(__first, __last, __comp_ref, __n); } template -inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 -void -sort_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp) -{ - typedef typename __comp_ref_type<_Compare>::type _Comp_ref; - _VSTD::__sort_heap<_Comp_ref>(__first, __last, __comp); +inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX17 +void sort_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp) { + std::__sort_heap(std::move(__first), std::move(__last), __comp); } template -inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 -void -sort_heap(_RandomAccessIterator __first, _RandomAccessIterator __last) -{ - _VSTD::sort_heap(__first, __last, __less::value_type>()); +inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX17 +void sort_heap(_RandomAccessIterator __first, _RandomAccessIterator __last) { + std::sort_heap(std::move(__first), std::move(__last), + __less::value_type>()); } _LIBCPP_END_NAMESPACE_STD diff --git a/contrib/llvm-project/libcxx/include/__algorithm/upper_bound.h b/contrib/llvm-project/libcxx/include/__algorithm/upper_bound.h index c6483607e3c6..3fc254873532 100644 --- a/contrib/llvm-project/libcxx/include/__algorithm/upper_bound.h +++ b/contrib/llvm-project/libcxx/include/__algorithm/upper_bound.h @@ -24,7 +24,7 @@ _LIBCPP_BEGIN_NAMESPACE_STD template _LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator -__upper_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_, _Compare __comp) +__upper_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value, _Compare __comp) { typedef typename iterator_traits<_ForwardIterator>::difference_type difference_type; difference_type __len = _VSTD::distance(__first, __last); @@ -33,7 +33,7 @@ __upper_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __va difference_type __l2 = _VSTD::__half_positive(__len); _ForwardIterator __m = __first; _VSTD::advance(__m, __l2); - if (__comp(__value_, *__m)) + if (__comp(__value, *__m)) __len = __l2; else { @@ -48,18 +48,18 @@ template _LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator -upper_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_, _Compare __comp) +upper_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value, _Compare __comp) { - return _VSTD::__upper_bound<_Compare&>(__first, __last, __value_, __comp); + return _VSTD::__upper_bound<_Compare&>(__first, __last, __value, __comp); } template _LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator -upper_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_) +upper_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value) { - return _VSTD::upper_bound(__first, __last, __value_, + return _VSTD::upper_bound(__first, __last, __value, __less<_Tp, typename iterator_traits<_ForwardIterator>::value_type>()); } diff --git a/contrib/llvm-project/libcxx/include/__bit_reference b/contrib/llvm-project/libcxx/include/__bit_reference index 8c4f1badbd35..f54cb6c16f48 100644 --- a/contrib/llvm-project/libcxx/include/__bit_reference +++ b/contrib/llvm-project/libcxx/include/__bit_reference @@ -250,9 +250,9 @@ __find_bool_false(__bit_iterator<_Cp, _IsConst> __first, typename _Cp::size_type template inline _LIBCPP_INLINE_VISIBILITY __bit_iterator<_Cp, _IsConst> -find(__bit_iterator<_Cp, _IsConst> __first, __bit_iterator<_Cp, _IsConst> __last, const _Tp& __value_) +find(__bit_iterator<_Cp, _IsConst> __first, __bit_iterator<_Cp, _IsConst> __last, const _Tp& __value) { - if (static_cast(__value_)) + if (static_cast(__value)) return _VSTD::__find_bool_true(__first, static_cast(__last - __first)); return _VSTD::__find_bool_false(__first, static_cast(__last - __first)); } @@ -324,9 +324,9 @@ __count_bool_false(__bit_iterator<_Cp, _IsConst> __first, typename _Cp::size_typ template inline _LIBCPP_INLINE_VISIBILITY typename __bit_iterator<_Cp, _IsConst>::difference_type -count(__bit_iterator<_Cp, _IsConst> __first, __bit_iterator<_Cp, _IsConst> __last, const _Tp& __value_) +count(__bit_iterator<_Cp, _IsConst> __first, __bit_iterator<_Cp, _IsConst> __last, const _Tp& __value) { - if (static_cast(__value_)) + if (static_cast(__value)) return _VSTD::__count_bool_true(__first, static_cast(__last - __first)); return _VSTD::__count_bool_false(__first, static_cast(__last - __first)); } @@ -396,11 +396,11 @@ __fill_n_true(__bit_iterator<_Cp, false> __first, typename _Cp::size_type __n) template inline _LIBCPP_INLINE_VISIBILITY void -fill_n(__bit_iterator<_Cp, false> __first, typename _Cp::size_type __n, bool __value_) +fill_n(__bit_iterator<_Cp, false> __first, typename _Cp::size_type __n, bool __value) { if (__n > 0) { - if (__value_) + if (__value) _VSTD::__fill_n_true(__first, __n); else _VSTD::__fill_n_false(__first, __n); @@ -412,9 +412,9 @@ fill_n(__bit_iterator<_Cp, false> __first, typename _Cp::size_type __n, bool __v template inline _LIBCPP_INLINE_VISIBILITY void -fill(__bit_iterator<_Cp, false> __first, __bit_iterator<_Cp, false> __last, bool __value_) +fill(__bit_iterator<_Cp, false> __first, __bit_iterator<_Cp, false> __last, bool __value) { - _VSTD::fill_n(__first, static_cast(__last - __first), __value_); + _VSTD::fill_n(__first, static_cast(__last - __first), __value); } // copy diff --git a/contrib/llvm-project/libcxx/include/__bits b/contrib/llvm-project/libcxx/include/__bits index 1eee8f576e9e..92ef5c0a7b49 100644 --- a/contrib/llvm-project/libcxx/include/__bits +++ b/contrib/llvm-project/libcxx/include/__bits @@ -43,6 +43,23 @@ int __libcpp_clz(unsigned long __x) _NOEXCEPT { return __builtin_clzl(__x); inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR int __libcpp_clz(unsigned long long __x) _NOEXCEPT { return __builtin_clzll(__x); } +# ifndef _LIBCPP_HAS_NO_INT128 +inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR +int __libcpp_clz(__uint128_t __x) _NOEXCEPT { + // The function is written in this form due to C++ constexpr limitations. + // The algorithm: + // - Test whether any bit in the high 64-bits is set + // - No bits set: + // - The high 64-bits contain 64 leading zeros, + // - Add the result of the low 64-bits. + // - Any bits set: + // - The number of leading zeros of the input is the number of leading + // zeros in the high 64-bits. + return ((__x >> 64) == 0) + ? (64 + __builtin_clzll(static_cast(__x))) + : __builtin_clzll(static_cast(__x >> 64)); +} +# endif inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR int __libcpp_popcount(unsigned __x) _NOEXCEPT { return __builtin_popcount(__x); } diff --git a/contrib/llvm-project/libcxx/include/__charconv/tables.h b/contrib/llvm-project/libcxx/include/__charconv/tables.h index a2f7f7ce29b3..83f39e6fd2ef 100644 --- a/contrib/llvm-project/libcxx/include/__charconv/tables.h +++ b/contrib/llvm-project/libcxx/include/__charconv/tables.h @@ -35,6 +35,11 @@ struct __table { static const uint32_t __pow10_32[10]; static const uint64_t __pow10_64[20]; +# ifndef _LIBCPP_HAS_NO_INT128 + // TODO FMT Reduce the number of entries in this table. + static const __uint128_t __pow10_128[40]; + static const int __pow10_128_offset = 0; +# endif static const char __digits_base_10[200]; }; @@ -106,6 +111,51 @@ const uint64_t __table<_Tp>::__pow10_64[20] = {UINT64_C(0), UINT64_C(1000000000000000000), UINT64_C(10000000000000000000)}; +# ifndef _LIBCPP_HAS_NO_INT128 +template +const __uint128_t __table<_Tp>::__pow10_128[40] = { + UINT64_C(0), + UINT64_C(10), + UINT64_C(100), + UINT64_C(1000), + UINT64_C(10000), + UINT64_C(100000), + UINT64_C(1000000), + UINT64_C(10000000), + UINT64_C(100000000), + UINT64_C(1000000000), + UINT64_C(10000000000), + UINT64_C(100000000000), + UINT64_C(1000000000000), + UINT64_C(10000000000000), + UINT64_C(100000000000000), + UINT64_C(1000000000000000), + UINT64_C(10000000000000000), + UINT64_C(100000000000000000), + UINT64_C(1000000000000000000), + UINT64_C(10000000000000000000), + __uint128_t(UINT64_C(10000000000000000000)) * UINT64_C(10), + __uint128_t(UINT64_C(10000000000000000000)) * UINT64_C(100), + __uint128_t(UINT64_C(10000000000000000000)) * UINT64_C(1000), + __uint128_t(UINT64_C(10000000000000000000)) * UINT64_C(10000), + __uint128_t(UINT64_C(10000000000000000000)) * UINT64_C(100000), + __uint128_t(UINT64_C(10000000000000000000)) * UINT64_C(1000000), + __uint128_t(UINT64_C(10000000000000000000)) * UINT64_C(10000000), + __uint128_t(UINT64_C(10000000000000000000)) * UINT64_C(100000000), + __uint128_t(UINT64_C(10000000000000000000)) * UINT64_C(1000000000), + __uint128_t(UINT64_C(10000000000000000000)) * UINT64_C(10000000000), + __uint128_t(UINT64_C(10000000000000000000)) * UINT64_C(100000000000), + __uint128_t(UINT64_C(10000000000000000000)) * UINT64_C(1000000000000), + __uint128_t(UINT64_C(10000000000000000000)) * UINT64_C(10000000000000), + __uint128_t(UINT64_C(10000000000000000000)) * UINT64_C(100000000000000), + __uint128_t(UINT64_C(10000000000000000000)) * UINT64_C(1000000000000000), + __uint128_t(UINT64_C(10000000000000000000)) * UINT64_C(10000000000000000), + __uint128_t(UINT64_C(10000000000000000000)) * UINT64_C(100000000000000000), + __uint128_t(UINT64_C(10000000000000000000)) * UINT64_C(1000000000000000000), + __uint128_t(UINT64_C(10000000000000000000)) * UINT64_C(10000000000000000000), + (__uint128_t(UINT64_C(10000000000000000000)) * UINT64_C(10000000000000000000)) * 10}; +# endif + template const char __table<_Tp>::__digits_base_10[200] = { // clang-format off diff --git a/contrib/llvm-project/libcxx/include/__charconv/to_chars_base_10.h b/contrib/llvm-project/libcxx/include/__charconv/to_chars_base_10.h index 91c209559aff..d25deffc592f 100644 --- a/contrib/llvm-project/libcxx/include/__charconv/to_chars_base_10.h +++ b/contrib/llvm-project/libcxx/include/__charconv/to_chars_base_10.h @@ -14,11 +14,15 @@ #include <__charconv/tables.h> #include <__config> #include +#include #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) # pragma GCC system_header #endif +_LIBCPP_PUSH_MACROS +#include <__undef_macros> + _LIBCPP_BEGIN_NAMESPACE_STD #ifndef _LIBCPP_CXX03_LANG @@ -62,7 +66,6 @@ _LIBCPP_HIDE_FROM_ABI inline char* __append9(char* __first, uint32_t __value) no return __itoa::__append8(__itoa::__append1(__first, __value / 100000000), __value % 100000000); } -// This function is used for uint32_t and uint64_t. template _LIBCPP_HIDE_FROM_ABI char* __append10(char* __first, _Tp __value) noexcept { return __itoa::__append8(__itoa::__append2(__first, static_cast(__value / 100000000)), @@ -118,10 +121,65 @@ _LIBCPP_HIDE_FROM_ABI inline char* __base_10_u64(char* __buffer, uint64_t __valu return __itoa::__append10(__buffer, __value); } +# ifndef _LIBCPP_HAS_NO_INT128 +/// \returns 10^\a exp +/// +/// \pre \a exp [19, 39] +/// +/// \note The lookup table contains a partial set of exponents limiting the +/// range that can be used. However the range is sufficient for +/// \ref __base_10_u128. +_LIBCPP_HIDE_FROM_ABI inline __uint128_t __pow_10(int __exp) noexcept { + _LIBCPP_ASSERT(__exp >= __table<>::__pow10_128_offset, "Index out of bounds"); + return __table<>::__pow10_128[__exp - __table<>::__pow10_128_offset]; +} + +_LIBCPP_HIDE_FROM_ABI inline char* __base_10_u128(char* __buffer, __uint128_t __value) noexcept { + _LIBCPP_ASSERT( + __value > numeric_limits::max(), "The optimizations for this algorithm fail when this isn't true."); + + // Unlike the 64 to 32 bit case the 128 bit case the "upper half" can't be + // stored in the "lower half". Instead we first need to handle the top most + // digits separately. + // + // Maximum unsigned values + // 64 bit 18'446'744'073'709'551'615 (20 digits) + // 128 bit 340'282'366'920'938'463'463'374'607'431'768'211'455 (39 digits) + // step 1 ^ ([0-1] digits) + // step 2 ^^^^^^^^^^^^^^^^^^^^^^^^^ ([0-19] digits) + // step 3 ^^^^^^^^^^^^^^^^^^^^^^^^^ (19 digits) + if (__value >= __itoa::__pow_10(38)) { + // step 1 + __buffer = __itoa::__append1(__buffer, static_cast(__value / __itoa::__pow_10(38))); + __value %= __itoa::__pow_10(38); + + // step 2 always 19 digits. + // They are handled here since leading zeros need to be appended to the buffer, + __buffer = __itoa::__append9(__buffer, static_cast(__value / __itoa::__pow_10(29))); + __value %= __itoa::__pow_10(29); + __buffer = __itoa::__append10(__buffer, static_cast(__value / __itoa::__pow_10(19))); + __value %= __itoa::__pow_10(19); + } + else { + // step 2 + // This version needs to determine the position of the leading non-zero digit. + __buffer = __base_10_u64(__buffer, static_cast(__value / __itoa::__pow_10(19))); + __value %= __itoa::__pow_10(19); + } + + // Step 3 + __buffer = __itoa::__append9(__buffer, static_cast(__value / 10000000000)); + __buffer = __itoa::__append10(__buffer, static_cast(__value % 10000000000)); + + return __buffer; +} +# endif } // namespace __itoa #endif // _LIBCPP_CXX03_LANG _LIBCPP_END_NAMESPACE_STD +_LIBCPP_POP_MACROS + #endif // _LIBCPP___CHARCONV_TO_CHARS_BASE_10_H diff --git a/contrib/llvm-project/libcxx/include/__chrono/day.h b/contrib/llvm-project/libcxx/include/__chrono/day.h index 7e425558e359..d9fa4ffbc45e 100644 --- a/contrib/llvm-project/libcxx/include/__chrono/day.h +++ b/contrib/llvm-project/libcxx/include/__chrono/day.h @@ -12,6 +12,7 @@ #include <__chrono/duration.h> #include <__config> +#include #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) # pragma GCC system_header @@ -45,25 +46,9 @@ _LIBCPP_HIDE_FROM_ABI inline constexpr bool operator==(const day& __lhs, const day& __rhs) noexcept { return static_cast(__lhs) == static_cast(__rhs); } -_LIBCPP_HIDE_FROM_ABI inline constexpr -bool operator!=(const day& __lhs, const day& __rhs) noexcept -{ return !(__lhs == __rhs); } - -_LIBCPP_HIDE_FROM_ABI inline constexpr -bool operator< (const day& __lhs, const day& __rhs) noexcept -{ return static_cast(__lhs) < static_cast(__rhs); } - -_LIBCPP_HIDE_FROM_ABI inline constexpr -bool operator> (const day& __lhs, const day& __rhs) noexcept -{ return __rhs < __lhs; } - -_LIBCPP_HIDE_FROM_ABI inline constexpr -bool operator<=(const day& __lhs, const day& __rhs) noexcept -{ return !(__rhs < __lhs);} - -_LIBCPP_HIDE_FROM_ABI inline constexpr -bool operator>=(const day& __lhs, const day& __rhs) noexcept -{ return !(__lhs < __rhs); } +_LIBCPP_HIDE_FROM_ABI constexpr strong_ordering operator<=>(const day& __lhs, const day& __rhs) noexcept { + return static_cast(__lhs) <=> static_cast(__rhs); +} _LIBCPP_HIDE_FROM_ABI inline constexpr day operator+ (const day& __lhs, const days& __rhs) noexcept diff --git a/contrib/llvm-project/libcxx/include/__chrono/duration.h b/contrib/llvm-project/libcxx/include/__chrono/duration.h index f5207594291e..c502574fb267 100644 --- a/contrib/llvm-project/libcxx/include/__chrono/duration.h +++ b/contrib/llvm-project/libcxx/include/__chrono/duration.h @@ -286,10 +286,10 @@ public: _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14 duration& operator+=(const duration& __d) {__rep_ += __d.count(); return *this;} _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14 duration& operator-=(const duration& __d) {__rep_ -= __d.count(); return *this;} - _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14 duration& operator*=(const rep& rhs) {__rep_ *= rhs; return *this;} - _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14 duration& operator/=(const rep& rhs) {__rep_ /= rhs; return *this;} - _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14 duration& operator%=(const rep& rhs) {__rep_ %= rhs; return *this;} - _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14 duration& operator%=(const duration& rhs) {__rep_ %= rhs.count(); return *this;} + _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14 duration& operator*=(const rep& __rhs) {__rep_ *= __rhs; return *this;} + _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14 duration& operator/=(const rep& __rhs) {__rep_ /= __rhs; return *this;} + _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14 duration& operator%=(const rep& __rhs) {__rep_ %= __rhs; return *this;} + _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14 duration& operator%=(const duration& __rhs) {__rep_ %= __rhs.count(); return *this;} // special values diff --git a/contrib/llvm-project/libcxx/include/__chrono/time_point.h b/contrib/llvm-project/libcxx/include/__chrono/time_point.h index ac2d347a0dca..63d67d77dd05 100644 --- a/contrib/llvm-project/libcxx/include/__chrono/time_point.h +++ b/contrib/llvm-project/libcxx/include/__chrono/time_point.h @@ -47,12 +47,12 @@ public: // conversions template _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11 - time_point(const time_point& t, + time_point(const time_point& __t, typename enable_if < is_convertible<_Duration2, duration>::value >::type* = nullptr) - : __d_(t.time_since_epoch()) {} + : __d_(__t.time_since_epoch()) {} // observer diff --git a/contrib/llvm-project/libcxx/include/__chrono/year.h b/contrib/llvm-project/libcxx/include/__chrono/year.h index a641fe1c93b0..c7f0027eba7b 100644 --- a/contrib/llvm-project/libcxx/include/__chrono/year.h +++ b/contrib/llvm-project/libcxx/include/__chrono/year.h @@ -12,6 +12,7 @@ #include <__chrono/duration.h> #include <__config> +#include #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) # pragma GCC system_header @@ -100,9 +101,11 @@ _LIBCPP_HIDE_FROM_ABI inline constexpr year& year::operator-=(const years& __dy) noexcept { *this = *this - __dy; return *this; } -_LIBCPP_HIDE_FROM_ABI inline constexpr -bool year::ok() const noexcept -{ return static_cast(min()) <= __y && __y <= static_cast(max()); } +_LIBCPP_HIDE_FROM_ABI constexpr bool year::ok() const noexcept { + static_assert(static_cast(std::numeric_limits::max()) == static_cast(max())); + return static_cast(min()) <= __y; +} + } // namespace chrono _LIBCPP_END_NAMESPACE_STD diff --git a/contrib/llvm-project/libcxx/include/__chrono/year_month_weekday.h b/contrib/llvm-project/libcxx/include/__chrono/year_month_weekday.h index 9ba81e7e3f65..b69b77152fb1 100644 --- a/contrib/llvm-project/libcxx/include/__chrono/year_month_weekday.h +++ b/contrib/llvm-project/libcxx/include/__chrono/year_month_weekday.h @@ -47,10 +47,10 @@ public: : year_month_weekday(__from_days(__sysd.time_since_epoch())) {} _LIBCPP_HIDE_FROM_ABI inline explicit constexpr year_month_weekday(const local_days& __locd) noexcept : year_month_weekday(__from_days(__locd.time_since_epoch())) {} - _LIBCPP_HIDE_FROM_ABI constexpr year_month_weekday& operator+=(const months& m) noexcept; - _LIBCPP_HIDE_FROM_ABI constexpr year_month_weekday& operator-=(const months& m) noexcept; - _LIBCPP_HIDE_FROM_ABI constexpr year_month_weekday& operator+=(const years& y) noexcept; - _LIBCPP_HIDE_FROM_ABI constexpr year_month_weekday& operator-=(const years& y) noexcept; + _LIBCPP_HIDE_FROM_ABI constexpr year_month_weekday& operator+=(const months&) noexcept; + _LIBCPP_HIDE_FROM_ABI constexpr year_month_weekday& operator-=(const months&) noexcept; + _LIBCPP_HIDE_FROM_ABI constexpr year_month_weekday& operator+=(const years&) noexcept; + _LIBCPP_HIDE_FROM_ABI constexpr year_month_weekday& operator-=(const years&) noexcept; _LIBCPP_HIDE_FROM_ABI inline constexpr chrono::year year() const noexcept { return __y; } _LIBCPP_HIDE_FROM_ABI inline constexpr chrono::month month() const noexcept { return __m; } diff --git a/contrib/llvm-project/libcxx/include/__config b/contrib/llvm-project/libcxx/include/__config index e4b7d25edf34..22c2ed7fd87b 100644 --- a/contrib/llvm-project/libcxx/include/__config +++ b/contrib/llvm-project/libcxx/include/__config @@ -26,6 +26,13 @@ # define _LIBCPP_VERSION 15000 +# define _LIBCPP_CONCAT_IMPL(_X, _Y) _X##_Y +# define _LIBCPP_CONCAT(_X, _Y) _LIBCPP_CONCAT_IMPL(_X, _Y) + +// Valid C++ identifier that revs with every libc++ version. This can be used to +// generate identifiers that must be unique for every released libc++ version. +# define _LIBCPP_VERSIONED_IDENTIFIER _LIBCPP_CONCAT(v, _LIBCPP_VERSION) + # if __STDC_HOSTED__ == 0 # define _LIBCPP_FREESTANDING # endif @@ -568,12 +575,6 @@ typedef __char32_t char32_t; # endif // defined(_LIBCPP_OBJECT_FORMAT_COFF) -# if __has_attribute(internal_linkage) -# define _LIBCPP_INTERNAL_LINKAGE __attribute__((internal_linkage)) -# else -# define _LIBCPP_INTERNAL_LINKAGE _LIBCPP_ALWAYS_INLINE -# endif - # if __has_attribute(exclude_from_explicit_instantiation) # define _LIBCPP_EXCLUDE_FROM_EXPLICIT_INSTANTIATION __attribute__((__exclude_from_explicit_instantiation__)) # else @@ -583,20 +584,35 @@ typedef __char32_t char32_t; # define _LIBCPP_EXCLUDE_FROM_EXPLICIT_INSTANTIATION _LIBCPP_ALWAYS_INLINE # endif -# ifndef _LIBCPP_HIDE_FROM_ABI_PER_TU -# ifndef _LIBCPP_HIDE_FROM_ABI_PER_TU_BY_DEFAULT -# define _LIBCPP_HIDE_FROM_ABI_PER_TU 0 -# else -# define _LIBCPP_HIDE_FROM_ABI_PER_TU 1 -# endif -# endif - -# ifndef _LIBCPP_HIDE_FROM_ABI -# if _LIBCPP_HIDE_FROM_ABI_PER_TU -# define _LIBCPP_HIDE_FROM_ABI _LIBCPP_HIDDEN _LIBCPP_INTERNAL_LINKAGE -# else -# define _LIBCPP_HIDE_FROM_ABI _LIBCPP_HIDDEN _LIBCPP_EXCLUDE_FROM_EXPLICIT_INSTANTIATION -# endif +// This macro marks a symbol as being hidden from libc++'s ABI. This is achieved +// on two levels: +// 1. The symbol is given hidden visibility, which ensures that users won't start exporting +// symbols from their dynamic library by means of using the libc++ headers. This ensures +// that those symbols stay private to the dynamic library in which it is defined. +// +// 2. The symbol is given an ABI tag that changes with each version of libc++. This ensures +// that no ODR violation can arise from mixing two TUs compiled with different versions +// of libc++ where we would have changed the definition of a symbol. If the symbols shared +// the same name, the ODR would require that their definitions be token-by-token equivalent, +// which basically prevents us from being able to make any change to any function in our +// headers. Using this ABI tag ensures that the symbol name is "bumped" artificially at +// each release, which lets us change the definition of these symbols at our leisure. +// Note that historically, this has been achieved in various ways, including force-inlining +// all functions or giving internal linkage to all functions. Both these (previous) solutions +// suffer from drawbacks that lead notably to code bloat. +// +// Note that we use _LIBCPP_EXCLUDE_FROM_EXPLICIT_INSTANTIATION to ensure that we don't depend +// on _LIBCPP_HIDE_FROM_ABI methods of classes explicitly instantiated in the dynamic library. +// +// TODO: We provide a escape hatch with _LIBCPP_NO_ABI_TAG for folks who want to avoid increasing +// the length of symbols with an ABI tag. In practice, we should remove the escape hatch and +// use compression mangling instead, see https://github.com/itanium-cxx-abi/cxx-abi/issues/70. +# ifndef _LIBCPP_NO_ABI_TAG +# define _LIBCPP_HIDE_FROM_ABI \ + _LIBCPP_HIDDEN _LIBCPP_EXCLUDE_FROM_EXPLICIT_INSTANTIATION \ + __attribute__((__abi_tag__(_LIBCPP_TOSTRING(_LIBCPP_VERSIONED_IDENTIFIER)))) +# else +# define _LIBCPP_HIDE_FROM_ABI _LIBCPP_HIDDEN _LIBCPP_EXCLUDE_FROM_EXPLICIT_INSTANTIATION # endif # ifdef _LIBCPP_BUILDING_LIBRARY diff --git a/contrib/llvm-project/libcxx/include/__debug b/contrib/llvm-project/libcxx/include/__debug index d3dd202b54ab..59e85cb7d1bc 100644 --- a/contrib/llvm-project/libcxx/include/__debug +++ b/contrib/llvm-project/libcxx/include/__debug @@ -28,22 +28,6 @@ # define _LIBCPP_DEBUG_RANDOMIZE_UNSPECIFIED_STABILITY #endif -// TODO: Define this as a function instead -#if defined(_LIBCPP_DEBUG_RANDOMIZE_UNSPECIFIED_STABILITY) -# if defined(_LIBCPP_CXX03_LANG) -# error Support for unspecified stability is only for C++11 and higher -# endif -# define _LIBCPP_DEBUG_RANDOMIZE_RANGE(__first, __last) \ - do { \ - if (!__builtin_is_constant_evaluated()) \ - std::shuffle(__first, __last, __libcpp_debug_randomizer()); \ - } while (false) -#else -# define _LIBCPP_DEBUG_RANDOMIZE_RANGE(__first, __last) \ - do { \ - } while (false) -#endif - #ifdef _LIBCPP_ENABLE_DEBUG_MODE # define _LIBCPP_DEBUG_ASSERT(x, m) _LIBCPP_ASSERT(::std::__libcpp_is_constant_evaluated() || (x), m) #else diff --git a/contrib/llvm-project/libcxx/include/__debug_utils/randomize_range.h b/contrib/llvm-project/libcxx/include/__debug_utils/randomize_range.h new file mode 100644 index 000000000000..fd5b9e588493 --- /dev/null +++ b/contrib/llvm-project/libcxx/include/__debug_utils/randomize_range.h @@ -0,0 +1,42 @@ +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef _LIBCPP___LIBCXX_DEBUG_RANDOMIZE_RANGE_H +#define _LIBCPP___LIBCXX_DEBUG_RANDOMIZE_RANGE_H + +#include <__config> + +#ifdef _LIBCPP_DEBUG_RANDOMIZE_UNSPECIFIED_STABILITY +# include <__algorithm/shuffle.h> +# include <__type_traits/is_constant_evaluated.h> +#endif + +#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) +# pragma GCC system_header +#endif + +_LIBCPP_BEGIN_NAMESPACE_STD + +template +_LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX11 void __debug_randomize_range(_Iterator __first, _Iterator __last) { +#ifdef _LIBCPP_DEBUG_RANDOMIZE_UNSPECIFIED_STABILITY +# ifdef _LIBCPP_CXX03_LANG +# error Support for unspecified stability is only for C++11 and higher +# endif + + if (!__libcpp_is_constant_evaluated()) + std::shuffle(__first, __last, __libcpp_debug_randomizer()); +#else + (void)__first; + (void)__last; +#endif +} + +_LIBCPP_END_NAMESPACE_STD + +#endif // _LIBCPP___LIBCXX_DEBUG_RANDOMIZE_RANGE_H diff --git a/contrib/llvm-project/libcxx/include/__filesystem/copy_options.h b/contrib/llvm-project/libcxx/include/__filesystem/copy_options.h index 2e037403f6f2..96c7535812e2 100644 --- a/contrib/llvm-project/libcxx/include/__filesystem/copy_options.h +++ b/contrib/llvm-project/libcxx/include/__filesystem/copy_options.h @@ -38,41 +38,41 @@ enum class _LIBCPP_ENUM_VIS copy_options : unsigned short { }; _LIBCPP_INLINE_VISIBILITY -inline constexpr copy_options operator&(copy_options _LHS, copy_options _RHS) { - return static_cast(static_cast(_LHS) & - static_cast(_RHS)); +inline constexpr copy_options operator&(copy_options __lhs, copy_options __rhs) { + return static_cast(static_cast(__lhs) & + static_cast(__rhs)); } _LIBCPP_INLINE_VISIBILITY -inline constexpr copy_options operator|(copy_options _LHS, copy_options _RHS) { - return static_cast(static_cast(_LHS) | - static_cast(_RHS)); +inline constexpr copy_options operator|(copy_options __lhs, copy_options __rhs) { + return static_cast(static_cast(__lhs) | + static_cast(__rhs)); } _LIBCPP_INLINE_VISIBILITY -inline constexpr copy_options operator^(copy_options _LHS, copy_options _RHS) { - return static_cast(static_cast(_LHS) ^ - static_cast(_RHS)); +inline constexpr copy_options operator^(copy_options __lhs, copy_options __rhs) { + return static_cast(static_cast(__lhs) ^ + static_cast(__rhs)); } _LIBCPP_INLINE_VISIBILITY -inline constexpr copy_options operator~(copy_options _LHS) { - return static_cast(~static_cast(_LHS)); +inline constexpr copy_options operator~(copy_options __lhs) { + return static_cast(~static_cast(__lhs)); } _LIBCPP_INLINE_VISIBILITY -inline copy_options& operator&=(copy_options& _LHS, copy_options _RHS) { - return _LHS = _LHS & _RHS; +inline copy_options& operator&=(copy_options& __lhs, copy_options __rhs) { + return __lhs = __lhs & __rhs; } _LIBCPP_INLINE_VISIBILITY -inline copy_options& operator|=(copy_options& _LHS, copy_options _RHS) { - return _LHS = _LHS | _RHS; +inline copy_options& operator|=(copy_options& __lhs, copy_options __rhs) { + return __lhs = __lhs | __rhs; } _LIBCPP_INLINE_VISIBILITY -inline copy_options& operator^=(copy_options& _LHS, copy_options _RHS) { - return _LHS = _LHS ^ _RHS; +inline copy_options& operator^=(copy_options& __lhs, copy_options __rhs) { + return __lhs = __lhs ^ __rhs; } _LIBCPP_AVAILABILITY_FILESYSTEM_POP diff --git a/contrib/llvm-project/libcxx/include/__filesystem/directory_options.h b/contrib/llvm-project/libcxx/include/__filesystem/directory_options.h index d3f8cc1deb21..c5c031a567cf 100644 --- a/contrib/llvm-project/libcxx/include/__filesystem/directory_options.h +++ b/contrib/llvm-project/libcxx/include/__filesystem/directory_options.h @@ -30,47 +30,47 @@ enum class _LIBCPP_ENUM_VIS directory_options : unsigned char { }; _LIBCPP_INLINE_VISIBILITY -inline constexpr directory_options operator&(directory_options _LHS, - directory_options _RHS) { - return static_cast(static_cast(_LHS) & - static_cast(_RHS)); +inline constexpr directory_options operator&(directory_options __lhs, + directory_options __rhs) { + return static_cast(static_cast(__lhs) & + static_cast(__rhs)); } _LIBCPP_INLINE_VISIBILITY -inline constexpr directory_options operator|(directory_options _LHS, - directory_options _RHS) { - return static_cast(static_cast(_LHS) | - static_cast(_RHS)); +inline constexpr directory_options operator|(directory_options __lhs, + directory_options __rhs) { + return static_cast(static_cast(__lhs) | + static_cast(__rhs)); } _LIBCPP_INLINE_VISIBILITY -inline constexpr directory_options operator^(directory_options _LHS, - directory_options _RHS) { - return static_cast(static_cast(_LHS) ^ - static_cast(_RHS)); +inline constexpr directory_options operator^(directory_options __lhs, + directory_options __rhs) { + return static_cast(static_cast(__lhs) ^ + static_cast(__rhs)); } _LIBCPP_INLINE_VISIBILITY -inline constexpr directory_options operator~(directory_options _LHS) { - return static_cast(~static_cast(_LHS)); +inline constexpr directory_options operator~(directory_options __lhs) { + return static_cast(~static_cast(__lhs)); } _LIBCPP_INLINE_VISIBILITY -inline directory_options& operator&=(directory_options& _LHS, - directory_options _RHS) { - return _LHS = _LHS & _RHS; +inline directory_options& operator&=(directory_options& __lhs, + directory_options __rhs) { + return __lhs = __lhs & __rhs; } _LIBCPP_INLINE_VISIBILITY -inline directory_options& operator|=(directory_options& _LHS, - directory_options _RHS) { - return _LHS = _LHS | _RHS; +inline directory_options& operator|=(directory_options& __lhs, + directory_options __rhs) { + return __lhs = __lhs | __rhs; } _LIBCPP_INLINE_VISIBILITY -inline directory_options& operator^=(directory_options& _LHS, - directory_options _RHS) { - return _LHS = _LHS ^ _RHS; +inline directory_options& operator^=(directory_options& __lhs, + directory_options __rhs) { + return __lhs = __lhs ^ __rhs; } _LIBCPP_AVAILABILITY_FILESYSTEM_POP diff --git a/contrib/llvm-project/libcxx/include/__filesystem/operations.h b/contrib/llvm-project/libcxx/include/__filesystem/operations.h index 85c71f017f34..f48d301d090c 100644 --- a/contrib/llvm-project/libcxx/include/__filesystem/operations.h +++ b/contrib/llvm-project/libcxx/include/__filesystem/operations.h @@ -39,10 +39,10 @@ _LIBCPP_FUNC_VIS path __canonical(const path&, error_code* __ec = nullptr); _LIBCPP_FUNC_VIS bool __copy_file(const path& __from, const path& __to, copy_options __opt, error_code* __ec = nullptr); _LIBCPP_FUNC_VIS void __copy_symlink(const path& __existing_symlink, const path& __new_symlink, error_code* __ec = nullptr); _LIBCPP_FUNC_VIS void __copy(const path& __from, const path& __to, copy_options __opt, error_code* __ec = nullptr); -_LIBCPP_FUNC_VIS bool __create_directories(const path& p, error_code* ec = nullptr); +_LIBCPP_FUNC_VIS bool __create_directories(const path&, error_code* = nullptr); _LIBCPP_FUNC_VIS void __create_directory_symlink(const path& __to, const path& __new_symlink, error_code* __ec = nullptr); -_LIBCPP_FUNC_VIS bool __create_directory(const path& p, error_code* ec = nullptr); -_LIBCPP_FUNC_VIS bool __create_directory(const path& p, const path& attributes, error_code* ec = nullptr); +_LIBCPP_FUNC_VIS bool __create_directory(const path&, error_code* = nullptr); +_LIBCPP_FUNC_VIS bool __create_directory(const path&, const path& __attributes, error_code* = nullptr); _LIBCPP_FUNC_VIS void __create_hard_link(const path& __to, const path& __new_hard_link, error_code* __ec = nullptr); _LIBCPP_FUNC_VIS void __create_symlink(const path& __to, const path& __new_symlink, error_code* __ec = nullptr); _LIBCPP_FUNC_VIS path __current_path(error_code* __ec = nullptr); @@ -52,14 +52,14 @@ _LIBCPP_FUNC_VIS file_status __status(const path&, error_code* __ec = nullptr); _LIBCPP_FUNC_VIS uintmax_t __file_size(const path&, error_code* __ec = nullptr); _LIBCPP_FUNC_VIS uintmax_t __hard_link_count(const path&, error_code* __ec = nullptr); _LIBCPP_FUNC_VIS file_status __symlink_status(const path&, error_code* __ec = nullptr); -_LIBCPP_FUNC_VIS file_time_type __last_write_time(const path& p, error_code* ec = nullptr); -_LIBCPP_FUNC_VIS void __last_write_time(const path& p, file_time_type new_time, error_code* ec = nullptr); +_LIBCPP_FUNC_VIS file_time_type __last_write_time(const path&, error_code* __ec = nullptr); +_LIBCPP_FUNC_VIS void __last_write_time(const path&, file_time_type __new_time, error_code* __ec = nullptr); _LIBCPP_FUNC_VIS path __weakly_canonical(path const& __p, error_code* __ec = nullptr); -_LIBCPP_FUNC_VIS path __read_symlink(const path& p, error_code* ec = nullptr); -_LIBCPP_FUNC_VIS uintmax_t __remove_all(const path& p, error_code* ec = nullptr); -_LIBCPP_FUNC_VIS bool __remove(const path& p, error_code* ec = nullptr); -_LIBCPP_FUNC_VIS void __rename(const path& from, const path& to, error_code* ec = nullptr); -_LIBCPP_FUNC_VIS void __resize_file(const path& p, uintmax_t size, error_code* ec = nullptr); +_LIBCPP_FUNC_VIS path __read_symlink(const path&, error_code* __ec = nullptr); +_LIBCPP_FUNC_VIS uintmax_t __remove_all(const path&, error_code* __ec = nullptr); +_LIBCPP_FUNC_VIS bool __remove(const path&, error_code* __ec = nullptr); +_LIBCPP_FUNC_VIS void __rename(const path& __from, const path& __to, error_code* __ec = nullptr); +_LIBCPP_FUNC_VIS void __resize_file(const path&, uintmax_t __size, error_code* = nullptr); _LIBCPP_FUNC_VIS path __temp_directory_path(error_code* __ec = nullptr); inline _LIBCPP_HIDE_FROM_ABI path absolute(const path& __p) { return __absolute(__p); } @@ -118,7 +118,7 @@ inline _LIBCPP_HIDE_FROM_ABI bool is_character_file(const path& __p, error_code& inline _LIBCPP_HIDE_FROM_ABI bool is_directory(file_status __s) noexcept { return __s.type() == file_type::directory; } inline _LIBCPP_HIDE_FROM_ABI bool is_directory(const path& __p) { return is_directory(__status(__p)); } inline _LIBCPP_HIDE_FROM_ABI bool is_directory(const path& __p, error_code& __ec) noexcept { return is_directory(__status(__p, &__ec)); } -_LIBCPP_FUNC_VIS bool __fs_is_empty(const path& p, error_code* ec = nullptr); +_LIBCPP_FUNC_VIS bool __fs_is_empty(const path& __p, error_code* __ec = nullptr); inline _LIBCPP_HIDE_FROM_ABI bool is_empty(const path& __p) { return __fs_is_empty(__p); } inline _LIBCPP_HIDE_FROM_ABI bool is_empty(const path& __p, error_code& __ec) { return __fs_is_empty(__p, &__ec); } inline _LIBCPP_HIDE_FROM_ABI bool is_fifo(file_status __s) noexcept { return __s.type() == file_type::fifo; } diff --git a/contrib/llvm-project/libcxx/include/__filesystem/perm_options.h b/contrib/llvm-project/libcxx/include/__filesystem/perm_options.h index f7580a2473d0..4aba302edfbe 100644 --- a/contrib/llvm-project/libcxx/include/__filesystem/perm_options.h +++ b/contrib/llvm-project/libcxx/include/__filesystem/perm_options.h @@ -31,41 +31,41 @@ enum class _LIBCPP_ENUM_VIS perm_options : unsigned char { }; _LIBCPP_INLINE_VISIBILITY -inline constexpr perm_options operator&(perm_options _LHS, perm_options _RHS) { - return static_cast(static_cast(_LHS) & - static_cast(_RHS)); +inline constexpr perm_options operator&(perm_options __lhs, perm_options __rhs) { + return static_cast(static_cast(__lhs) & + static_cast(__rhs)); } _LIBCPP_INLINE_VISIBILITY -inline constexpr perm_options operator|(perm_options _LHS, perm_options _RHS) { - return static_cast(static_cast(_LHS) | - static_cast(_RHS)); +inline constexpr perm_options operator|(perm_options __lhs, perm_options __rhs) { + return static_cast(static_cast(__lhs) | + static_cast(__rhs)); } _LIBCPP_INLINE_VISIBILITY -inline constexpr perm_options operator^(perm_options _LHS, perm_options _RHS) { - return static_cast(static_cast(_LHS) ^ - static_cast(_RHS)); +inline constexpr perm_options operator^(perm_options __lhs, perm_options __rhs) { + return static_cast(static_cast(__lhs) ^ + static_cast(__rhs)); } _LIBCPP_INLINE_VISIBILITY -inline constexpr perm_options operator~(perm_options _LHS) { - return static_cast(~static_cast(_LHS)); +inline constexpr perm_options operator~(perm_options __lhs) { + return static_cast(~static_cast(__lhs)); } _LIBCPP_INLINE_VISIBILITY -inline perm_options& operator&=(perm_options& _LHS, perm_options _RHS) { - return _LHS = _LHS & _RHS; +inline perm_options& operator&=(perm_options& __lhs, perm_options __rhs) { + return __lhs = __lhs & __rhs; } _LIBCPP_INLINE_VISIBILITY -inline perm_options& operator|=(perm_options& _LHS, perm_options _RHS) { - return _LHS = _LHS | _RHS; +inline perm_options& operator|=(perm_options& __lhs, perm_options __rhs) { + return __lhs = __lhs | __rhs; } _LIBCPP_INLINE_VISIBILITY -inline perm_options& operator^=(perm_options& _LHS, perm_options _RHS) { - return _LHS = _LHS ^ _RHS; +inline perm_options& operator^=(perm_options& __lhs, perm_options __rhs) { + return __lhs = __lhs ^ __rhs; } _LIBCPP_AVAILABILITY_FILESYSTEM_POP diff --git a/contrib/llvm-project/libcxx/include/__filesystem/perms.h b/contrib/llvm-project/libcxx/include/__filesystem/perms.h index 0e5c7ed8d2e9..df4590057ee1 100644 --- a/contrib/llvm-project/libcxx/include/__filesystem/perms.h +++ b/contrib/llvm-project/libcxx/include/__filesystem/perms.h @@ -55,36 +55,36 @@ enum class _LIBCPP_ENUM_VIS perms : unsigned { }; _LIBCPP_INLINE_VISIBILITY -inline constexpr perms operator&(perms _LHS, perms _RHS) { - return static_cast(static_cast(_LHS) & - static_cast(_RHS)); +inline constexpr perms operator&(perms __lhs, perms __rhs) { + return static_cast(static_cast(__lhs) & + static_cast(__rhs)); } _LIBCPP_INLINE_VISIBILITY -inline constexpr perms operator|(perms _LHS, perms _RHS) { - return static_cast(static_cast(_LHS) | - static_cast(_RHS)); +inline constexpr perms operator|(perms __lhs, perms __rhs) { + return static_cast(static_cast(__lhs) | + static_cast(__rhs)); } _LIBCPP_INLINE_VISIBILITY -inline constexpr perms operator^(perms _LHS, perms _RHS) { - return static_cast(static_cast(_LHS) ^ - static_cast(_RHS)); +inline constexpr perms operator^(perms __lhs, perms __rhs) { + return static_cast(static_cast(__lhs) ^ + static_cast(__rhs)); } _LIBCPP_INLINE_VISIBILITY -inline constexpr perms operator~(perms _LHS) { - return static_cast(~static_cast(_LHS)); +inline constexpr perms operator~(perms __lhs) { + return static_cast(~static_cast(__lhs)); } _LIBCPP_INLINE_VISIBILITY -inline perms& operator&=(perms& _LHS, perms _RHS) { return _LHS = _LHS & _RHS; } +inline perms& operator&=(perms& __lhs, perms __rhs) { return __lhs = __lhs & __rhs; } _LIBCPP_INLINE_VISIBILITY -inline perms& operator|=(perms& _LHS, perms _RHS) { return _LHS = _LHS | _RHS; } +inline perms& operator|=(perms& __lhs, perms __rhs) { return __lhs = __lhs | __rhs; } _LIBCPP_INLINE_VISIBILITY -inline perms& operator^=(perms& _LHS, perms _RHS) { return _LHS = _LHS ^ _RHS; } +inline perms& operator^=(perms& __lhs, perms __rhs) { return __lhs = __lhs ^ __rhs; } _LIBCPP_AVAILABILITY_FILESYSTEM_POP diff --git a/contrib/llvm-project/libcxx/include/__format/format_arg.h b/contrib/llvm-project/libcxx/include/__format/format_arg.h index 3f2afc898d2c..4f93024b7c69 100644 --- a/contrib/llvm-project/libcxx/include/__format/format_arg.h +++ b/contrib/llvm-project/libcxx/include/__format/format_arg.h @@ -147,15 +147,20 @@ public: /// Contains the implementation for basic_format_arg::handle. struct __handle { template - _LIBCPP_HIDE_FROM_ABI explicit __handle(const _Tp& __v) noexcept + _LIBCPP_HIDE_FROM_ABI explicit __handle(_Tp&& __v) noexcept : __ptr_(_VSTD::addressof(__v)), __format_([](basic_format_parse_context<_CharT>& __parse_ctx, _Context& __ctx, const void* __ptr) { - using _Formatter = typename _Context::template formatter_type<_Tp>; - using _Qp = conditional_t(), declval<_Context&>()); }, - const _Tp, _Tp>; + using _Dp = remove_cvref_t<_Tp>; + using _Formatter = typename _Context::template formatter_type<_Dp>; + constexpr bool __const_formattable = + requires { _Formatter().format(declval(), declval<_Context&>()); }; + using _Qp = conditional_t<__const_formattable, const _Dp, _Dp>; + + static_assert(__const_formattable || !is_const_v>, "Mandated by [format.arg]/18"); + _Formatter __f; __parse_ctx.advance_to(__f.parse(__parse_ctx)); - __ctx.advance_to(__f.format(*const_cast<_Qp*>(static_cast(__ptr)), __ctx)); + __ctx.advance_to(__f.format(*const_cast<_Qp*>(static_cast(__ptr)), __ctx)); }) {} const void* __ptr_; @@ -205,7 +210,9 @@ public: _LIBCPP_HIDE_FROM_ABI __basic_format_arg_value(basic_string_view<_CharT> __value) noexcept : __string_view_(__value) {} _LIBCPP_HIDE_FROM_ABI __basic_format_arg_value(const void* __value) noexcept : __ptr_(__value) {} - _LIBCPP_HIDE_FROM_ABI __basic_format_arg_value(__handle __value) noexcept : __handle_(__value) {} + _LIBCPP_HIDE_FROM_ABI __basic_format_arg_value(__handle __value) noexcept + // TODO FMT Investigate why it doesn't work without the forward. + : __handle_(std::forward<__handle>(__value)) {} }; template @@ -251,11 +258,11 @@ public: __handle_.__format_(__parse_ctx, __ctx, __handle_.__ptr_); } - _LIBCPP_HIDE_FROM_ABI explicit handle(typename __basic_format_arg_value<_Context>::__handle __handle) noexcept + _LIBCPP_HIDE_FROM_ABI explicit handle(typename __basic_format_arg_value<_Context>::__handle& __handle) noexcept : __handle_(__handle) {} private: - typename __basic_format_arg_value<_Context>::__handle __handle_; + typename __basic_format_arg_value<_Context>::__handle& __handle_; }; #endif //_LIBCPP_STD_VER > 17 diff --git a/contrib/llvm-project/libcxx/include/__format/format_arg_store.h b/contrib/llvm-project/libcxx/include/__format/format_arg_store.h index 6602dfeb956b..26a5e71b93af 100644 --- a/contrib/llvm-project/libcxx/include/__format/format_arg_store.h +++ b/contrib/llvm-project/libcxx/include/__format/format_arg_store.h @@ -197,7 +197,7 @@ _LIBCPP_HIDE_FROM_ABI void __create_packed_storage(uint64_t& __types, __basic_fo int __shift = 0; ( [&] { - basic_format_arg<_Context> __arg = __create_format_arg<_Context>(_VSTD::forward<_Args>(__args)); + basic_format_arg<_Context> __arg = __create_format_arg<_Context>(__args); if (__shift != 0) __types |= static_cast(__arg.__type_) << __shift; else @@ -211,7 +211,7 @@ _LIBCPP_HIDE_FROM_ABI void __create_packed_storage(uint64_t& __types, __basic_fo template _LIBCPP_HIDE_FROM_ABI void __store_basic_format_arg(basic_format_arg<_Context>* __data, _Args&&... __args) noexcept { - ([&] { *__data++ = __create_format_arg<_Context>(_VSTD::forward<_Args>(__args)); }(), ...); + ([&] { *__data++ = __create_format_arg<_Context>(__args); }(), ...); } template @@ -230,12 +230,12 @@ struct __unpacked_format_arg_store { template struct _LIBCPP_TEMPLATE_VIS __format_arg_store { _LIBCPP_HIDE_FROM_ABI - __format_arg_store(_Args&&... __args) noexcept { + __format_arg_store(_Args&... __args) noexcept { if constexpr (sizeof...(_Args) != 0) { if constexpr (__format::__use_packed_format_arg_store(sizeof...(_Args))) - __format::__create_packed_storage(__storage.__types_, __storage.__values_, _VSTD::forward<_Args>(__args)...); + __format::__create_packed_storage(__storage.__types_, __storage.__values_, __args...); else - __format::__store_basic_format_arg<_Context>(__storage.__args_, _VSTD::forward<_Args>(__args)...); + __format::__store_basic_format_arg<_Context>(__storage.__args_, __args...); } } diff --git a/contrib/llvm-project/libcxx/include/__format/formatter.h b/contrib/llvm-project/libcxx/include/__format/formatter.h index c39e25b354eb..4816f961c445 100644 --- a/contrib/llvm-project/libcxx/include/__format/formatter.h +++ b/contrib/llvm-project/libcxx/include/__format/formatter.h @@ -10,20 +10,10 @@ #ifndef _LIBCPP___FORMAT_FORMATTER_H #define _LIBCPP___FORMAT_FORMATTER_H -#include <__algorithm/copy.h> -#include <__algorithm/fill_n.h> -#include <__algorithm/transform.h> -#include <__assert> #include <__availability> #include <__concepts/same_as.h> #include <__config> -#include <__format/format_error.h> #include <__format/format_fwd.h> -#include <__format/format_string.h> -#include <__format/parser_std_format_spec.h> -#include <__utility/move.h> -#include <__utility/unreachable.h> -#include #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) # pragma GCC system_header @@ -49,229 +39,12 @@ struct _LIBCPP_TEMPLATE_VIS _LIBCPP_AVAILABILITY_FORMAT formatter { formatter& operator=(const formatter&) = delete; }; -namespace __format_spec { - -_LIBCPP_HIDE_FROM_ABI inline char* __insert_sign(char* __buf, bool __negative, - _Flags::_Sign __sign) { - if (__negative) - *__buf++ = '-'; - else - switch (__sign) { - case _Flags::_Sign::__default: - case _Flags::_Sign::__minus: - // No sign added. - break; - case _Flags::_Sign::__plus: - *__buf++ = '+'; - break; - case _Flags::_Sign::__space: - *__buf++ = ' '; - break; - } - - return __buf; -} - -_LIBCPP_HIDE_FROM_ABI constexpr char __hex_to_upper(char c) { - switch (c) { - case 'a': - return 'A'; - case 'b': - return 'B'; - case 'c': - return 'C'; - case 'd': - return 'D'; - case 'e': - return 'E'; - case 'f': - return 'F'; - } - return c; -} - -} // namespace __format_spec - namespace __formatter { /** The character types that formatters are specialized for. */ template concept __char_type = same_as<_CharT, char> || same_as<_CharT, wchar_t>; -struct _LIBCPP_TEMPLATE_VIS __padding_size_result { - size_t __before; - size_t __after; -}; - -_LIBCPP_HIDE_FROM_ABI constexpr __padding_size_result -__padding_size(size_t __size, size_t __width, - __format_spec::_Flags::_Alignment __align) { - _LIBCPP_ASSERT(__width > __size, - "Don't call this function when no padding is required"); - _LIBCPP_ASSERT( - __align != __format_spec::_Flags::_Alignment::__default, - "Caller should adjust the default to the value required by the type"); - - size_t __fill = __width - __size; - switch (__align) { - case __format_spec::_Flags::_Alignment::__default: - __libcpp_unreachable(); - - case __format_spec::_Flags::_Alignment::__left: - return {0, __fill}; - - case __format_spec::_Flags::_Alignment::__center: { - // The extra padding is divided per [format.string.std]/3 - // __before = floor(__fill, 2); - // __after = ceil(__fill, 2); - size_t __before = __fill / 2; - size_t __after = __fill - __before; - return {__before, __after}; - } - case __format_spec::_Flags::_Alignment::__right: - return {__fill, 0}; - } - __libcpp_unreachable(); -} - -/** - * Writes the input to the output with the required padding. - * - * Since the output column width is specified the function can be used for - * ASCII and Unicode input. - * - * @pre [@a __first, @a __last) is a valid range. - * @pre @a __size <= @a __width. Using this function when this pre-condition - * doesn't hold incurs an unwanted overhead. - * - * @param __out_it The output iterator to write to. - * @param __first Pointer to the first element to write. - * @param __last Pointer beyond the last element to write. - * @param __size The (estimated) output column width. When the elements - * to be written are ASCII the following condition holds - * @a __size == @a __last - @a __first. - * @param __width The number of output columns to write. - * @param __fill The character used for the alignment of the output. - * TODO FMT Will probably change to support Unicode grapheme - * cluster. - * @param __alignment The requested alignment. - * - * @returns An iterator pointing beyond the last element written. - * - * @note The type of the elements in range [@a __first, @a __last) can differ - * from the type of @a __fill. Integer output uses @c std::to_chars for its - * conversion, which means the [@a __first, @a __last) always contains elements - * of the type @c char. - */ -template -_LIBCPP_HIDE_FROM_ABI auto -__write(output_iterator auto __out_it, const _CharT* __first, - const _CharT* __last, size_t __size, size_t __width, _Fill __fill, - __format_spec::_Flags::_Alignment __alignment) -> decltype(__out_it) { - - _LIBCPP_ASSERT(__first <= __last, "Not a valid range"); - _LIBCPP_ASSERT(__size < __width, "Precondition failure"); - - __padding_size_result __padding = - __padding_size(__size, __width, __alignment); - __out_it = _VSTD::fill_n(_VSTD::move(__out_it), __padding.__before, __fill); - __out_it = _VSTD::copy(__first, __last, _VSTD::move(__out_it)); - return _VSTD::fill_n(_VSTD::move(__out_it), __padding.__after, __fill); -} - -/** - * @overload - * - * Writes additional zero's for the precision before the exponent. - * This is used when the precision requested in the format string is larger - * than the maximum precision of the floating-point type. These precision - * digits are always 0. - * - * @param __exponent The location of the exponent character. - * @param __num_trailing_zeros The number of 0's to write before the exponent - * character. - */ -template -_LIBCPP_HIDE_FROM_ABI auto __write(output_iterator auto __out_it, const _CharT* __first, - const _CharT* __last, size_t __size, size_t __width, _Fill __fill, - __format_spec::_Flags::_Alignment __alignment, const _CharT* __exponent, - size_t __num_trailing_zeros) -> decltype(__out_it) { - _LIBCPP_ASSERT(__first <= __last, "Not a valid range"); - _LIBCPP_ASSERT(__num_trailing_zeros > 0, "The overload not writing trailing zeros should have been used"); - - __padding_size_result __padding = __padding_size(__size + __num_trailing_zeros, __width, __alignment); - __out_it = _VSTD::fill_n(_VSTD::move(__out_it), __padding.__before, __fill); - __out_it = _VSTD::copy(__first, __exponent, _VSTD::move(__out_it)); - __out_it = _VSTD::fill_n(_VSTD::move(__out_it), __num_trailing_zeros, _CharT('0')); - __out_it = _VSTD::copy(__exponent, __last, _VSTD::move(__out_it)); - return _VSTD::fill_n(_VSTD::move(__out_it), __padding.__after, __fill); -} - -/** - * @overload - * - * Uses a transformation operation before writing an element. - * - * TODO FMT Fill will probably change to support Unicode grapheme cluster. - */ -template -_LIBCPP_HIDE_FROM_ABI auto -__write(output_iterator auto __out_it, const _CharT* __first, - const _CharT* __last, size_t __size, _UnaryOperation __op, - size_t __width, _Fill __fill, - __format_spec::_Flags::_Alignment __alignment) -> decltype(__out_it) { - - _LIBCPP_ASSERT(__first <= __last, "Not a valid range"); - _LIBCPP_ASSERT(__size < __width, "Precondition failure"); - - __padding_size_result __padding = - __padding_size(__size, __width, __alignment); - __out_it = _VSTD::fill_n(_VSTD::move(__out_it), __padding.__before, __fill); - __out_it = _VSTD::transform(__first, __last, _VSTD::move(__out_it), __op); - return _VSTD::fill_n(_VSTD::move(__out_it), __padding.__after, __fill); -} - -/** - * Writes Unicode input to the output with the required padding. - * - * This function does almost the same as the @ref __write function, but handles - * the width estimation of the Unicode input. - * - * @param __str The range [@a __first, @a __last). - * @param __precision The width to truncate the input string to, use @c -1 for - * no limit. - */ -template -_LIBCPP_HIDE_FROM_ABI auto -__write_unicode(output_iterator auto __out_it, - basic_string_view<_CharT> __str, ptrdiff_t __width, - ptrdiff_t __precision, _Fill __fill, - __format_spec::_Flags::_Alignment __alignment) - -> decltype(__out_it) { - - // This value changes when there Unicode column width limits the output - // size. - auto __last = __str.end(); - if (__width != 0 || __precision != -1) { - __format_spec::__string_alignment<_CharT> __format_traits = - __format_spec::__get_string_alignment(__str.begin(), __str.end(), - __width, __precision); - - if (__format_traits.__align) - return __write(_VSTD::move(__out_it), __str.begin(), - __format_traits.__last, __format_traits.__size, __width, - __fill, __alignment); - - // No alignment required update the output based on the precision. - // This might be the same as __str.end(). - __last = __format_traits.__last; - } - - // Copy the input to the output. The output size might be limited by the - // precision. - return _VSTD::copy(__str.begin(), __last, _VSTD::move(__out_it)); -} - } // namespace __formatter #endif //_LIBCPP_STD_VER > 17 diff --git a/contrib/llvm-project/libcxx/include/__format/formatter_bool.h b/contrib/llvm-project/libcxx/include/__format/formatter_bool.h index 4c9d3fc77473..cdb0631f87d4 100644 --- a/contrib/llvm-project/libcxx/include/__format/formatter_bool.h +++ b/contrib/llvm-project/libcxx/include/__format/formatter_bool.h @@ -47,6 +47,7 @@ public: _LIBCPP_HIDE_FROM_ABI auto format(bool __value, auto& __ctx) const -> decltype(__ctx.out()) { switch (__parser_.__type_) { + case __format_spec::__type::__default: case __format_spec::__type::__string: return __formatter::__format_bool(__value, __ctx, __parser_.__get_parsed_std_specifications(__ctx)); diff --git a/contrib/llvm-project/libcxx/include/__format/formatter_char.h b/contrib/llvm-project/libcxx/include/__format/formatter_char.h index cd54abba348a..a3ca36ec0a62 100644 --- a/contrib/llvm-project/libcxx/include/__format/formatter_char.h +++ b/contrib/llvm-project/libcxx/include/__format/formatter_char.h @@ -41,7 +41,7 @@ public: } _LIBCPP_HIDE_FROM_ABI auto format(_CharT __value, auto& __ctx) const -> decltype(__ctx.out()) { - if (__parser_.__type_ == __format_spec::__type::__char) + if (__parser_.__type_ == __format_spec::__type::__default || __parser_.__type_ == __format_spec::__type::__char) return __formatter::__format_char(__value, __ctx.out(), __parser_.__get_parsed_std_specifications(__ctx)); if constexpr (sizeof(_CharT) <= sizeof(int)) diff --git a/contrib/llvm-project/libcxx/include/__format/formatter_floating_point.h b/contrib/llvm-project/libcxx/include/__format/formatter_floating_point.h index c9f5689abd8b..90a76193196e 100644 --- a/contrib/llvm-project/libcxx/include/__format/formatter_floating_point.h +++ b/contrib/llvm-project/libcxx/include/__format/formatter_floating_point.h @@ -17,21 +17,19 @@ #include <__algorithm/min.h> #include <__algorithm/rotate.h> #include <__algorithm/transform.h> -#include <__assert> #include <__concepts/arithmetic.h> #include <__concepts/same_as.h> #include <__config> -#include <__format/format_error.h> #include <__format/format_fwd.h> -#include <__format/format_string.h> +#include <__format/format_parse_context.h> #include <__format/formatter.h> #include <__format/formatter_integral.h> +#include <__format/formatter_output.h> #include <__format/parser_std_format_spec.h> #include <__memory/allocator.h> #include <__utility/move.h> #include <__utility/unreachable.h> #include -#include #ifndef _LIBCPP_HAS_NO_LOCALIZATION # include @@ -48,7 +46,7 @@ _LIBCPP_BEGIN_NAMESPACE_STD #if _LIBCPP_STD_VER > 17 -namespace __format_spec { +namespace __formatter { template _LIBCPP_HIDE_FROM_ABI char* __to_buffer(char* __first, char* __last, _Tp __value) { @@ -164,7 +162,7 @@ public: __precision_ = _Traits::__max_fractional; } - __size_ = __format_spec::__float_buffer_size<_Fp>(__precision_); + __size_ = __formatter::__float_buffer_size<_Fp>(__precision_); if (__size_ > _Traits::__stack_buffer_size) // The allocated buffer's contents don't need initialization. __begin_ = allocator{}.allocate(__size_); @@ -233,9 +231,9 @@ _LIBCPP_HIDE_FROM_ABI __float_result __format_buffer_default(const __float_buffe char* __integral) { __float_result __result; __result.__integral = __integral; - __result.__last = __format_spec::__to_buffer(__integral, __buffer.end(), __value); + __result.__last = __formatter::__to_buffer(__integral, __buffer.end(), __value); - __result.__exponent = __format_spec::__find_exponent(__result.__integral, __result.__last); + __result.__exponent = __formatter::__find_exponent(__result.__integral, __result.__last); // Constrains: // - There's at least one decimal digit before the radix point. @@ -264,9 +262,9 @@ _LIBCPP_HIDE_FROM_ABI __float_result __format_buffer_hexadecimal_lower_case(cons __float_result __result; __result.__integral = __integral; if (__precision == -1) - __result.__last = __format_spec::__to_buffer(__integral, __buffer.end(), __value, chars_format::hex); + __result.__last = __formatter::__to_buffer(__integral, __buffer.end(), __value, chars_format::hex); else - __result.__last = __format_spec::__to_buffer(__integral, __buffer.end(), __value, chars_format::hex, __precision); + __result.__last = __formatter::__to_buffer(__integral, __buffer.end(), __value, chars_format::hex, __precision); // H = one or more hex-digits // S = sign @@ -315,7 +313,7 @@ _LIBCPP_HIDE_FROM_ABI __float_result __format_buffer_hexadecimal_upper_case(cons _Tp __value, int __precision, char* __integral) { __float_result __result = - __format_spec::__format_buffer_hexadecimal_lower_case(__buffer, __value, __precision, __integral); + __formatter::__format_buffer_hexadecimal_lower_case(__buffer, __value, __precision, __integral); _VSTD::transform(__result.__integral, __result.__exponent, __result.__integral, __hex_to_upper); *__result.__exponent = 'P'; return __result; @@ -328,13 +326,13 @@ _LIBCPP_HIDE_FROM_ABI __float_result __format_buffer_scientific_lower_case(const __float_result __result; __result.__integral = __integral; __result.__last = - __format_spec::__to_buffer(__integral, __buffer.end(), __value, chars_format::scientific, __precision); + __formatter::__to_buffer(__integral, __buffer.end(), __value, chars_format::scientific, __precision); char* __first = __integral + 1; _LIBCPP_ASSERT(__first != __result.__last, "No exponent present"); if (*__first == '.') { __result.__radix_point = __first; - __result.__exponent = __format_spec::__find_exponent(__first + 1, __result.__last); + __result.__exponent = __formatter::__find_exponent(__first + 1, __result.__last); } else { __result.__radix_point = __result.__last; __result.__exponent = __first; @@ -354,7 +352,7 @@ _LIBCPP_HIDE_FROM_ABI __float_result __format_buffer_scientific_upper_case(const _Tp __value, int __precision, char* __integral) { __float_result __result = - __format_spec::__format_buffer_scientific_lower_case(__buffer, __value, __precision, __integral); + __formatter::__format_buffer_scientific_lower_case(__buffer, __value, __precision, __integral); *__result.__exponent = 'E'; return __result; } @@ -364,7 +362,7 @@ _LIBCPP_HIDE_FROM_ABI __float_result __format_buffer_fixed(const __float_buffer< int __precision, char* __integral) { __float_result __result; __result.__integral = __integral; - __result.__last = __format_spec::__to_buffer(__integral, __buffer.end(), __value, chars_format::fixed, __precision); + __result.__last = __formatter::__to_buffer(__integral, __buffer.end(), __value, chars_format::fixed, __precision); // When there's no precision there's no radix point. // Else the radix point is placed at __precision + 1 from the end. @@ -390,14 +388,14 @@ _LIBCPP_HIDE_FROM_ABI __float_result __format_buffer_general_lower_case(__float_ __float_result __result; __result.__integral = __integral; - __result.__last = __format_spec::__to_buffer(__integral, __buffer.end(), __value, chars_format::general, __precision); + __result.__last = __formatter::__to_buffer(__integral, __buffer.end(), __value, chars_format::general, __precision); char* __first = __integral + 1; if (__first == __result.__last) { __result.__radix_point = __result.__last; __result.__exponent = __result.__last; } else { - __result.__exponent = __format_spec::__find_exponent(__first, __result.__last); + __result.__exponent = __formatter::__find_exponent(__first, __result.__last); if (__result.__exponent != __result.__last) // In scientific mode if there's a radix point it will always be after // the first digit. (This is the position __first points at). @@ -423,19 +421,79 @@ _LIBCPP_HIDE_FROM_ABI __float_result __format_buffer_general_lower_case(__float_ template _LIBCPP_HIDE_FROM_ABI __float_result __format_buffer_general_upper_case(__float_buffer<_Fp>& __buffer, _Tp __value, int __precision, char* __integral) { - __float_result __result = - __format_spec::__format_buffer_general_lower_case(__buffer, __value, __precision, __integral); + __float_result __result = __formatter::__format_buffer_general_lower_case(__buffer, __value, __precision, __integral); if (__result.__exponent != __result.__last) *__result.__exponent = 'E'; return __result; } -# ifndef _LIBCPP_HAS_NO_LOCALIZATION +/// Fills the buffer with the data based on the requested formatting. +/// +/// This function, when needed, turns the characters to upper case and +/// determines the "interesting" locations which are returned to the caller. +/// +/// This means the caller never has to convert the contents of the buffer to +/// upper case or search for radix points and the location of the exponent. +/// This gives a bit of overhead. The original code didn't do that, but due +/// to the number of possible additional work needed to turn this number to +/// the proper output the code was littered with tests for upper cases and +/// searches for radix points and exponents. +/// - When a precision larger than the type's precision is selected +/// additional zero characters need to be written before the exponent. +/// - alternate form needs to add a radix point when not present. +/// - localization needs to do grouping in the integral part. +template +// TODO FMT _Fp should just be _Tp when to_chars has proper long double support. +_LIBCPP_HIDE_FROM_ABI __float_result __format_buffer( + __float_buffer<_Fp>& __buffer, + _Tp __value, + bool __negative, + bool __has_precision, + __format_spec::__sign __sign, + __format_spec::__type __type) { + char* __first = __formatter::__insert_sign(__buffer.begin(), __negative, __sign); + switch (__type) { + case __format_spec::__type::__default: + return __formatter::__format_buffer_default(__buffer, __value, __first); + + case __format_spec::__type::__hexfloat_lower_case: + return __formatter::__format_buffer_hexadecimal_lower_case( + __buffer, __value, __has_precision ? __buffer.__precision() : -1, __first); + + case __format_spec::__type::__hexfloat_upper_case: + return __formatter::__format_buffer_hexadecimal_upper_case( + __buffer, __value, __has_precision ? __buffer.__precision() : -1, __first); + + case __format_spec::__type::__scientific_lower_case: + return __formatter::__format_buffer_scientific_lower_case(__buffer, __value, __buffer.__precision(), __first); + + case __format_spec::__type::__scientific_upper_case: + return __formatter::__format_buffer_scientific_upper_case(__buffer, __value, __buffer.__precision(), __first); + + case __format_spec::__type::__fixed_lower_case: + case __format_spec::__type::__fixed_upper_case: + return __formatter::__format_buffer_fixed(__buffer, __value, __buffer.__precision(), __first); + + case __format_spec::__type::__general_lower_case: + return __formatter::__format_buffer_general_lower_case(__buffer, __value, __buffer.__precision(), __first); + + case __format_spec::__type::__general_upper_case: + return __formatter::__format_buffer_general_upper_case(__buffer, __value, __buffer.__precision(), __first); + + default: + _LIBCPP_ASSERT(false, "The parser should have validated the type"); + __libcpp_unreachable(); + } +} + +# ifndef _LIBCPP_HAS_NO_LOCALIZATION template -_LIBCPP_HIDE_FROM_ABI _OutIt __format_locale_specific_form(_OutIt __out_it, const __float_buffer<_Fp>& __buffer, - const __float_result& __result, _VSTD::locale __loc, - size_t __width, _Flags::_Alignment __alignment, - _CharT __fill) { +_LIBCPP_HIDE_FROM_ABI _OutIt __format_locale_specific_form( + _OutIt __out_it, + const __float_buffer<_Fp>& __buffer, + const __float_result& __result, + _VSTD::locale __loc, + __format_spec::__parsed_specifications<_CharT> __specs) { const auto& __np = use_facet>(__loc); string __grouping = __np.grouping(); char* __first = __result.__integral; @@ -450,26 +508,27 @@ _LIBCPP_HIDE_FROM_ABI _OutIt __format_locale_specific_form(_OutIt __out_it, cons __grouping = __formatter::__determine_grouping(__digits, __grouping); } - size_t __size = __result.__last - __buffer.begin() + // Formatted string - __buffer.__num_trailing_zeros() + // Not yet rendered zeros - __grouping.size() - // Grouping contains one - !__grouping.empty(); // additional character + ptrdiff_t __size = + __result.__last - __buffer.begin() + // Formatted string + __buffer.__num_trailing_zeros() + // Not yet rendered zeros + __grouping.size() - // Grouping contains one + !__grouping.empty(); // additional character - __formatter::__padding_size_result __padding = {0, 0}; - bool __zero_padding = __alignment == _Flags::_Alignment::__default; - if (__size < __width) { + __formatter::__padding_size_result __padding = {0, 0}; + bool __zero_padding = __specs.__alignment_ == __format_spec::__alignment::__zero_padding; + if (__size < __specs.__width_) { if (__zero_padding) { - __alignment = _Flags::_Alignment::__right; - __fill = _CharT('0'); + __specs.__alignment_ = __format_spec::__alignment::__right; + __specs.__fill_ = _CharT('0'); } - __padding = __formatter::__padding_size(__size, __width, __alignment); + __padding = __formatter::__padding_size(__size, __specs.__width_, __specs.__alignment_); } // sign and (zero padding or alignment) if (__zero_padding && __first != __buffer.begin()) *__out_it++ = *__buffer.begin(); - __out_it = _VSTD::fill_n(_VSTD::move(__out_it), __padding.__before, __fill); + __out_it = _VSTD::fill_n(_VSTD::move(__out_it), __padding.__before_, __specs.__fill_); if (!__zero_padding && __first != __buffer.begin()) *__out_it++ = *__buffer.begin(); @@ -510,198 +569,148 @@ _LIBCPP_HIDE_FROM_ABI _OutIt __format_locale_specific_form(_OutIt __out_it, cons __out_it = _VSTD::copy(__result.__exponent, __result.__last, _VSTD::move(__out_it)); // alignment - return _VSTD::fill_n(_VSTD::move(__out_it), __padding.__after, __fill); + return _VSTD::fill_n(_VSTD::move(__out_it), __padding.__after_, __specs.__fill_); +} +# endif // _LIBCPP_HAS_NO_LOCALIZATION + +template +_LIBCPP_HIDE_FROM_ABI _OutIt __format_floating_point_non_finite( + _OutIt __out_it, __format_spec::__parsed_specifications<_CharT> __specs, bool __negative, bool __isnan) { + char __buffer[4]; + char* __last = __formatter::__insert_sign(__buffer, __negative, __specs.__std_.__sign_); + + // to_chars can return inf, infinity, nan, and nan(n-char-sequence). + // The format library requires inf and nan. + // All in one expression to avoid dangling references. + bool __upper_case = + __specs.__std_.__type_ == __format_spec::__type::__hexfloat_upper_case || + __specs.__std_.__type_ == __format_spec::__type::__scientific_upper_case || + __specs.__std_.__type_ == __format_spec::__type::__fixed_upper_case || + __specs.__std_.__type_ == __format_spec::__type::__general_upper_case; + __last = _VSTD::copy_n(&("infnanINFNAN"[6 * __upper_case + 3 * __isnan]), 3, __last); + + // [format.string.std]/13 + // A zero (0) character preceding the width field pads the field with + // leading zeros (following any indication of sign or base) to the field + // width, except when applied to an infinity or NaN. + if (__specs.__alignment_ == __format_spec::__alignment::__zero_padding) + __specs.__alignment_ = __format_spec::__alignment::__right; + + return __formatter::__write(__buffer, __last, _VSTD::move(__out_it), __specs); } -# endif // _LIBCPP_HAS_NO_LOCALIZATION - -template <__formatter::__char_type _CharT> -class _LIBCPP_TEMPLATE_VIS __formatter_floating_point : public __parser_floating_point<_CharT> { -public: - template - _LIBCPP_HIDE_FROM_ABI auto format(_Tp __value, auto& __ctx) -> decltype(__ctx.out()) { - if (this->__width_needs_substitution()) - this->__substitute_width_arg_id(__ctx.arg(this->__width)); - - bool __negative = _VSTD::signbit(__value); - - if (!_VSTD::isfinite(__value)) [[unlikely]] - return __format_non_finite(__ctx.out(), __negative, _VSTD::isnan(__value)); - - bool __has_precision = this->__has_precision_field(); - if (this->__precision_needs_substitution()) - this->__substitute_precision_arg_id(__ctx.arg(this->__precision)); - - // Depending on the std-format-spec string the sign and the value - // might not be outputted together: - // - zero-padding may insert additional '0' characters. - // Therefore the value is processed as a non negative value. - // The function @ref __insert_sign will insert a '-' when the value was - // negative. - - if (__negative) - __value = _VSTD::copysign(__value, +1.0); - - // TODO FMT _Fp should just be _Tp when to_chars has proper long double support. - using _Fp = conditional_t, double, _Tp>; - // Force the type of the precision to avoid -1 to become an unsigned value. - __float_buffer<_Fp> __buffer(__has_precision ? int(this->__precision) : -1); - __float_result __result = __format_buffer(__buffer, __value, __negative, __has_precision); - - if (this->__alternate_form && __result.__radix_point == __result.__last) { - *__result.__last++ = '.'; - - // When there is an exponent the point needs to be moved before the - // exponent. When there's no exponent the rotate does nothing. Since - // rotate tests whether the operation is a nop, call it unconditionally. - _VSTD::rotate(__result.__exponent, __result.__last - 1, __result.__last); - __result.__radix_point = __result.__exponent; - - // The radix point is always placed before the exponent. - // - No exponent needs to point to the new last. - // - An exponent needs to move one position to the right. - // So it's safe to increment the value unconditionally. - ++__result.__exponent; - } +template +_LIBCPP_HIDE_FROM_ABI auto +__format_floating_point(_Tp __value, auto& __ctx, __format_spec::__parsed_specifications<_CharT> __specs) + -> decltype(__ctx.out()) { + bool __negative = _VSTD::signbit(__value); -# ifndef _LIBCPP_HAS_NO_LOCALIZATION - if (this->__locale_specific_form) - return __format_spec::__format_locale_specific_form(__ctx.out(), __buffer, __result, __ctx.locale(), - this->__width, this->__alignment, this->__fill); -# endif - - ptrdiff_t __size = __result.__last - __buffer.begin(); - int __num_trailing_zeros = __buffer.__num_trailing_zeros(); - if (__size + __num_trailing_zeros >= this->__width) { - if (__num_trailing_zeros && __result.__exponent != __result.__last) - // Insert trailing zeros before exponent character. - return _VSTD::copy(__result.__exponent, __result.__last, - _VSTD::fill_n(_VSTD::copy(__buffer.begin(), __result.__exponent, __ctx.out()), - __num_trailing_zeros, _CharT('0'))); - - return _VSTD::fill_n(_VSTD::copy(__buffer.begin(), __result.__last, __ctx.out()), __num_trailing_zeros, - _CharT('0')); - } + if (!_VSTD::isfinite(__value)) [[unlikely]] + return __formatter::__format_floating_point_non_finite(__ctx.out(), __specs, __negative, _VSTD::isnan(__value)); - auto __out_it = __ctx.out(); - char* __first = __buffer.begin(); - if (this->__alignment == _Flags::_Alignment::__default) { - // When there is a sign output it before the padding. Note the __size - // doesn't need any adjustment, regardless whether the sign is written - // here or in __formatter::__write. - if (__first != __result.__integral) - *__out_it++ = *__first++; - // After the sign is written, zero padding is the same a right alignment - // with '0'. - this->__alignment = _Flags::_Alignment::__right; - this->__fill = _CharT('0'); - } + // Depending on the std-format-spec string the sign and the value + // might not be outputted together: + // - zero-padding may insert additional '0' characters. + // Therefore the value is processed as a non negative value. + // The function @ref __insert_sign will insert a '-' when the value was + // negative. - if (__num_trailing_zeros) - return __formatter::__write(_VSTD::move(__out_it), __first, __result.__last, __size, this->__width, this->__fill, - this->__alignment, __result.__exponent, __num_trailing_zeros); + if (__negative) + __value = -__value; - return __formatter::__write(_VSTD::move(__out_it), __first, __result.__last, __size, this->__width, this->__fill, - this->__alignment); + // TODO FMT _Fp should just be _Tp when to_chars has proper long double support. + using _Fp = conditional_t, double, _Tp>; + // Force the type of the precision to avoid -1 to become an unsigned value. + __float_buffer<_Fp> __buffer(__specs.__precision_); + __float_result __result = __formatter::__format_buffer( + __buffer, __value, __negative, (__specs.__has_precision()), __specs.__std_.__sign_, __specs.__std_.__type_); + + if (__specs.__std_.__alternate_form_ && __result.__radix_point == __result.__last) { + *__result.__last++ = '.'; + + // When there is an exponent the point needs to be moved before the + // exponent. When there's no exponent the rotate does nothing. Since + // rotate tests whether the operation is a nop, call it unconditionally. + _VSTD::rotate(__result.__exponent, __result.__last - 1, __result.__last); + __result.__radix_point = __result.__exponent; + + // The radix point is always placed before the exponent. + // - No exponent needs to point to the new last. + // - An exponent needs to move one position to the right. + // So it's safe to increment the value unconditionally. + ++__result.__exponent; } -private: - template - _LIBCPP_HIDE_FROM_ABI _OutIt __format_non_finite(_OutIt __out_it, bool __negative, bool __isnan) { - char __buffer[4]; - char* __last = __insert_sign(__buffer, __negative, this->__sign); - - // to_char can return inf, infinity, nan, and nan(n-char-sequence). - // The format library requires inf and nan. - // All in one expression to avoid dangling references. - __last = _VSTD::copy_n(&("infnanINFNAN"[6 * (this->__type == _Flags::_Type::__float_hexadecimal_upper_case || - this->__type == _Flags::_Type::__scientific_upper_case || - this->__type == _Flags::_Type::__fixed_upper_case || - this->__type == _Flags::_Type::__general_upper_case) + - 3 * __isnan]), - 3, __last); - - // [format.string.std]/13 - // A zero (0) character preceding the width field pads the field with - // leading zeros (following any indication of sign or base) to the field - // width, except when applied to an infinity or NaN. - if (this->__alignment == _Flags::_Alignment::__default) - this->__alignment = _Flags::_Alignment::__right; - - ptrdiff_t __size = __last - __buffer; - if (__size >= this->__width) - return _VSTD::copy_n(__buffer, __size, _VSTD::move(__out_it)); - - return __formatter::__write(_VSTD::move(__out_it), __buffer, __last, __size, this->__width, this->__fill, - this->__alignment); +# ifndef _LIBCPP_HAS_NO_LOCALIZATION + if (__specs.__std_.__locale_specific_form_) + return __formatter::__format_locale_specific_form(__ctx.out(), __buffer, __result, __ctx.locale(), __specs); +# endif + + ptrdiff_t __size = __result.__last - __buffer.begin(); + int __num_trailing_zeros = __buffer.__num_trailing_zeros(); + if (__size + __num_trailing_zeros >= __specs.__width_) { + if (__num_trailing_zeros && __result.__exponent != __result.__last) + // Insert trailing zeros before exponent character. + return _VSTD::copy( + __result.__exponent, + __result.__last, + _VSTD::fill_n( + _VSTD::copy(__buffer.begin(), __result.__exponent, __ctx.out()), __num_trailing_zeros, _CharT('0'))); + + return _VSTD::fill_n( + _VSTD::copy(__buffer.begin(), __result.__last, __ctx.out()), __num_trailing_zeros, _CharT('0')); } - /// Fills the buffer with the data based on the requested formatting. - /// - /// This function, when needed, turns the characters to upper case and - /// determines the "interesting" locations which are returned to the caller. - /// - /// This means the caller never has to convert the contents of the buffer to - /// upper case or search for radix points and the location of the exponent. - /// This gives a bit of overhead. The original code didn't do that, but due - /// to the number of possible additional work needed to turn this number to - /// the proper output the code was littered with tests for upper cases and - /// searches for radix points and exponents. - /// - When a precision larger than the type's precision is selected - /// additional zero characters need to be written before the exponent. - /// - alternate form needs to add a radix point when not present. - /// - localization needs to do grouping in the integral part. - template - // TODO FMT _Fp should just be _Tp when to_chars has proper long double support. - _LIBCPP_HIDE_FROM_ABI __float_result __format_buffer(__float_buffer<_Fp>& __buffer, _Tp __value, bool __negative, - bool __has_precision) { - char* __first = __insert_sign(__buffer.begin(), __negative, this->__sign); - switch (this->__type) { - case _Flags::_Type::__default: - return __format_spec::__format_buffer_default(__buffer, __value, __first); - - case _Flags::_Type::__float_hexadecimal_lower_case: - return __format_spec::__format_buffer_hexadecimal_lower_case( - __buffer, __value, __has_precision ? __buffer.__precision() : -1, __first); - - case _Flags::_Type::__float_hexadecimal_upper_case: - return __format_spec::__format_buffer_hexadecimal_upper_case( - __buffer, __value, __has_precision ? __buffer.__precision() : -1, __first); - - case _Flags::_Type::__scientific_lower_case: - return __format_spec::__format_buffer_scientific_lower_case(__buffer, __value, __buffer.__precision(), __first); + auto __out_it = __ctx.out(); + char* __first = __buffer.begin(); + if (__specs.__alignment_ == __format_spec::__alignment ::__zero_padding) { + // When there is a sign output it before the padding. Note the __size + // doesn't need any adjustment, regardless whether the sign is written + // here or in __formatter::__write. + if (__first != __result.__integral) + *__out_it++ = *__first++; + // After the sign is written, zero padding is the same a right alignment + // with '0'. + __specs.__alignment_ = __format_spec::__alignment::__right; + __specs.__fill_ = _CharT('0'); + } - case _Flags::_Type::__scientific_upper_case: - return __format_spec::__format_buffer_scientific_upper_case(__buffer, __value, __buffer.__precision(), __first); + if (__num_trailing_zeros) + return __formatter::__write_using_trailing_zeros( + __first, __result.__last, _VSTD::move(__out_it), __specs, __size, __result.__exponent, __num_trailing_zeros); - case _Flags::_Type::__fixed_lower_case: - case _Flags::_Type::__fixed_upper_case: - return __format_spec::__format_buffer_fixed(__buffer, __value, __buffer.__precision(), __first); + return __formatter::__write(__first, __result.__last, _VSTD::move(__out_it), __specs, __size); +} - case _Flags::_Type::__general_lower_case: - return __format_spec::__format_buffer_general_lower_case(__buffer, __value, __buffer.__precision(), __first); +} // namespace __formatter - case _Flags::_Type::__general_upper_case: - return __format_spec::__format_buffer_general_upper_case(__buffer, __value, __buffer.__precision(), __first); +template <__formatter::__char_type _CharT> +struct _LIBCPP_TEMPLATE_VIS __formatter_floating_point { +public: + _LIBCPP_HIDE_FROM_ABI constexpr auto + parse(basic_format_parse_context<_CharT>& __parse_ctx) -> decltype(__parse_ctx.begin()) { + auto __result = __parser_.__parse(__parse_ctx, __format_spec::__fields_floating_point); + __format_spec::__process_parsed_floating_point(__parser_); + return __result; + } - default: - _LIBCPP_ASSERT(false, "The parser should have validated the type"); - __libcpp_unreachable(); - } + template + _LIBCPP_HIDE_FROM_ABI auto format(_Tp __value, auto& __ctx) const -> decltype(__ctx.out()) { + return __formatter::__format_floating_point(__value, __ctx, __parser_.__get_parsed_std_specifications(__ctx)); } -}; -} //namespace __format_spec + __format_spec::__parser<_CharT> __parser_; +}; template <__formatter::__char_type _CharT> struct _LIBCPP_TEMPLATE_VIS _LIBCPP_AVAILABILITY_FORMAT formatter - : public __format_spec::__formatter_floating_point<_CharT> {}; + : public __formatter_floating_point<_CharT> {}; template <__formatter::__char_type _CharT> struct _LIBCPP_TEMPLATE_VIS _LIBCPP_AVAILABILITY_FORMAT formatter - : public __format_spec::__formatter_floating_point<_CharT> {}; + : public __formatter_floating_point<_CharT> {}; template <__formatter::__char_type _CharT> struct _LIBCPP_TEMPLATE_VIS _LIBCPP_AVAILABILITY_FORMAT formatter - : public __format_spec::__formatter_floating_point<_CharT> {}; + : public __formatter_floating_point<_CharT> {}; #endif //_LIBCPP_STD_VER > 17 diff --git a/contrib/llvm-project/libcxx/include/__format/formatter_integer.h b/contrib/llvm-project/libcxx/include/__format/formatter_integer.h index 5d11f8d1d990..0281b4f2fa67 100644 --- a/contrib/llvm-project/libcxx/include/__format/formatter_integer.h +++ b/contrib/llvm-project/libcxx/include/__format/formatter_integer.h @@ -13,23 +13,18 @@ #include <__availability> #include <__concepts/arithmetic.h> #include <__config> -#include <__format/format_error.h> // TODO FMT Remove after adding 128-bit support #include <__format/format_fwd.h> #include <__format/format_parse_context.h> #include <__format/formatter.h> #include <__format/formatter_integral.h> #include <__format/formatter_output.h> #include <__format/parser_std_format_spec.h> -#include // TODO FMT Remove after adding 128-bit support #include #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) # pragma GCC system_header #endif -_LIBCPP_PUSH_MACROS // TODO FMT Remove after adding 128-bit support -#include <__undef_macros> - _LIBCPP_BEGIN_NAMESPACE_STD #if _LIBCPP_STD_VER > 17 @@ -79,18 +74,7 @@ struct _LIBCPP_TEMPLATE_VIS _LIBCPP_AVAILABILITY_FORMAT formatter struct _LIBCPP_TEMPLATE_VIS _LIBCPP_AVAILABILITY_FORMAT formatter<__int128_t, _CharT> - : public __formatter_integer<_CharT> { - using _Base = __formatter_integer<_CharT>; - - _LIBCPP_HIDE_FROM_ABI auto format(__int128_t __value, auto& __ctx) const -> decltype(__ctx.out()) { - // TODO FMT Implement full 128 bit support. - using _To = long long; - if (__value < numeric_limits<_To>::min() || __value > numeric_limits<_To>::max()) - std::__throw_format_error("128-bit value is outside of implemented range"); - - return _Base::format(static_cast<_To>(__value), __ctx); - } -}; + : public __formatter_integer<_CharT> {}; # endif // Unsigned integral types. @@ -112,24 +96,11 @@ struct _LIBCPP_TEMPLATE_VIS _LIBCPP_AVAILABILITY_FORMAT formatter struct _LIBCPP_TEMPLATE_VIS _LIBCPP_AVAILABILITY_FORMAT formatter<__uint128_t, _CharT> - : public __formatter_integer<_CharT> { - using _Base = __formatter_integer<_CharT>; - - _LIBCPP_HIDE_FROM_ABI auto format(__uint128_t __value, auto& __ctx) const -> decltype(__ctx.out()) { - // TODO FMT Implement full 128 bit support. - using _To = unsigned long long; - if (__value < numeric_limits<_To>::min() || __value > numeric_limits<_To>::max()) - std::__throw_format_error("128-bit value is outside of implemented range"); - - return _Base::format(static_cast<_To>(__value), __ctx); - } -}; + : public __formatter_integer<_CharT> {}; # endif #endif //_LIBCPP_STD_VER > 17 _LIBCPP_END_NAMESPACE_STD -_LIBCPP_POP_MACROS - #endif // _LIBCPP___FORMAT_FORMATTER_INTEGER_H diff --git a/contrib/llvm-project/libcxx/include/__format/formatter_integral.h b/contrib/llvm-project/libcxx/include/__format/formatter_integral.h index 4ad6de0ec66f..d6fa5ec18eb8 100644 --- a/contrib/llvm-project/libcxx/include/__format/formatter_integral.h +++ b/contrib/llvm-project/libcxx/include/__format/formatter_integral.h @@ -207,10 +207,6 @@ _LIBCPP_HIDE_FROM_ABI auto __format_integer( char* __end, const char* __prefix, int __base) -> decltype(__ctx.out()) { - _LIBCPP_ASSERT( - __specs.__alignment_ != __format_spec::__alignment::__default, - "the caller should adjust the default to the value required by the type"); - char* __first = __formatter::__insert_sign(__begin, __negative, __specs.__std_.__sign_); if (__specs.__std_.__alternate_form_ && __prefix) while (*__prefix) @@ -280,6 +276,7 @@ _LIBCPP_HIDE_FROM_ABI auto __format_integer( return __formatter::__format_integer( __value, __ctx, __specs, __negative, __array.begin(), __array.end(), __value != 0 ? "0" : nullptr, 8); } + case __format_spec::__type::__default: case __format_spec::__type::__decimal: { array()> __array; return __formatter::__format_integer( diff --git a/contrib/llvm-project/libcxx/include/__format/formatter_output.h b/contrib/llvm-project/libcxx/include/__format/formatter_output.h index ab016f6f1610..c59cbbeeb5dd 100644 --- a/contrib/llvm-project/libcxx/include/__format/formatter_output.h +++ b/contrib/llvm-project/libcxx/include/__format/formatter_output.h @@ -33,8 +33,8 @@ _LIBCPP_BEGIN_NAMESPACE_STD namespace __formatter { -_LIBCPP_HIDE_FROM_ABI constexpr char __hex_to_upper(char c) { - switch (c) { +_LIBCPP_HIDE_FROM_ABI constexpr char __hex_to_upper(char __c) { + switch (__c) { case 'a': return 'A'; case 'b': @@ -48,27 +48,22 @@ _LIBCPP_HIDE_FROM_ABI constexpr char __hex_to_upper(char c) { case 'f': return 'F'; } - return c; + return __c; } -// TODO FMT remove _v2 suffix. -struct _LIBCPP_TYPE_VIS __padding_size_result_v2 { +struct _LIBCPP_TYPE_VIS __padding_size_result { size_t __before_; size_t __after_; }; -// TODO FMT remove _v2 suffix. -_LIBCPP_HIDE_FROM_ABI constexpr __padding_size_result_v2 __padding_size_v2(size_t __size, size_t __width, - __format_spec::__alignment __align) { +_LIBCPP_HIDE_FROM_ABI constexpr __padding_size_result +__padding_size(size_t __size, size_t __width, __format_spec::__alignment __align) { _LIBCPP_ASSERT(__width > __size, "don't call this function when no padding is required"); - _LIBCPP_ASSERT(__align != __format_spec::__alignment::__default, - "the caller should adjust the default to the value required by the type"); _LIBCPP_ASSERT(__align != __format_spec::__alignment::__zero_padding, "the caller should have handled the zero-padding"); size_t __fill = __width - __size; switch (__align) { - case __format_spec::__alignment::__default: case __format_spec::__alignment::__zero_padding: __libcpp_unreachable(); @@ -83,6 +78,7 @@ _LIBCPP_HIDE_FROM_ABI constexpr __padding_size_result_v2 __padding_size_v2(size_ size_t __after = __fill - __before; return {__before, __after}; } + case __format_spec::__alignment::__default: case __format_spec::__alignment::__right: return {__fill, 0}; } @@ -93,14 +89,11 @@ template _LIBCPP_HIDE_FROM_ABI _OutIt __write_using_decimal_separators(_OutIt __out_it, const char* __begin, const char* __first, const char* __last, string&& __grouping, _CharT __sep, __format_spec::__parsed_specifications<_CharT> __specs) { - _LIBCPP_ASSERT(__specs.__alignment_ != __format_spec::__alignment::__default, - "the caller should adjust the default to the value required by the type"); - int __size = (__first - __begin) + // [sign][prefix] (__last - __first) + // data (__grouping.size() - 1); // number of separator characters - __padding_size_result_v2 __padding = {0, 0}; + __padding_size_result __padding = {0, 0}; if (__specs.__alignment_ == __format_spec::__alignment::__zero_padding) { // Write [sign][prefix]. __out_it = _VSTD::copy(__begin, __first, _VSTD::move(__out_it)); @@ -113,7 +106,7 @@ _LIBCPP_HIDE_FROM_ABI _OutIt __write_using_decimal_separators(_OutIt __out_it, c } else { if (__specs.__width_ > __size) { // Determine padding and write padding. - __padding = __padding_size_v2(__size, __specs.__width_, __specs.__alignment_); + __padding = __padding_size(__size, __specs.__width_, __specs.__alignment_); __out_it = _VSTD::fill_n(_VSTD::move(__out_it), __padding.__before_, __specs.__fill_); } @@ -189,8 +182,7 @@ _LIBCPP_HIDE_FROM_ABI auto __write(const _CharT* __first, const _CharT* __last, if (__size >= __specs.__width_) return _VSTD::copy(__first, __last, _VSTD::move(__out_it)); - __padding_size_result_v2 __padding = - __formatter::__padding_size_v2(__size, __specs.__width_, __specs.__std_.__alignment_); + __padding_size_result __padding = __formatter::__padding_size(__size, __specs.__width_, __specs.__std_.__alignment_); __out_it = _VSTD::fill_n(_VSTD::move(__out_it), __padding.__before_, __specs.__fill_); __out_it = _VSTD::copy(__first, __last, _VSTD::move(__out_it)); return _VSTD::fill_n(_VSTD::move(__out_it), __padding.__after_, __specs.__fill_); @@ -216,12 +208,41 @@ _LIBCPP_HIDE_FROM_ABI auto __write_transformed(const _CharT* __first, const _Cha if (__size >= __specs.__width_) return _VSTD::transform(__first, __last, _VSTD::move(__out_it), __op); - __padding_size_result_v2 __padding = __padding_size_v2(__size, __specs.__width_, __specs.__alignment_); + __padding_size_result __padding = __padding_size(__size, __specs.__width_, __specs.__alignment_); __out_it = _VSTD::fill_n(_VSTD::move(__out_it), __padding.__before_, __specs.__fill_); __out_it = _VSTD::transform(__first, __last, _VSTD::move(__out_it), __op); return _VSTD::fill_n(_VSTD::move(__out_it), __padding.__after_, __specs.__fill_); } +/// Writes additional zero's for the precision before the exponent. +/// This is used when the precision requested in the format string is larger +/// than the maximum precision of the floating-point type. These precision +/// digits are always 0. +/// +/// \param __exponent The location of the exponent character. +/// \param __num_trailing_zeros The number of 0's to write before the exponent +/// character. +template +_LIBCPP_HIDE_FROM_ABI auto __write_using_trailing_zeros( + const _CharT* __first, + const _CharT* __last, + output_iterator auto __out_it, + __format_spec::__parsed_specifications<_ParserCharT> __specs, + size_t __size, + const _CharT* __exponent, + size_t __num_trailing_zeros) -> decltype(__out_it) { + _LIBCPP_ASSERT(__first <= __last, "Not a valid range"); + _LIBCPP_ASSERT(__num_trailing_zeros > 0, "The overload not writing trailing zeros should have been used"); + + __padding_size_result __padding = + __padding_size(__size + __num_trailing_zeros, __specs.__width_, __specs.__alignment_); + __out_it = _VSTD::fill_n(_VSTD::move(__out_it), __padding.__before_, __specs.__fill_); + __out_it = _VSTD::copy(__first, __exponent, _VSTD::move(__out_it)); + __out_it = _VSTD::fill_n(_VSTD::move(__out_it), __num_trailing_zeros, _CharT('0')); + __out_it = _VSTD::copy(__exponent, __last, _VSTD::move(__out_it)); + return _VSTD::fill_n(_VSTD::move(__out_it), __padding.__after_, __specs.__fill_); +} + # ifndef _LIBCPP_HAS_NO_UNICODE template _LIBCPP_HIDE_FROM_ABI auto __write_unicode_no_precision(basic_string_view<_CharT> __str, diff --git a/contrib/llvm-project/libcxx/include/__format/parser_std_format_spec.h b/contrib/llvm-project/libcxx/include/__format/parser_std_format_spec.h index 739bdf457e40..034fc55a44dc 100644 --- a/contrib/llvm-project/libcxx/include/__format/parser_std_format_spec.h +++ b/contrib/llvm-project/libcxx/include/__format/parser_std_format_spec.h @@ -44,168 +44,6 @@ _LIBCPP_BEGIN_NAMESPACE_STD namespace __format_spec { -/** - * Contains the flags for the std-format-spec. - * - * Some format-options can only be used for specific C++ types and may depend on - * the selected format-type. - * * The C++type filtering can be done using the proper policies for - * @ref __parser_std. - * * The format-type filtering needs to be done post parsing in the parser - * derived from @ref __parser_std. - */ -_LIBCPP_PACKED_BYTE_FOR_AIX -class _LIBCPP_TYPE_VIS _Flags { -public: - enum class _LIBCPP_ENUM_VIS _Alignment : uint8_t { - /** - * No alignment is set in the format string. - * - * Zero-padding is ignored when an alignment is selected. - * The default alignment depends on the selected format-type. - */ - __default, - __left, - __center, - __right - }; - enum class _LIBCPP_ENUM_VIS _Sign : uint8_t { - /** - * No sign is set in the format string. - * - * The sign isn't allowed for certain format-types. By using this value - * it's possible to detect whether or not the user explicitly set the sign - * flag. For formatting purposes it behaves the same as @ref __minus. - */ - __default, - __minus, - __plus, - __space - }; - - _Alignment __alignment : 2 {_Alignment::__default}; - _Sign __sign : 2 {_Sign::__default}; - uint8_t __alternate_form : 1 {false}; - uint8_t __zero_padding : 1 {false}; - uint8_t __locale_specific_form : 1 {false}; - - enum class _LIBCPP_ENUM_VIS _Type : uint8_t { - __default, - __string, - __binary_lower_case, - __binary_upper_case, - __octal, - __decimal, - __hexadecimal_lower_case, - __hexadecimal_upper_case, - __pointer, - __char, - __float_hexadecimal_lower_case, - __float_hexadecimal_upper_case, - __scientific_lower_case, - __scientific_upper_case, - __fixed_lower_case, - __fixed_upper_case, - __general_lower_case, - __general_upper_case - }; - - _Type __type{_Type::__default}; -}; -_LIBCPP_PACKED_BYTE_FOR_AIX_END - -namespace __detail { -template -_LIBCPP_HIDE_FROM_ABI constexpr bool -__parse_alignment(_CharT __c, _Flags& __flags) noexcept { - switch (__c) { - case _CharT('<'): - __flags.__alignment = _Flags::_Alignment::__left; - return true; - - case _CharT('^'): - __flags.__alignment = _Flags::_Alignment::__center; - return true; - - case _CharT('>'): - __flags.__alignment = _Flags::_Alignment::__right; - return true; - } - return false; -} -} // namespace __detail - -template -class _LIBCPP_TEMPLATE_VIS __parser_fill_align { -public: - // TODO FMT The standard doesn't specify this character is a Unicode - // character. Validate what fmt and MSVC have implemented. - _CharT __fill{_CharT(' ')}; - -protected: - _LIBCPP_HIDE_FROM_ABI constexpr const _CharT* - __parse(const _CharT* __begin, const _CharT* __end, _Flags& __flags) { - _LIBCPP_ASSERT(__begin != __end, - "When called with an empty input the function will cause " - "undefined behavior by evaluating data not in the input"); - if (__begin + 1 != __end) { - if (__detail::__parse_alignment(*(__begin + 1), __flags)) { - if (*__begin == _CharT('{') || *__begin == _CharT('}')) - __throw_format_error( - "The format-spec fill field contains an invalid character"); - __fill = *__begin; - return __begin + 2; - } - } - - if (__detail::__parse_alignment(*__begin, __flags)) - return __begin + 1; - - return __begin; - } -}; - -template -_LIBCPP_HIDE_FROM_ABI constexpr const _CharT* -__parse_sign(const _CharT* __begin, _Flags& __flags) noexcept { - switch (*__begin) { - case _CharT('-'): - __flags.__sign = _Flags::_Sign::__minus; - break; - case _CharT('+'): - __flags.__sign = _Flags::_Sign::__plus; - break; - case _CharT(' '): - __flags.__sign = _Flags::_Sign::__space; - break; - default: - return __begin; - } - return __begin + 1; -} - -template -_LIBCPP_HIDE_FROM_ABI constexpr const _CharT* -__parse_alternate_form(const _CharT* __begin, _Flags& __flags) noexcept { - if (*__begin == _CharT('#')) { - __flags.__alternate_form = true; - ++__begin; - } - - return __begin; -} - -template -_LIBCPP_HIDE_FROM_ABI constexpr const _CharT* -__parse_zero_padding(const _CharT* __begin, _Flags& __flags) noexcept { - if (*__begin == _CharT('0')) { - __flags.__zero_padding = true; - ++__begin; - } - - return __begin; -} - template _LIBCPP_HIDE_FROM_ABI constexpr __format::__parse_number_result< _CharT> __parse_arg_id(const _CharT* __begin, const _CharT* __end, auto& __parse_ctx) { @@ -226,7 +64,7 @@ __parse_arg_id(const _CharT* __begin, const _CharT* __end, auto& __parse_ctx) { template _LIBCPP_HIDE_FROM_ABI constexpr uint32_t -__substitute_arg_id(basic_format_arg<_Context> _Arg) { +__substitute_arg_id(basic_format_arg<_Context> __format_arg) { return visit_format_arg( [](auto __arg) -> uint32_t { using _Type = decltype(__arg); @@ -250,685 +88,9 @@ __substitute_arg_id(basic_format_arg<_Context> _Arg) { __throw_format_error("A format-spec arg-id replacement argument " "isn't an integral type"); }, - _Arg); -} - -class _LIBCPP_TYPE_VIS __parser_width { -public: - /** Contains a width or an arg-id. */ - uint32_t __width : 31 {0}; - /** Determines whether the value stored is a width or an arg-id. */ - uint32_t __width_as_arg : 1 {0}; - - /** - * Does the supplied width field contain an arg-id? - * - * If @c true the formatter needs to call @ref __substitute_width_arg_id. - */ - constexpr bool __width_needs_substitution() const noexcept { return __width_as_arg; } - -protected: - /** - * Does the supplied std-format-spec contain a width field? - * - * When the field isn't present there's no padding required. This can be used - * to optimize the formatting. - */ - constexpr bool __has_width_field() const noexcept { return __width_as_arg || __width; } - - template - _LIBCPP_HIDE_FROM_ABI constexpr const _CharT* - __parse(const _CharT* __begin, const _CharT* __end, auto& __parse_ctx) { - if (*__begin == _CharT('0')) - __throw_format_error( - "A format-spec width field shouldn't have a leading zero"); - - if (*__begin == _CharT('{')) { - __format::__parse_number_result __r = - __parse_arg_id(++__begin, __end, __parse_ctx); - __width = __r.__value; - __width_as_arg = 1; - return __r.__ptr; - } - - if (*__begin < _CharT('0') || *__begin > _CharT('9')) - return __begin; - - __format::__parse_number_result __r = - __format::__parse_number(__begin, __end); - __width = __r.__value; - _LIBCPP_ASSERT(__width != 0, - "A zero value isn't allowed and should be impossible, " - "due to validations in this function"); - return __r.__ptr; - } - - _LIBCPP_HIDE_FROM_ABI constexpr void __substitute_width_arg_id(auto __arg) { - _LIBCPP_ASSERT(__width_as_arg == 1, - "Substitute width called when no substitution is required"); - - // The clearing of the flag isn't required but looks better when debugging - // the code. - __width_as_arg = 0; - __width = __substitute_arg_id(__arg); - if (__width == 0) - __throw_format_error( - "A format-spec width field replacement should have a positive value"); - } -}; - -class _LIBCPP_TYPE_VIS __parser_precision { -public: - /** Contains a precision or an arg-id. */ - uint32_t __precision : 31 {__format::__number_max}; - /** - * Determines whether the value stored is a precision or an arg-id. - * - * @note Since @ref __precision == @ref __format::__number_max is a valid - * value, the default value contains an arg-id of INT32_MAX. (This number of - * arguments isn't supported by compilers.) This is used to detect whether - * the std-format-spec contains a precision field. - */ - uint32_t __precision_as_arg : 1 {1}; - - /** - * Does the supplied precision field contain an arg-id? - * - * If @c true the formatter needs to call @ref __substitute_precision_arg_id. - */ - constexpr bool __precision_needs_substitution() const noexcept { - return __precision_as_arg && __precision != __format::__number_max; - } - -protected: - /** - * Does the supplied std-format-spec contain a precision field? - * - * When the field isn't present there's no truncating required. This can be - * used to optimize the formatting. - */ - constexpr bool __has_precision_field() const noexcept { - - return __precision_as_arg == 0 || // Contains a value? - __precision != __format::__number_max; // The arg-id is valid? - } - - template - _LIBCPP_HIDE_FROM_ABI constexpr const _CharT* - __parse(const _CharT* __begin, const _CharT* __end, auto& __parse_ctx) { - if (*__begin != _CharT('.')) - return __begin; - - ++__begin; - if (__begin == __end) - __throw_format_error("End of input while parsing format-spec precision"); - - if (*__begin == _CharT('{')) { - __format::__parse_number_result __arg_id = - __parse_arg_id(++__begin, __end, __parse_ctx); - _LIBCPP_ASSERT(__arg_id.__value != __format::__number_max, - "Unsupported number of arguments, since this number of " - "arguments is used a special value"); - __precision = __arg_id.__value; - return __arg_id.__ptr; - } - - if (*__begin < _CharT('0') || *__begin > _CharT('9')) - __throw_format_error( - "The format-spec precision field doesn't contain a value or arg-id"); - - __format::__parse_number_result __r = - __format::__parse_number(__begin, __end); - __precision = __r.__value; - __precision_as_arg = 0; - return __r.__ptr; - } - - _LIBCPP_HIDE_FROM_ABI constexpr void __substitute_precision_arg_id( - auto __arg) { - _LIBCPP_ASSERT( - __precision_as_arg == 1 && __precision != __format::__number_max, - "Substitute precision called when no substitution is required"); - - // The clearing of the flag isn't required but looks better when debugging - // the code. - __precision_as_arg = 0; - __precision = __substitute_arg_id(__arg); - } -}; - -template -_LIBCPP_HIDE_FROM_ABI constexpr const _CharT* -__parse_locale_specific_form(const _CharT* __begin, _Flags& __flags) noexcept { - if (*__begin == _CharT('L')) { - __flags.__locale_specific_form = true; - ++__begin; - } - - return __begin; -} - -template -_LIBCPP_HIDE_FROM_ABI constexpr const _CharT* -__parse_type(const _CharT* __begin, _Flags& __flags) { - - // Determines the type. It does not validate whether the selected type is - // valid. Most formatters have optional fields that are only allowed for - // certain types. These parsers need to do validation after the type has - // been parsed. So its easier to implement the validation for all types in - // the specific parse function. - switch (*__begin) { - case 'A': - __flags.__type = _Flags::_Type::__float_hexadecimal_upper_case; - break; - case 'B': - __flags.__type = _Flags::_Type::__binary_upper_case; - break; - case 'E': - __flags.__type = _Flags::_Type::__scientific_upper_case; - break; - case 'F': - __flags.__type = _Flags::_Type::__fixed_upper_case; - break; - case 'G': - __flags.__type = _Flags::_Type::__general_upper_case; - break; - case 'X': - __flags.__type = _Flags::_Type::__hexadecimal_upper_case; - break; - case 'a': - __flags.__type = _Flags::_Type::__float_hexadecimal_lower_case; - break; - case 'b': - __flags.__type = _Flags::_Type::__binary_lower_case; - break; - case 'c': - __flags.__type = _Flags::_Type::__char; - break; - case 'd': - __flags.__type = _Flags::_Type::__decimal; - break; - case 'e': - __flags.__type = _Flags::_Type::__scientific_lower_case; - break; - case 'f': - __flags.__type = _Flags::_Type::__fixed_lower_case; - break; - case 'g': - __flags.__type = _Flags::_Type::__general_lower_case; - break; - case 'o': - __flags.__type = _Flags::_Type::__octal; - break; - case 'p': - __flags.__type = _Flags::_Type::__pointer; - break; - case 's': - __flags.__type = _Flags::_Type::__string; - break; - case 'x': - __flags.__type = _Flags::_Type::__hexadecimal_lower_case; - break; - default: - return __begin; - } - return ++__begin; -} - -/** - * Process the parsed alignment and zero-padding state of arithmetic types. - * - * [format.string.std]/13 - * If the 0 character and an align option both appear, the 0 character is - * ignored. - * - * For the formatter a @ref __default alignment means zero-padding. - */ -_LIBCPP_HIDE_FROM_ABI constexpr void __process_arithmetic_alignment(_Flags& __flags) { - __flags.__zero_padding &= __flags.__alignment == _Flags::_Alignment::__default; - if (!__flags.__zero_padding && __flags.__alignment == _Flags::_Alignment::__default) - __flags.__alignment = _Flags::_Alignment::__right; + __format_arg); } -/** - * The parser for the std-format-spec. - * - * [format.string.std]/1 specifies the std-format-spec: - * fill-and-align sign # 0 width precision L type - * - * All these fields are optional. Whether these fields can be used depend on: - * - The type supplied to the format string. - * E.g. A string never uses the sign field so the field may not be set. - * This constrain is validated by the parsers in this file. - * - The supplied value for the optional type field. - * E.g. A int formatted as decimal uses the sign field. - * When formatted as a char the sign field may no longer be set. - * This constrain isn't validated by the parsers in this file. - * - * The base classes are ordered to minimize the amount of padding. - * - * This implements the parser for the string types. - */ -template -class _LIBCPP_TEMPLATE_VIS __parser_string - : public __parser_width, // provides __width(|as_arg) - public __parser_precision, // provides __precision(|as_arg) - public __parser_fill_align<_CharT>, // provides __fill and uses __flags - public _Flags // provides __flags -{ -public: - using char_type = _CharT; - - _LIBCPP_HIDE_FROM_ABI constexpr __parser_string() { - this->__alignment = _Flags::_Alignment::__left; - } - - /** - * The low-level std-format-spec parse function. - * - * @pre __begin points at the beginning of the std-format-spec. This means - * directly after the ':'. - * @pre The std-format-spec parses the entire input, or the first unmatched - * character is a '}'. - * - * @returns The iterator pointing at the last parsed character. - */ - _LIBCPP_HIDE_FROM_ABI constexpr auto parse(auto& __parse_ctx) - -> decltype(__parse_ctx.begin()) { - auto __it = __parse(__parse_ctx); - __process_display_type(); - return __it; - } - -private: - /** - * Parses the std-format-spec. - * - * @throws __throw_format_error When @a __parse_ctx contains an ill-formed - * std-format-spec. - * - * @returns An iterator to the end of input or point at the closing '}'. - */ - _LIBCPP_HIDE_FROM_ABI constexpr auto __parse(auto& __parse_ctx) - -> decltype(__parse_ctx.begin()) { - - auto __begin = __parse_ctx.begin(); - auto __end = __parse_ctx.end(); - if (__begin == __end) - return __begin; - - __begin = __parser_fill_align<_CharT>::__parse(__begin, __end, - static_cast<_Flags&>(*this)); - if (__begin == __end) - return __begin; - - __begin = __parser_width::__parse(__begin, __end, __parse_ctx); - if (__begin == __end) - return __begin; - - __begin = __parser_precision::__parse(__begin, __end, __parse_ctx); - if (__begin == __end) - return __begin; - - __begin = __parse_type(__begin, static_cast<_Flags&>(*this)); - - if (__begin != __end && *__begin != _CharT('}')) - __throw_format_error( - "The format-spec should consume the input or end with a '}'"); - - return __begin; - } - - /** Processes the parsed std-format-spec based on the parsed display type. */ - _LIBCPP_HIDE_FROM_ABI constexpr void __process_display_type() { - switch (this->__type) { - case _Flags::_Type::__default: - case _Flags::_Type::__string: - break; - - default: - __throw_format_error("The format-spec type has a type not supported for " - "a string argument"); - } - } -}; - -/** - * The parser for the std-format-spec. - * - * This implements the parser for the integral types. This includes the - * character type and boolean type. - * - * See @ref __parser_string. - */ -template -class _LIBCPP_TEMPLATE_VIS __parser_integral - : public __parser_width, // provides __width(|as_arg) - public __parser_fill_align<_CharT>, // provides __fill and uses __flags - public _Flags // provides __flags -{ -public: - using char_type = _CharT; - -protected: - /** - * The low-level std-format-spec parse function. - * - * @pre __begin points at the beginning of the std-format-spec. This means - * directly after the ':'. - * @pre The std-format-spec parses the entire input, or the first unmatched - * character is a '}'. - * - * @returns The iterator pointing at the last parsed character. - */ - _LIBCPP_HIDE_FROM_ABI constexpr auto __parse(auto& __parse_ctx) - -> decltype(__parse_ctx.begin()) { - auto __begin = __parse_ctx.begin(); - auto __end = __parse_ctx.end(); - if (__begin == __end) - return __begin; - - __begin = __parser_fill_align<_CharT>::__parse(__begin, __end, - static_cast<_Flags&>(*this)); - if (__begin == __end) - return __begin; - - __begin = __parse_sign(__begin, static_cast<_Flags&>(*this)); - if (__begin == __end) - return __begin; - - __begin = __parse_alternate_form(__begin, static_cast<_Flags&>(*this)); - if (__begin == __end) - return __begin; - - __begin = __parse_zero_padding(__begin, static_cast<_Flags&>(*this)); - if (__begin == __end) - return __begin; - - __begin = __parser_width::__parse(__begin, __end, __parse_ctx); - if (__begin == __end) - return __begin; - - __begin = - __parse_locale_specific_form(__begin, static_cast<_Flags&>(*this)); - if (__begin == __end) - return __begin; - - __begin = __parse_type(__begin, static_cast<_Flags&>(*this)); - - if (__begin != __end && *__begin != _CharT('}')) - __throw_format_error( - "The format-spec should consume the input or end with a '}'"); - - return __begin; - } - - /** Handles the post-parsing updates for the integer types. */ - _LIBCPP_HIDE_FROM_ABI constexpr void __handle_integer() noexcept { - __process_arithmetic_alignment(static_cast<_Flags&>(*this)); - } - - /** - * Handles the post-parsing updates for the character types. - * - * Sets the alignment and validates the format flags set for a character type. - * - * At the moment the validation for a character and a Boolean behave the - * same, but this may change in the future. - * Specifically at the moment the locale-specific form is allowed for the - * char output type, but it has no effect on the output. - */ - _LIBCPP_HIDE_FROM_ABI constexpr void __handle_char() { __handle_bool(); } - - /** - * Handles the post-parsing updates for the Boolean types. - * - * Sets the alignment and validates the format flags set for a Boolean type. - */ - _LIBCPP_HIDE_FROM_ABI constexpr void __handle_bool() { - if (this->__sign != _Flags::_Sign::__default) - __throw_format_error("A sign field isn't allowed in this format-spec"); - - if (this->__alternate_form) - __throw_format_error( - "An alternate form field isn't allowed in this format-spec"); - - if (this->__zero_padding) - __throw_format_error( - "A zero-padding field isn't allowed in this format-spec"); - - if (this->__alignment == _Flags::_Alignment::__default) - this->__alignment = _Flags::_Alignment::__left; - } -}; - -/** - * The parser for the std-format-spec. - * - * This implements the parser for the floating-point types. - * - * See @ref __parser_string. - */ -template -class _LIBCPP_TEMPLATE_VIS __parser_floating_point - : public __parser_width, // provides __width(|as_arg) - public __parser_precision, // provides __precision(|as_arg) - public __parser_fill_align<_CharT>, // provides __fill and uses __flags - public _Flags // provides __flags -{ -public: - using char_type = _CharT; - - /** - * The low-level std-format-spec parse function. - * - * @pre __begin points at the beginning of the std-format-spec. This means - * directly after the ':'. - * @pre The std-format-spec parses the entire input, or the first unmatched - * character is a '}'. - * - * @returns The iterator pointing at the last parsed character. - */ - _LIBCPP_HIDE_FROM_ABI constexpr auto parse(auto& __parse_ctx) - -> decltype(__parse_ctx.begin()) { - auto __it = __parse(__parse_ctx); - __process_arithmetic_alignment(static_cast<_Flags&>(*this)); - __process_display_type(); - return __it; - } -protected: - /** - * The low-level std-format-spec parse function. - * - * @pre __begin points at the beginning of the std-format-spec. This means - * directly after the ':'. - * @pre The std-format-spec parses the entire input, or the first unmatched - * character is a '}'. - * - * @returns The iterator pointing at the last parsed character. - */ - _LIBCPP_HIDE_FROM_ABI constexpr auto __parse(auto& __parse_ctx) - -> decltype(__parse_ctx.begin()) { - auto __begin = __parse_ctx.begin(); - auto __end = __parse_ctx.end(); - if (__begin == __end) - return __begin; - - __begin = __parser_fill_align<_CharT>::__parse(__begin, __end, - static_cast<_Flags&>(*this)); - if (__begin == __end) - return __begin; - - __begin = __parse_sign(__begin, static_cast<_Flags&>(*this)); - if (__begin == __end) - return __begin; - - __begin = __parse_alternate_form(__begin, static_cast<_Flags&>(*this)); - if (__begin == __end) - return __begin; - - __begin = __parse_zero_padding(__begin, static_cast<_Flags&>(*this)); - if (__begin == __end) - return __begin; - - __begin = __parser_width::__parse(__begin, __end, __parse_ctx); - if (__begin == __end) - return __begin; - - __begin = __parser_precision::__parse(__begin, __end, __parse_ctx); - if (__begin == __end) - return __begin; - - __begin = - __parse_locale_specific_form(__begin, static_cast<_Flags&>(*this)); - if (__begin == __end) - return __begin; - - __begin = __parse_type(__begin, static_cast<_Flags&>(*this)); - - if (__begin != __end && *__begin != _CharT('}')) - __throw_format_error( - "The format-spec should consume the input or end with a '}'"); - - return __begin; - } - - /** Processes the parsed std-format-spec based on the parsed display type. */ - _LIBCPP_HIDE_FROM_ABI constexpr void __process_display_type() { - switch (this->__type) { - case _Flags::_Type::__default: - // When no precision specified then it keeps default since that - // formatting differs from the other types. - if (this->__has_precision_field()) - this->__type = _Flags::_Type::__general_lower_case; - break; - case _Flags::_Type::__float_hexadecimal_lower_case: - case _Flags::_Type::__float_hexadecimal_upper_case: - // Precision specific behavior will be handled later. - break; - case _Flags::_Type::__scientific_lower_case: - case _Flags::_Type::__scientific_upper_case: - case _Flags::_Type::__fixed_lower_case: - case _Flags::_Type::__fixed_upper_case: - case _Flags::_Type::__general_lower_case: - case _Flags::_Type::__general_upper_case: - if (!this->__has_precision_field()) { - // Set the default precision for the call to to_chars. - this->__precision = 6; - this->__precision_as_arg = false; - } - break; - - default: - __throw_format_error("The format-spec type has a type not supported for " - "a floating-point argument"); - } - } -}; - -/** - * The parser for the std-format-spec. - * - * This implements the parser for the pointer types. - * - * See @ref __parser_string. - */ -template -class _LIBCPP_TEMPLATE_VIS __parser_pointer : public __parser_width, // provides __width(|as_arg) - public __parser_fill_align<_CharT>, // provides __fill and uses __flags - public _Flags // provides __flags -{ -public: - using char_type = _CharT; - - _LIBCPP_HIDE_FROM_ABI constexpr __parser_pointer() { - // Implements LWG3612 Inconsistent pointer alignment in std::format. - // The issue's current status is "Tentatively Ready" and libc++ status is - // still experimental. - // - // TODO FMT Validate this with the final resolution of LWG3612. - this->__alignment = _Flags::_Alignment::__right; - } - - /** - * The low-level std-format-spec parse function. - * - * @pre __begin points at the beginning of the std-format-spec. This means - * directly after the ':'. - * @pre The std-format-spec parses the entire input, or the first unmatched - * character is a '}'. - * - * @returns The iterator pointing at the last parsed character. - */ - _LIBCPP_HIDE_FROM_ABI constexpr auto parse(auto& __parse_ctx) -> decltype(__parse_ctx.begin()) { - auto __it = __parse(__parse_ctx); - __process_display_type(); - return __it; - } - -protected: - /** - * The low-level std-format-spec parse function. - * - * @pre __begin points at the beginning of the std-format-spec. This means - * directly after the ':'. - * @pre The std-format-spec parses the entire input, or the first unmatched - * character is a '}'. - * - * @returns The iterator pointing at the last parsed character. - */ - _LIBCPP_HIDE_FROM_ABI constexpr auto __parse(auto& __parse_ctx) -> decltype(__parse_ctx.begin()) { - auto __begin = __parse_ctx.begin(); - auto __end = __parse_ctx.end(); - if (__begin == __end) - return __begin; - - __begin = __parser_fill_align<_CharT>::__parse(__begin, __end, static_cast<_Flags&>(*this)); - if (__begin == __end) - return __begin; - - // An integer presentation type isn't defined in the Standard. - // Since a pointer is formatted as an integer it can be argued it's an - // integer presentation type. However there are two LWG-issues asserting it - // isn't an integer presentation type: - // - LWG3612 Inconsistent pointer alignment in std::format - // - LWG3644 std::format does not define "integer presentation type" - // - // There's a paper to make additional clarifications on the status of - // formatting pointers and proposes additional fields to be valid. That - // paper hasn't been reviewed by the Committee yet. - // - P2510 Formatting pointers - // - // The current implementation assumes formatting pointers isn't covered by - // "integer presentation type". - // TODO FMT Apply the LWG-issues/papers after approval/rejection by the Committee. - - __begin = __parser_width::__parse(__begin, __end, __parse_ctx); - if (__begin == __end) - return __begin; - - __begin = __parse_type(__begin, static_cast<_Flags&>(*this)); - - if (__begin != __end && *__begin != _CharT('}')) - __throw_format_error("The format-spec should consume the input or end with a '}'"); - - return __begin; - } - - /** Processes the parsed std-format-spec based on the parsed display type. */ - _LIBCPP_HIDE_FROM_ABI constexpr void __process_display_type() { - switch (this->__type) { - case _Flags::_Type::__default: - this->__type = _Flags::_Type::__pointer; - break; - case _Flags::_Type::__pointer: - break; - default: - __throw_format_error("The format-spec type has a type not supported for a pointer argument"); - } - } -}; - /** Helper struct returned from @ref __get_string_alignment. */ template struct _LIBCPP_TEMPLATE_VIS __string_alignment { @@ -1406,6 +568,13 @@ inline constexpr __fields __fields_integral{ .__zero_padding_ = true, .__locale_specific_form_ = true, .__type_ = true}; +inline constexpr __fields __fields_floating_point{ + .__sign_ = true, + .__alternate_form_ = true, + .__zero_padding_ = true, + .__precision_ = true, + .__locale_specific_form_ = true, + .__type_ = true}; inline constexpr __fields __fields_string{.__precision_ = true, .__type_ = true}; inline constexpr __fields __fields_pointer{.__type_ = true}; @@ -1871,18 +1040,10 @@ _LIBCPP_HIDE_FROM_ABI constexpr void __process_display_type_char(__parser<_CharT __format_spec::__process_display_type_bool_string(__parser); } -template -_LIBCPP_HIDE_FROM_ABI constexpr void __process_display_type_integer(__parser<_CharT>& __parser) { - if (__parser.__alignment_ == __alignment::__default) - __parser.__alignment_ = __alignment::__right; -} - template _LIBCPP_HIDE_FROM_ABI constexpr void __process_parsed_bool(__parser<_CharT>& __parser) { switch (__parser.__type_) { case __format_spec::__type::__default: - __parser.__type_ = __format_spec::__type::__string; - [[fallthrough]]; case __format_spec::__type::__string: __format_spec::__process_display_type_bool_string(__parser); break; @@ -1893,7 +1054,6 @@ _LIBCPP_HIDE_FROM_ABI constexpr void __process_parsed_bool(__parser<_CharT>& __p case __format_spec::__type::__decimal: case __format_spec::__type::__hexadecimal_lower_case: case __format_spec::__type::__hexadecimal_upper_case: - __process_display_type_integer(__parser); break; default: @@ -1905,8 +1065,6 @@ template _LIBCPP_HIDE_FROM_ABI constexpr void __process_parsed_char(__parser<_CharT>& __parser) { switch (__parser.__type_) { case __format_spec::__type::__default: - __parser.__type_ = __format_spec::__type::__char; - [[fallthrough]]; case __format_spec::__type::__char: __format_spec::__process_display_type_char(__parser); break; @@ -1917,7 +1075,6 @@ _LIBCPP_HIDE_FROM_ABI constexpr void __process_parsed_char(__parser<_CharT>& __p case __format_spec::__type::__decimal: case __format_spec::__type::__hexadecimal_lower_case: case __format_spec::__type::__hexadecimal_upper_case: - __format_spec::__process_display_type_integer(__parser); break; default: @@ -1929,15 +1086,12 @@ template _LIBCPP_HIDE_FROM_ABI constexpr void __process_parsed_integer(__parser<_CharT>& __parser) { switch (__parser.__type_) { case __format_spec::__type::__default: - __parser.__type_ = __format_spec::__type::__decimal; - [[fallthrough]]; case __format_spec::__type::__binary_lower_case: case __format_spec::__type::__binary_upper_case: case __format_spec::__type::__octal: case __format_spec::__type::__decimal: case __format_spec::__type::__hexadecimal_lower_case: case __format_spec::__type::__hexadecimal_upper_case: - __format_spec::__process_display_type_integer(__parser); break; case __format_spec::__type::__char: @@ -1949,6 +1103,35 @@ _LIBCPP_HIDE_FROM_ABI constexpr void __process_parsed_integer(__parser<_CharT>& } } +template +_LIBCPP_HIDE_FROM_ABI constexpr void __process_parsed_floating_point(__parser<_CharT>& __parser) { + switch (__parser.__type_) { + case __format_spec::__type::__default: + // When no precision specified then it keeps default since that + // formatting differs from the other types. + if (__parser.__precision_as_arg_ || __parser.__precision_ != -1) + __parser.__type_ = __format_spec::__type::__general_lower_case; + break; + case __format_spec::__type::__hexfloat_lower_case: + case __format_spec::__type::__hexfloat_upper_case: + // Precision specific behavior will be handled later. + break; + case __format_spec::__type::__scientific_lower_case: + case __format_spec::__type::__scientific_upper_case: + case __format_spec::__type::__fixed_lower_case: + case __format_spec::__type::__fixed_upper_case: + case __format_spec::__type::__general_lower_case: + case __format_spec::__type::__general_upper_case: + if (!__parser.__precision_as_arg_ && __parser.__precision_ == -1) + // Set the default precision for the call to to_chars. + __parser.__precision_ = 6; + break; + + default: + std::__throw_format_error("The format-spec type has a type not supported for a floating-point argument"); + } +} + _LIBCPP_HIDE_FROM_ABI constexpr void __process_display_type_pointer(__format_spec::__type __type) { switch (__type) { case __format_spec::__type::__default: diff --git a/contrib/llvm-project/libcxx/include/__functional/default_searcher.h b/contrib/llvm-project/libcxx/include/__functional/default_searcher.h index 05fb23d7c3c4..8e37082b6bed 100644 --- a/contrib/llvm-project/libcxx/include/__functional/default_searcher.h +++ b/contrib/llvm-project/libcxx/include/__functional/default_searcher.h @@ -12,6 +12,7 @@ #include <__algorithm/search.h> #include <__config> +#include <__functional/identity.h> #include <__functional/operations.h> #include <__iterator/iterator_traits.h> #include <__utility/pair.h> @@ -38,16 +39,15 @@ public: pair<_ForwardIterator2, _ForwardIterator2> operator () (_ForwardIterator2 __f, _ForwardIterator2 __l) const { - return _VSTD::__search(__f, __l, __first_, __last_, __pred_, - typename iterator_traits<_ForwardIterator>::iterator_category(), - typename iterator_traits<_ForwardIterator2>::iterator_category()); + auto __proj = __identity(); + return std::__search_impl(__f, __l, __first_, __last_, __pred_, __proj, __proj); } private: _ForwardIterator __first_; _ForwardIterator __last_; _BinaryPredicate __pred_; - }; +}; #endif // _LIBCPP_STD_VER > 14 diff --git a/contrib/llvm-project/libcxx/include/__functional/function.h b/contrib/llvm-project/libcxx/include/__functional/function.h index 312443b67c3b..db3af6e24101 100644 --- a/contrib/llvm-project/libcxx/include/__functional/function.h +++ b/contrib/llvm-project/libcxx/include/__functional/function.h @@ -390,9 +390,9 @@ template class __value_func<_Rp(_ArgTypes...)> typedef __base<_Rp(_ArgTypes...)> __func; __func* __f_; - _LIBCPP_NO_CFI static __func* __as_base(void* p) + _LIBCPP_NO_CFI static __func* __as_base(void* __p) { - return reinterpret_cast<__func*>(p); + return reinterpret_cast<__func*>(__p); } public: diff --git a/contrib/llvm-project/libcxx/include/__hash_table b/contrib/llvm-project/libcxx/include/__hash_table index 20223014432f..6123a310ad63 100644 --- a/contrib/llvm-project/libcxx/include/__hash_table +++ b/contrib/llvm-project/libcxx/include/__hash_table @@ -178,16 +178,14 @@ struct __hash_key_value_types<__hash_value_type<_Key, _Tp> > { template _LIBCPP_INLINE_VISIBILITY - static typename enable_if<__is_same_uncvref<_Up, __node_value_type>::value, - __container_value_type const&>::type + static __enable_if_t<__is_same_uncvref<_Up, __node_value_type>::value, __container_value_type const&> __get_value(_Up& __t) { return __t.__get_value(); } template _LIBCPP_INLINE_VISIBILITY - static typename enable_if<__is_same_uncvref<_Up, __container_value_type>::value, - __container_value_type const&>::type + static __enable_if_t<__is_same_uncvref<_Up, __container_value_type>::value, __container_value_type const&> __get_value(_Up& __t) { return __t; } @@ -1049,10 +1047,8 @@ public: template _LIBCPP_INLINE_VISIBILITY - typename enable_if< - __can_extract_map_key<_First, key_type, __container_value_type>::value, - pair - >::type __emplace_unique(_First&& __f, _Second&& __s) { + __enable_if_t<__can_extract_map_key<_First, key_type, __container_value_type>::value, pair > + __emplace_unique(_First&& __f, _Second&& __s) { return __emplace_unique_key_args(__f, _VSTD::forward<_First>(__f), _VSTD::forward<_Second>(__s)); } @@ -1096,9 +1092,7 @@ public: return __emplace_unique_key_args(_NodeTypes::__get_key(__x), _VSTD::move(__x)); } - template ::value - >::type> + template ::value> > _LIBCPP_INLINE_VISIBILITY pair __insert_unique(_Pp&& __x) { return __emplace_unique(_VSTD::forward<_Pp>(__x)); @@ -1152,9 +1146,16 @@ public: #endif void clear() _NOEXCEPT; - void rehash(size_type __n); - _LIBCPP_INLINE_VISIBILITY void reserve(size_type __n) - {rehash(static_cast(ceil(__n / max_load_factor())));} + _LIBCPP_INLINE_VISIBILITY void __rehash_unique(size_type __n) { __rehash(__n); } + _LIBCPP_INLINE_VISIBILITY void __rehash_multi(size_type __n) { __rehash(__n); } + _LIBCPP_INLINE_VISIBILITY void __reserve_unique(size_type __n) + { + __rehash_unique(static_cast(ceil(__n / max_load_factor()))); + } + _LIBCPP_INLINE_VISIBILITY void __reserve_multi(size_type __n) + { + __rehash_multi(static_cast(ceil(__n / max_load_factor()))); + } _LIBCPP_INLINE_VISIBILITY size_type bucket_count() const _NOEXCEPT @@ -1291,7 +1292,8 @@ public: #endif // _LIBCPP_ENABLE_DEBUG_MODE private: - void __rehash(size_type __n); + template void __rehash(size_type __n); + template void __do_rehash(size_type __n); template __node_holder __construct_node(_Args&& ...__args); @@ -1796,7 +1798,7 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::__node_insert_unique_prepare( } if (size()+1 > __bc * max_load_factor() || __bc == 0) { - rehash(_VSTD::max(2 * __bc + !__is_hash_power2(__bc), + __rehash_unique(_VSTD::max(2 * __bc + !__is_hash_power2(__bc), size_type(ceil(float(size() + 1) / max_load_factor())))); } return nullptr; @@ -1868,7 +1870,7 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::__node_insert_multi_prepare( size_type __bc = bucket_count(); if (size()+1 > __bc * max_load_factor() || __bc == 0) { - rehash(_VSTD::max(2 * __bc + !__is_hash_power2(__bc), + __rehash_multi(_VSTD::max(2 * __bc + !__is_hash_power2(__bc), size_type(ceil(float(size() + 1) / max_load_factor())))); __bc = bucket_count(); } @@ -1962,7 +1964,7 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::__node_insert_multi( size_type __bc = bucket_count(); if (size()+1 > __bc * max_load_factor() || __bc == 0) { - rehash(_VSTD::max(2 * __bc + !__is_hash_power2(__bc), + __rehash_multi(_VSTD::max(2 * __bc + !__is_hash_power2(__bc), size_type(ceil(float(size() + 1) / max_load_factor())))); __bc = bucket_count(); } @@ -2010,7 +2012,7 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::__emplace_unique_key_args(_Key const& __node_holder __h = __construct_node_hash(__hash, _VSTD::forward<_Args>(__args)...); if (size()+1 > __bc * max_load_factor() || __bc == 0) { - rehash(_VSTD::max(2 * __bc + !__is_hash_power2(__bc), + __rehash_unique(_VSTD::max(2 * __bc + !__is_hash_power2(__bc), size_type(ceil(float(size() + 1) / max_load_factor())))); __bc = bucket_count(); __chash = __constrain_hash(__hash, __bc); @@ -2213,8 +2215,9 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::__node_handle_merge_multi( #endif // _LIBCPP_STD_VER > 14 template +template void -__hash_table<_Tp, _Hash, _Equal, _Alloc>::rehash(size_type __n) +__hash_table<_Tp, _Hash, _Equal, _Alloc>::__rehash(size_type __n) _LIBCPP_DISABLE_UBSAN_UNSIGNED_INTEGER_CHECK { if (__n == 1) @@ -2223,7 +2226,7 @@ _LIBCPP_DISABLE_UBSAN_UNSIGNED_INTEGER_CHECK __n = __next_prime(__n); size_type __bc = bucket_count(); if (__n > __bc) - __rehash(__n); + __do_rehash<_UniqueKeys>(__n); else if (__n < __bc) { __n = _VSTD::max @@ -2233,13 +2236,14 @@ _LIBCPP_DISABLE_UBSAN_UNSIGNED_INTEGER_CHECK __next_prime(size_t(ceil(float(size()) / max_load_factor()))) ); if (__n < __bc) - __rehash(__n); + __do_rehash<_UniqueKeys>(__n); } } template +template void -__hash_table<_Tp, _Hash, _Equal, _Alloc>::__rehash(size_type __nbc) +__hash_table<_Tp, _Hash, _Equal, _Alloc>::__do_rehash(size_type __nbc) { std::__debug_db_invalidate_all(this); __pointer_allocator& __npa = __bucket_list_.get_deleter().__alloc(); @@ -2274,11 +2278,14 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::__rehash(size_type __nbc) else { __next_pointer __np = __cp; - for (; __np->__next_ != nullptr && - key_eq()(__cp->__upcast()->__value_, - __np->__next_->__upcast()->__value_); - __np = __np->__next_) - ; + if _LIBCPP_CONSTEXPR_AFTER_CXX14 (!_UniqueKeys) + { + for (; __np->__next_ != nullptr && + key_eq()(__cp->__upcast()->__value_, + __np->__next_->__upcast()->__value_); + __np = __np->__next_) + ; + } __pp->__next_ = __np->__next_; __np->__next_ = __bucket_list_[__chash]->__next_; __bucket_list_[__chash]->__next_ = __cp; diff --git a/contrib/llvm-project/libcxx/include/__iterator/back_insert_iterator.h b/contrib/llvm-project/libcxx/include/__iterator/back_insert_iterator.h index 7bbf5b09e0e5..e9f9f2abec2a 100644 --- a/contrib/llvm-project/libcxx/include/__iterator/back_insert_iterator.h +++ b/contrib/llvm-project/libcxx/include/__iterator/back_insert_iterator.h @@ -46,11 +46,11 @@ public: typedef _Container container_type; _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX17 explicit back_insert_iterator(_Container& __x) : container(_VSTD::addressof(__x)) {} - _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX17 back_insert_iterator& operator=(const typename _Container::value_type& __value_) - {container->push_back(__value_); return *this;} + _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX17 back_insert_iterator& operator=(const typename _Container::value_type& __value) + {container->push_back(__value); return *this;} #ifndef _LIBCPP_CXX03_LANG - _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX17 back_insert_iterator& operator=(typename _Container::value_type&& __value_) - {container->push_back(_VSTD::move(__value_)); return *this;} + _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX17 back_insert_iterator& operator=(typename _Container::value_type&& __value) + {container->push_back(_VSTD::move(__value)); return *this;} #endif // _LIBCPP_CXX03_LANG _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX17 back_insert_iterator& operator*() {return *this;} _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX17 back_insert_iterator& operator++() {return *this;} diff --git a/contrib/llvm-project/libcxx/include/__iterator/front_insert_iterator.h b/contrib/llvm-project/libcxx/include/__iterator/front_insert_iterator.h index 69b2d32d077a..9c8ec0028298 100644 --- a/contrib/llvm-project/libcxx/include/__iterator/front_insert_iterator.h +++ b/contrib/llvm-project/libcxx/include/__iterator/front_insert_iterator.h @@ -46,11 +46,11 @@ public: typedef _Container container_type; _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 explicit front_insert_iterator(_Container& __x) : container(_VSTD::addressof(__x)) {} - _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 front_insert_iterator& operator=(const typename _Container::value_type& __value_) - {container->push_front(__value_); return *this;} + _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 front_insert_iterator& operator=(const typename _Container::value_type& __value) + {container->push_front(__value); return *this;} #ifndef _LIBCPP_CXX03_LANG - _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 front_insert_iterator& operator=(typename _Container::value_type&& __value_) - {container->push_front(_VSTD::move(__value_)); return *this;} + _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 front_insert_iterator& operator=(typename _Container::value_type&& __value) + {container->push_front(_VSTD::move(__value)); return *this;} #endif // _LIBCPP_CXX03_LANG _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 front_insert_iterator& operator*() {return *this;} _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 front_insert_iterator& operator++() {return *this;} diff --git a/contrib/llvm-project/libcxx/include/__iterator/insert_iterator.h b/contrib/llvm-project/libcxx/include/__iterator/insert_iterator.h index 8b313f2a85bb..b35d8bf16af9 100644 --- a/contrib/llvm-project/libcxx/include/__iterator/insert_iterator.h +++ b/contrib/llvm-project/libcxx/include/__iterator/insert_iterator.h @@ -57,11 +57,11 @@ public: _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 insert_iterator(_Container& __x, __insert_iterator_iter_t<_Container> __i) : container(_VSTD::addressof(__x)), iter(__i) {} - _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 insert_iterator& operator=(const typename _Container::value_type& __value_) - {iter = container->insert(iter, __value_); ++iter; return *this;} + _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 insert_iterator& operator=(const typename _Container::value_type& __value) + {iter = container->insert(iter, __value); ++iter; return *this;} #ifndef _LIBCPP_CXX03_LANG - _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 insert_iterator& operator=(typename _Container::value_type&& __value_) - {iter = container->insert(iter, _VSTD::move(__value_)); ++iter; return *this;} + _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 insert_iterator& operator=(typename _Container::value_type&& __value) + {iter = container->insert(iter, _VSTD::move(__value)); ++iter; return *this;} #endif // _LIBCPP_CXX03_LANG _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 insert_iterator& operator*() {return *this;} _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 insert_iterator& operator++() {return *this;} diff --git a/contrib/llvm-project/libcxx/include/__iterator/iterator_traits.h b/contrib/llvm-project/libcxx/include/__iterator/iterator_traits.h index c3a5b7e0dd22..63525e230add 100644 --- a/contrib/llvm-project/libcxx/include/__iterator/iterator_traits.h +++ b/contrib/llvm-project/libcxx/include/__iterator/iterator_traits.h @@ -475,6 +475,18 @@ struct __is_exactly_cpp17_input_iterator __has_iterator_category_convertible_to<_Tp, input_iterator_tag>::value && !__has_iterator_category_convertible_to<_Tp, forward_iterator_tag>::value> {}; +template +struct __is_exactly_cpp17_forward_iterator + : public integral_constant::value && + !__has_iterator_category_convertible_to<_Tp, bidirectional_iterator_tag>::value> {}; + +template +struct __is_exactly_cpp17_bidirectional_iterator + : public integral_constant::value && + !__has_iterator_category_convertible_to<_Tp, random_access_iterator_tag>::value> {}; + template using __iter_value_type = typename iterator_traits<_InputIterator>::value_type; diff --git a/contrib/llvm-project/libcxx/include/__iterator/ostream_iterator.h b/contrib/llvm-project/libcxx/include/__iterator/ostream_iterator.h index 76ae4614939f..d16f5a26ebaa 100644 --- a/contrib/llvm-project/libcxx/include/__iterator/ostream_iterator.h +++ b/contrib/llvm-project/libcxx/include/__iterator/ostream_iterator.h @@ -53,9 +53,9 @@ public: : __out_stream_(_VSTD::addressof(__s)), __delim_(nullptr) {} _LIBCPP_INLINE_VISIBILITY ostream_iterator(ostream_type& __s, const _CharT* __delimiter) _NOEXCEPT : __out_stream_(_VSTD::addressof(__s)), __delim_(__delimiter) {} - _LIBCPP_INLINE_VISIBILITY ostream_iterator& operator=(const _Tp& __value_) + _LIBCPP_INLINE_VISIBILITY ostream_iterator& operator=(const _Tp& __value) { - *__out_stream_ << __value_; + *__out_stream_ << __value; if (__delim_) *__out_stream_ << __delim_; return *this; diff --git a/contrib/llvm-project/libcxx/include/__iterator/reverse_iterator.h b/contrib/llvm-project/libcxx/include/__iterator/reverse_iterator.h index 89bda19effef..a915609dbe33 100644 --- a/contrib/llvm-project/libcxx/include/__iterator/reverse_iterator.h +++ b/contrib/llvm-project/libcxx/include/__iterator/reverse_iterator.h @@ -15,15 +15,20 @@ #include <__compare/three_way_comparable.h> #include <__concepts/convertible_to.h> #include <__config> +#include <__iterator/advance.h> #include <__iterator/concepts.h> #include <__iterator/incrementable_traits.h> #include <__iterator/iter_move.h> #include <__iterator/iter_swap.h> #include <__iterator/iterator.h> #include <__iterator/iterator_traits.h> +#include <__iterator/next.h> #include <__iterator/prev.h> #include <__iterator/readable_traits.h> #include <__memory/addressof.h> +#include <__ranges/access.h> +#include <__ranges/concepts.h> +#include <__ranges/subrange.h> #include <__utility/move.h> #include @@ -136,7 +141,7 @@ public: #if _LIBCPP_STD_VER > 17 _LIBCPP_INLINE_VISIBILITY constexpr pointer operator->() const - requires is_pointer_v<_Iter> || requires(const _Iter i) { i.operator->(); } + requires is_pointer_v<_Iter> || requires(const _Iter __i) { __i.operator->(); } { if constexpr (is_pointer_v<_Iter>) { return std::prev(current); @@ -365,6 +370,16 @@ struct __rewrap_iter_impl<_ReverseWrapper<_OrigIter>, _UnwrappedIter> { } }; +#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES) +template +_LIBCPP_HIDE_FROM_ABI constexpr ranges:: + subrange>, reverse_iterator>> + __reverse_range(_Range&& __range) { + auto __first = ranges::begin(__range); + return {std::make_reverse_iterator(ranges::next(__first, ranges::end(__range))), std::make_reverse_iterator(__first)}; +} +#endif + _LIBCPP_END_NAMESPACE_STD #endif // _LIBCPP___ITERATOR_REVERSE_ITERATOR_H diff --git a/contrib/llvm-project/libcxx/include/__mutex_base b/contrib/llvm-project/libcxx/include/__mutex_base index da056b6d1423..ac0d090b7d19 100644 --- a/contrib/llvm-project/libcxx/include/__mutex_base +++ b/contrib/llvm-project/libcxx/include/__mutex_base @@ -338,11 +338,7 @@ private: template inline _LIBCPP_INLINE_VISIBILITY -typename enable_if -< - is_floating_point<_Rep>::value, - chrono::nanoseconds ->::type +__enable_if_t::value, chrono::nanoseconds> __safe_nanosecond_cast(chrono::duration<_Rep, _Period> __d) { using namespace chrono; @@ -365,11 +361,7 @@ __safe_nanosecond_cast(chrono::duration<_Rep, _Period> __d) template inline _LIBCPP_INLINE_VISIBILITY -typename enable_if -< - !is_floating_point<_Rep>::value, - chrono::nanoseconds ->::type +__enable_if_t::value, chrono::nanoseconds> __safe_nanosecond_cast(chrono::duration<_Rep, _Period> __d) { using namespace chrono; diff --git a/contrib/llvm-project/libcxx/include/__numeric/iota.h b/contrib/llvm-project/libcxx/include/__numeric/iota.h index b30e0e0a5484..b7127a11cb75 100644 --- a/contrib/llvm-project/libcxx/include/__numeric/iota.h +++ b/contrib/llvm-project/libcxx/include/__numeric/iota.h @@ -21,10 +21,10 @@ _LIBCPP_BEGIN_NAMESPACE_STD template _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 void -iota(_ForwardIterator __first, _ForwardIterator __last, _Tp __value_) +iota(_ForwardIterator __first, _ForwardIterator __last, _Tp __value) { - for (; __first != __last; ++__first, (void) ++__value_) - *__first = __value_; + for (; __first != __last; ++__first, (void) ++__value) + *__first = __value; } _LIBCPP_END_NAMESPACE_STD diff --git a/contrib/llvm-project/libcxx/include/__random/piecewise_constant_distribution.h b/contrib/llvm-project/libcxx/include/__random/piecewise_constant_distribution.h index a33ab0720062..9c9e14b16d6e 100644 --- a/contrib/llvm-project/libcxx/include/__random/piecewise_constant_distribution.h +++ b/contrib/llvm-project/libcxx/include/__random/piecewise_constant_distribution.h @@ -43,8 +43,8 @@ public: param_type(); template - param_type(_InputIteratorB __fB, _InputIteratorB __lB, - _InputIteratorW __fW); + param_type(_InputIteratorB __f_b, _InputIteratorB __l_b, + _InputIteratorW __f_w); #ifndef _LIBCPP_CXX03_LANG template param_type(initializer_list __bl, _UnaryOperation __fw); @@ -94,10 +94,10 @@ public: piecewise_constant_distribution() {} template _LIBCPP_INLINE_VISIBILITY - piecewise_constant_distribution(_InputIteratorB __fB, - _InputIteratorB __lB, - _InputIteratorW __fW) - : __p_(__fB, __lB, __fW) {} + piecewise_constant_distribution(_InputIteratorB __f_b, + _InputIteratorB __l_b, + _InputIteratorW __f_w) + : __p_(__f_b, __l_b, __f_w) {} #ifndef _LIBCPP_CXX03_LANG template @@ -215,8 +215,8 @@ piecewise_constant_distribution<_RealType>::param_type::param_type() template template piecewise_constant_distribution<_RealType>::param_type::param_type( - _InputIteratorB __fB, _InputIteratorB __lB, _InputIteratorW __fW) - : __b_(__fB, __lB) + _InputIteratorB __f_b, _InputIteratorB __l_b, _InputIteratorW __f_w) + : __b_(__f_b, __l_b) { if (__b_.size() < 2) { @@ -229,8 +229,8 @@ piecewise_constant_distribution<_RealType>::param_type::param_type( else { __densities_.reserve(__b_.size() - 1); - for (size_t __i = 0; __i < __b_.size() - 1; ++__i, ++__fW) - __densities_.push_back(*__fW); + for (size_t __i = 0; __i < __b_.size() - 1; ++__i, ++__f_w) + __densities_.push_back(*__f_w); __init(); } } diff --git a/contrib/llvm-project/libcxx/include/__random/piecewise_linear_distribution.h b/contrib/llvm-project/libcxx/include/__random/piecewise_linear_distribution.h index e69ce9444072..05f00cef06ef 100644 --- a/contrib/llvm-project/libcxx/include/__random/piecewise_linear_distribution.h +++ b/contrib/llvm-project/libcxx/include/__random/piecewise_linear_distribution.h @@ -43,8 +43,8 @@ public: param_type(); template - param_type(_InputIteratorB __fB, _InputIteratorB __lB, - _InputIteratorW __fW); + param_type(_InputIteratorB __f_b, _InputIteratorB __l_b, + _InputIteratorW __f_w); #ifndef _LIBCPP_CXX03_LANG template param_type(initializer_list __bl, _UnaryOperation __fw); @@ -94,10 +94,10 @@ public: piecewise_linear_distribution() {} template _LIBCPP_INLINE_VISIBILITY - piecewise_linear_distribution(_InputIteratorB __fB, - _InputIteratorB __lB, - _InputIteratorW __fW) - : __p_(__fB, __lB, __fW) {} + piecewise_linear_distribution(_InputIteratorB __f_b, + _InputIteratorB __l_b, + _InputIteratorW __f_w) + : __p_(__f_b, __l_b, __f_w) {} #ifndef _LIBCPP_CXX03_LANG template @@ -219,8 +219,8 @@ piecewise_linear_distribution<_RealType>::param_type::param_type() template template piecewise_linear_distribution<_RealType>::param_type::param_type( - _InputIteratorB __fB, _InputIteratorB __lB, _InputIteratorW __fW) - : __b_(__fB, __lB) + _InputIteratorB __f_b, _InputIteratorB __l_b, _InputIteratorW __f_w) + : __b_(__f_b, __l_b) { if (__b_.size() < 2) { @@ -233,8 +233,8 @@ piecewise_linear_distribution<_RealType>::param_type::param_type( else { __densities_.reserve(__b_.size()); - for (size_t __i = 0; __i < __b_.size(); ++__i, ++__fW) - __densities_.push_back(*__fW); + for (size_t __i = 0; __i < __b_.size(); ++__i, ++__f_w) + __densities_.push_back(*__f_w); __init(); } } diff --git a/contrib/llvm-project/libcxx/include/__ranges/zip_view.h b/contrib/llvm-project/libcxx/include/__ranges/zip_view.h index 560452aa7c69..a8035bc79e12 100644 --- a/contrib/llvm-project/libcxx/include/__ranges/zip_view.h +++ b/contrib/llvm-project/libcxx/include/__ranges/zip_view.h @@ -488,10 +488,10 @@ struct __fn { _LIBCPP_HIDE_FROM_ABI constexpr auto operator()() const noexcept { return empty_view>{}; } template - _LIBCPP_HIDE_FROM_ABI constexpr auto operator()(_Ranges&&... rs) const - noexcept(noexcept(zip_view...>(std::forward<_Ranges>(rs)...))) - -> decltype(zip_view...>(std::forward<_Ranges>(rs)...)) { - return zip_view...>(std::forward<_Ranges>(rs)...); + _LIBCPP_HIDE_FROM_ABI constexpr auto operator()(_Ranges&&... __rs) const + noexcept(noexcept(zip_view...>(std::forward<_Ranges>(__rs)...))) + -> decltype(zip_view...>(std::forward<_Ranges>(__rs)...)) { + return zip_view...>(std::forward<_Ranges>(__rs)...); } }; diff --git a/contrib/llvm-project/libcxx/include/__split_buffer b/contrib/llvm-project/libcxx/include/__split_buffer index e484e70440c9..7409b51b1f96 100644 --- a/contrib/llvm-project/libcxx/include/__split_buffer +++ b/contrib/llvm-project/libcxx/include/__split_buffer @@ -118,19 +118,10 @@ public: void __construct_at_end(size_type __n); void __construct_at_end(size_type __n, const_reference __x); template - typename enable_if - < - __is_cpp17_input_iterator<_InputIter>::value && - !__is_cpp17_forward_iterator<_InputIter>::value, - void - >::type + __enable_if_t<__is_exactly_cpp17_input_iterator<_InputIter>::value> __construct_at_end(_InputIter __first, _InputIter __last); template - typename enable_if - < - __is_cpp17_forward_iterator<_ForwardIterator>::value, - void - >::type + __enable_if_t<__is_cpp17_forward_iterator<_ForwardIterator>::value> __construct_at_end(_ForwardIterator __first, _ForwardIterator __last); _LIBCPP_INLINE_VISIBILITY void __destruct_at_begin(pointer __new_begin) @@ -239,12 +230,7 @@ __split_buffer<_Tp, _Allocator>::__construct_at_end(size_type __n, const_referen template template -typename enable_if -< - __is_cpp17_input_iterator<_InputIter>::value && - !__is_cpp17_forward_iterator<_InputIter>::value, - void ->::type +__enable_if_t<__is_exactly_cpp17_input_iterator<_InputIter>::value> __split_buffer<_Tp, _Allocator>::__construct_at_end(_InputIter __first, _InputIter __last) { __alloc_rr& __a = this->__alloc(); @@ -267,11 +253,7 @@ __split_buffer<_Tp, _Allocator>::__construct_at_end(_InputIter __first, _InputIt template template -typename enable_if -< - __is_cpp17_forward_iterator<_ForwardIterator>::value, - void ->::type +__enable_if_t<__is_cpp17_forward_iterator<_ForwardIterator>::value> __split_buffer<_Tp, _Allocator>::__construct_at_end(_ForwardIterator __first, _ForwardIterator __last) { _ConstructTransaction __tx(&this->__end_, _VSTD::distance(__first, __last)); diff --git a/contrib/llvm-project/libcxx/include/__string/char_traits.h b/contrib/llvm-project/libcxx/include/__string/char_traits.h index 457a771b94cf..18ad67b28e16 100644 --- a/contrib/llvm-project/libcxx/include/__string/char_traits.h +++ b/contrib/llvm-project/libcxx/include/__string/char_traits.h @@ -802,9 +802,7 @@ __str_rfind(const _CharT *__p, _SizeT __sz, __pos += __n; else __pos = __sz; - const _CharT* __r = _VSTD::__find_end( - __p, __p + __pos, __s, __s + __n, _Traits::eq, - random_access_iterator_tag(), random_access_iterator_tag()); + const _CharT* __r = std::__find_end_classic(__p, __p + __pos, __s, __s + __n, _Traits::eq); if (__n > 0 && __r == __p + __pos) return __npos; return static_cast<_SizeT>(__r - __p); diff --git a/contrib/llvm-project/libcxx/include/__threading_support b/contrib/llvm-project/libcxx/include/__threading_support index 8f1efb7854b7..a7f0da972a8d 100644 --- a/contrib/llvm-project/libcxx/include/__threading_support +++ b/contrib/llvm-project/libcxx/include/__threading_support @@ -201,15 +201,15 @@ int __libcpp_condvar_destroy(__libcpp_condvar_t* __cv); // Execute once _LIBCPP_THREAD_ABI_VISIBILITY -int __libcpp_execute_once(__libcpp_exec_once_flag *flag, - void (*init_routine)()); +int __libcpp_execute_once(__libcpp_exec_once_flag *__flag, + void (*__init_routine)()); // Thread id _LIBCPP_THREAD_ABI_VISIBILITY -bool __libcpp_thread_id_equal(__libcpp_thread_id t1, __libcpp_thread_id t2); +bool __libcpp_thread_id_equal(__libcpp_thread_id __t1, __libcpp_thread_id __t2); _LIBCPP_THREAD_ABI_VISIBILITY -bool __libcpp_thread_id_less(__libcpp_thread_id t1, __libcpp_thread_id t2); +bool __libcpp_thread_id_less(__libcpp_thread_id __t1, __libcpp_thread_id __t2); // Thread _LIBCPP_THREAD_ABI_VISIBILITY @@ -347,22 +347,22 @@ int __libcpp_condvar_destroy(__libcpp_condvar_t *__cv) } // Execute once -int __libcpp_execute_once(__libcpp_exec_once_flag *flag, - void (*init_routine)()) { - return pthread_once(flag, init_routine); +int __libcpp_execute_once(__libcpp_exec_once_flag *__flag, + void (*__init_routine)()) { + return pthread_once(__flag, __init_routine); } // Thread id // Returns non-zero if the thread ids are equal, otherwise 0 -bool __libcpp_thread_id_equal(__libcpp_thread_id t1, __libcpp_thread_id t2) +bool __libcpp_thread_id_equal(__libcpp_thread_id __t1, __libcpp_thread_id __t2) { - return t1 == t2; + return __t1 == __t2; } // Returns non-zero if t1 < t2, otherwise 0 -bool __libcpp_thread_id_less(__libcpp_thread_id t1, __libcpp_thread_id t2) +bool __libcpp_thread_id_less(__libcpp_thread_id __t1, __libcpp_thread_id __t2) { - return t1 < t2; + return __t1 < __t2; } // Thread diff --git a/contrib/llvm-project/libcxx/include/__tree b/contrib/llvm-project/libcxx/include/__tree index e5dd1f4d45ea..8d8449706871 100644 --- a/contrib/llvm-project/libcxx/include/__tree +++ b/contrib/llvm-project/libcxx/include/__tree @@ -597,8 +597,7 @@ struct __tree_key_value_types<__value_type<_Key, _Tp> > { template _LIBCPP_INLINE_VISIBILITY - static typename enable_if<__is_same_uncvref<_Up, __container_value_type>::value, - key_type const&>::type + static __enable_if_t<__is_same_uncvref<_Up, __container_value_type>::value, key_type const&> __get_key(_Up& __t) { return __t.first; } @@ -611,8 +610,7 @@ struct __tree_key_value_types<__value_type<_Key, _Tp> > { template _LIBCPP_INLINE_VISIBILITY - static typename enable_if<__is_same_uncvref<_Up, __container_value_type>::value, - __container_value_type const&>::type + static __enable_if_t<__is_same_uncvref<_Up, __container_value_type>::value, __container_value_type const&> __get_value(_Up& __t) { return __t; } @@ -1175,10 +1173,8 @@ public: template _LIBCPP_INLINE_VISIBILITY - typename enable_if< - __can_extract_map_key<_First, key_type, __container_value_type>::value, - pair - >::type __emplace_unique(_First&& __f, _Second&& __s) { + __enable_if_t<__can_extract_map_key<_First, key_type, __container_value_type>::value, pair > + __emplace_unique(_First&& __f, _Second&& __s) { return __emplace_unique_key_args(__f, _VSTD::forward<_First>(__f), _VSTD::forward<_Second>(__s)); } @@ -1219,10 +1215,8 @@ public: template _LIBCPP_INLINE_VISIBILITY - typename enable_if< - __can_extract_map_key<_First, key_type, __container_value_type>::value, - iterator - >::type __emplace_hint_unique(const_iterator __p, _First&& __f, _Second&& __s) { + __enable_if_t<__can_extract_map_key<_First, key_type, __container_value_type>::value, iterator> + __emplace_hint_unique(const_iterator __p, _First&& __f, _Second&& __s) { return __emplace_hint_unique_key_args(__p, __f, _VSTD::forward<_First>(__f), _VSTD::forward<_Second>(__s)).first; @@ -1275,21 +1269,15 @@ public: return __emplace_hint_unique_key_args(__p, _NodeTypes::__get_key(__v), _VSTD::move(__v)).first; } - template ::type, - __container_value_type - >::value - >::type> + template ::type, __container_value_type>::value> > _LIBCPP_INLINE_VISIBILITY pair __insert_unique(_Vp&& __v) { return __emplace_unique(_VSTD::forward<_Vp>(__v)); } - template ::type, - __container_value_type - >::value - >::type> + template ::type, __container_value_type>::value> > _LIBCPP_INLINE_VISIBILITY iterator __insert_unique(const_iterator __p, _Vp&& __v) { return __emplace_hint_unique(__p, _VSTD::forward<_Vp>(__v)); diff --git a/contrib/llvm-project/libcxx/include/__tuple b/contrib/llvm-project/libcxx/include/__tuple index 6d13bb24c579..f85036e7af1d 100644 --- a/contrib/llvm-project/libcxx/include/__tuple +++ b/contrib/llvm-project/libcxx/include/__tuple @@ -30,14 +30,14 @@ using __enable_if_tuple_size_imp = _Tp; template struct _LIBCPP_TEMPLATE_VIS tuple_size<__enable_if_tuple_size_imp< const _Tp, - typename enable_if::value>::type, + __enable_if_t::value>, integral_constant)>>> : public integral_constant::value> {}; template struct _LIBCPP_TEMPLATE_VIS tuple_size<__enable_if_tuple_size_imp< volatile _Tp, - typename enable_if::value>::type, + __enable_if_t::value>, integral_constant)>>> : public integral_constant::value> {}; @@ -393,7 +393,7 @@ struct __tuple_sfinae_base { template